diff --git a/.gitmodules b/.gitmodules index b9c60f72a..6137eb9d2 100644 --- a/.gitmodules +++ b/.gitmodules @@ -39,3 +39,4 @@ [submodule "ref/meshoptimizer"] path = ref/meshoptimizer url = https://github.com/zeux/meshoptimizer.git + shallow = true diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index 96af5c0ed..1bb1bbafb 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -226,6 +226,17 @@ bool check_vk14(std::string const &Name) if (!check_text(gfx::preprocess_shader(gfx::shader_api::vulkan14, Name, "#define NO_MOTION_OUTPUT 1\n", {}, false, vk14_dir), "-V --target-env " + vulkan_env)) suc = false; } + // the compact vertex layout of EU07M models (vk14::vertex_kind::scene_compact), alone and with the multi draws, as the + // renderer puts the definitions before the sources (compact_kind and multidraw_kind of vulkan14indirect.cpp) + if (source.text.find("COMPACT_VERTEX") != std::string::npos) + { + std::cout << "done, compact vertices..." << std::flush; + for (std::string_view const defines : {"#define COMPACT_VERTEX\n", "#define MODEL_DRAWS\n#define COMPACT_VERTEX\n"}) + { + if (!check_text(gfx::preprocess_shader(gfx::shader_api::vulkan14, Name, std::string{defines}, {}, false, vk14_dir), "-V --target-env " + vulkan_env)) + suc = false; + } + } // the ray traced reflections (gfx.raytracing): the renderer puts the extensions and REFLECTION_RAYS before the sources // (vk14::binding_preamble()), the shaders which shade with light_common.glsl trace the rays if (source.text.find("REFLECTION_RAYS_ACTIVE") != std::string::npos) diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index 8da6b5a37..1dc56a582 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -262,7 +262,11 @@ it as EU07M: - The `iFlags`, the visibility range and the colours stay in the node and in the material slot. - `TP_FREESPOTLIGHT` → `LGHT`; `Light_On##` / `Light_Off##` → `LSLT`; `smokesource_*` → `EMIT`; an `anim:` animation → `LANM`; `TP_TEXT` → `LTXT`; `TP_STARS` → `STAR`. -- The indices are written as `u16` when a primitive has fewer than 65 536 vertices. +- The indices are written as `u16` when a primitive has at most 65 536 vertices (indices 0–65 535). +- The pass bits (0x30) guessed from a material when an E3D is loaded go neither into `legacy_flags` nor into the flags of + the primitive: the game guesses them again, with the real material. A vehicle's model is converted from the `.e3d` the + game makes of it, not from its `.t3d`. +- A replaceable skin `-k` drawn in the translucent pass (bit k−1 of the E3D flags) has the `translucent` flag in `MATL`. The other commands: `eu07 -eu07m dump ` (the content as text, clips included) and `eu07 -eu07m validate ` (a check of the file with the hash of its content). @@ -327,13 +331,20 @@ parts of a node without a track stay as in its TRS. cubic rotation. Before the first and past the last key a track holds its value. - **Time.** A clip goes by the simulation time from when it started, at its pace. A looped clip starts over past its duration, another stops at its end. A clip with flag 0x2 starts on its own the first time the instance is drawn. -- **In the game.** `TAnimModel::play_clip(name, pace)` starts a clip (the self-test command `clip [pace]`), and - `stop_clips()` stops them all. Each time the instance is drawn, `RaPrepare()` samples the clips playing and sets the transforms - of the nodes (`TSubModel::SetClipTransform()`, the animation `at_Clip`), as the other animations of an instance. The nodes the - clips move are flagged animated at load, so a model with clips isn't instanced. A clip moving the joints of a skin bends the - skinned parts (see "Skinning"). +- **In the game.** `TAnimModel::play_clip(name, pace)` starts a clip (the self-test command `clip [pace]`), the + name regardless of case, and `stop_clips()` stops them all: each is held at the moment it was stopped and goes on setting its + nodes, as apart from what an instance sets as it's drawn the nodes are kept by the submodels all the instances share. Each time + the instance is drawn, `RaPrepare()` samples the clips and sets the transforms of the nodes (`TSubModel::SetClipTransform()`, + the animation `at_Clip`) before the animations of the events: an animation event of the scenery moving a node (`rotate`, + `translate`...) takes it over from a clip, one which ended or was stopped included. The nodes the clips move are flagged + animated at load, so a model with clips isn't instanced. A clip moving the joints of a skin bends the skinned parts (see + "Skinning"). +- The TRS fields of a node with a matrix (`XFRM`) are only an approximation of it: the parts the tracks of a clip don't move are + taken from the decomposed matrix, so the node doesn't jump when a clip starts moving another part of it. - **Scenery event.** `event animation clip endevent` starts the clip from its beginning at the - pace (a clip playing starts over), and a pace of 0 stops the clips of the model; the nodes stay where the clips left them. A clip + pace (a clip playing starts over), and a pace of 0 stops the clips of the model; the nodes stay where the clips left them. The + name of the clip is matched regardless of case, as the names of submodels are. An event without a pace (`clip endevent`) + plays the clip at its own pace and gives `Bad event: ... gives no pace for clip` in the log. A clip the model hasn't gives `Bad event: ... can't find clip` in the log. This is a new form of the `animation` event, which the current release doesn't read; the forms before it (`rotate`, `translate`, `digital`, `.vmd`) read as they did. @@ -346,12 +357,15 @@ the code of a vehicle, later Lua or a gauge in the cab) doesn't matter. - **Bindings the game follows.** A joint (`JOIN` of a node): the value of the target turns a hinge (radians) or a screw, or moves a slider (metres) along the axis of the joint, from the transform of the node, within the limits of the joint when it has them; a - fixed or a ball joint leaves the node at rest. A clip (its index in `ACLP`): the value of the target is the share of the duration + fixed or a ball joint leaves the node at rest. The node is modelled at the `rest` value of the joint: the joint moves it by the + value less `rest` (the limits are values of the joint, as `rest` is). A clip (its index in `ACLP`): the value of the target is the share of the duration of the clip, 0 to 1, so the channel scrubs the clip without playing it. Bindings to variants and light slots are read but not followed yet. -- **In the game.** `TAnimModel::set_channel(name, value)` sets a channel (the self-test command `channel `). - Each time the instance is drawn, `RaPrepare()` sets the nodes from the channels, after the clips playing, so a channel overrides a - clip on the same node. A channel not set yet has its initial value. The nodes of the joints are flagged animated at load. +- **In the game.** `TAnimModel::set_channel(name, value)` sets a channel (the self-test command `channel `), + the name regardless of case. Only scenery events and the self-test set channels so far; a vehicle (`TDynamicObject`: its cab + controls, its state) has no hook to them yet. + Each time the instance is drawn, `RaPrepare()` sets the nodes from the channels, after the clips, so a channel overrides a + clip on the same node; an animation event of the scenery on the node takes over from both. A channel not set yet has its initial value. The nodes of the joints are flagged animated at load. - **Scenery event.** `event animation channel endevent` sets the channel. A channel the model hasn't gives `Bad event: ... can't find channel` in the log. A new form of the `animation` event, which the current release doesn't read. @@ -396,7 +410,10 @@ own. It applies to EU07M and E3D models alike. the shader (`instance_hides_part()` in `common.glsl`). - An instance shows the whole lit part or the whole dark one. Blinking and switching (`ls_On` / `ls_Off` / `ls_Blink`) change over at half the fade (opacity 0.5), not with the cross-fade of the draws instance by instance. Steady states look the same as without - the instancing. + the instancing. `ls_Dark` and `ls_Home` + change without the fade (`fVisible`) too. +- An instance with light colours of its own (`lightcolors` of its node) is drawn on its own: the colours go onto the shared + submodels as the instance is prepared, which the instances of a bucket don't each get. - Measured (Vulkan, 200 heads `s4ipcpb_dd`): with `gfx.gpucull 0` the frame 9.2 ms → 1.5–2.5 ms and 2400 → 16 draw calls, with `gfx.gpucull 1` 9.1 ms → 3.0 ms and 2410 → 26 draw calls. diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 974339fdb..072168fc0 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -15,6 +15,9 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "model/AnimModel.h" +#include +#include + #include "rendering/renderer.h" #include "model/MdlMngr.h" #include "simulation/simulation.h" @@ -569,6 +572,9 @@ void TAnimModel::update_instanceable_flag() { // gfx.instancedlights: the lights go with the matrix of each instance (instance_light_bits()), and the instanced walk // animates each instance (RaAnimate) and prepares the model with all the parts of the lights shown (RaPrepareInstanced) if( ( iNumLights != 0 ) && ( false == Global.gfx_instancedlights ) ) { ++s_rejected_lights; return; } + // light colours of its own (lightcolors of the node) go onto the shared submodels as the instance is prepared (RaPrepare), + // which the instances of a bucket don't each get: such an instance is drawn on its own + if( std::ranges::any_of( m_lightcolors, []( glm::vec3 const &Colour ) { return Colour.r >= 0.f; } ) ) { ++s_rejected_lights; return; } if( !m_animlist.empty() ) { ++s_rejected_animlist; return; } if( submodel_tree_blocks_instancing( pModel->Root ) ) { ++s_rejected_animated_submodel; return; } m_instanceable = true; @@ -755,14 +761,15 @@ void TAnimModel::RaPrepare() TSubModel::iVariantSeed = 0; TSubModel::pasText = &asText; // przekazanie tekstu do wyświetlacza (!!!! do przemyślenia) - for (auto entry : m_animlist) { - entry->PrepareModel(); - } + // the clips first, then the channels, as they may set the same nodes; an animation event of the scenery on a node (rotate, + // translate...) takes over from both, a clip which ended or was stopped included, as the later one set on the submodel counts apply_clips(); - // after the clips playing, as they may set the same nodes if( ( pModel != nullptr ) && ( false == pModel->channels().empty() ) ) { apply_channels(); } + for (auto entry : m_animlist) { + entry->PrepareModel(); + } } // the state of the lit and the dark part of a numbered light, as RaPrepare() shows them @@ -806,7 +813,11 @@ bool TAnimModel::play_clip( std::string_view const Name, float const Speed, floa if( pModel == nullptr ) { return false; } auto const &clips { pModel->clips() }; - auto const found { std::ranges::find( clips, Name, &animation::clip::name ) }; + // the name regardless of case, as the submodels are found by theirs + auto const same { [ Name ]( animation::clip const &Clip ) { + return std::ranges::equal( Clip.name, Name, []( char const Left, char const Right ) { + return std::tolower( static_cast( Left ) ) == std::tolower( static_cast( Right ) ); } ); } }; + auto const found { std::ranges::find_if( clips, same ) }; if( found == clips.end() ) { return false; } auto const index { static_cast( std::distance( clips.begin(), found ) ) }; std::erase_if( m_clips, [ index ]( clip_playing const &Playing ) { return Playing.clip == index; } ); @@ -819,7 +830,15 @@ bool TAnimModel::play_clip( std::string_view const Name, float const Speed, floa void TAnimModel::stop_clips() { - m_clips.clear(); + // the clips are held where they are, not dropped: the pose lives in the submodels the instances of the model share, so the + // nodes of this instance are set again for each of its draws (apply_clips()), or another instance playing a clip would leave + // them at rest + auto const now { Timer::GetTime() }; + for( auto &playing : m_clips ) { + if( false == playing.held.has_value() ) { + playing.held = ( now - playing.start ) * playing.speed; + } + } m_autoplaystarted = true; } @@ -827,7 +846,11 @@ bool TAnimModel::set_channel( std::string_view const Name, float const Value ) { if( pModel == nullptr ) { return false; } auto const &channels { pModel->channels() }; - auto const found { std::ranges::find( channels, Name, &animation::channel::name ) }; + // the name regardless of case, as the submodels are found by theirs + auto const same { [ Name ]( animation::channel const &Channel ) { + return std::ranges::equal( Channel.name, Name, []( char const Left, char const Right ) { + return std::tolower( static_cast( Left ) ) == std::tolower( static_cast( Right ) ); } ); } }; + auto const found { std::ranges::find_if( channels, same ) }; if( found == channels.end() ) { return false; } if( m_channels.size() != channels.size() ) { m_channels.resize( channels.size() ); @@ -886,7 +909,7 @@ void TAnimModel::apply_clips() { auto const count { pModel->submodel_count() }; for( auto const &playing : m_clips ) { auto const &clip { clips[ playing.clip ] }; - auto const time { animation::clip_time( clip, ( now - playing.start ) * playing.speed ) }; + auto const time { animation::clip_time( clip, playing.held.value_or( ( now - playing.start ) * playing.speed ) ) }; for( auto const &node : clip.nodes ) { if( ( node.node < 0 ) || ( node.node >= count ) ) { continue; } root[ node.node ].SetClipTransform( animation::local_transform( clip, node, time ) ); diff --git a/model/AnimModel.h b/model/AnimModel.h index c1920e19b..66ecad0b6 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -20,6 +20,8 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "scene/scenenode.h" +#include + const int iMaxNumLights = 8; float const DefaultDarkThresholdLevel { 0.325f }; @@ -193,7 +195,8 @@ public: // pace; a clip already playing starts over. with the time stopped (the editor) it holds the pose of From. false when the model has // no clip of the name bool play_clip( std::string_view Name, float Speed = 1.f, float From = 0.f ); - // stops the clips playing, the nodes they moved stay where they were last put till the next clip moves them + // stops the clips playing: each is held at the moment it was stopped, so the nodes stay where they were put, till a clip + // started on them or an animation event of the scenery moves them void stop_clips(); // sets the channel of the model (EU07M) with the name to Value, kept within its range; the joints and the clips it's bound to // follow the next time the instance is drawn. false when the model has no channel of the name @@ -249,6 +252,7 @@ public: std::size_t clip { 0 }; double start { 0.0 }; float speed { 1.f }; + std::optional held; // stopped (stop_clips()): the time into the clip it stays at }; std::vector m_clips; bool m_autoplaystarted { false }; // the clips of the model to play on their own were started diff --git a/model/Model3d.cpp b/model/Model3d.cpp index 9f4459973..f5dbef139 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -27,6 +27,8 @@ Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others #include "utilities/wholefile.h" #include +#include +#include //--------------------------------------------------------------------------- @@ -1525,9 +1527,10 @@ void TSubModel::create_geometry(std::size_t &Indexoffset, std::size_t &Vertexoff // since we're comparing squared radii, we need to square it back for correct results m_boundingradius *= m_boundingradius; auto const submodeloffset{offset(std::numeric_limits::max())}; - for (auto const &vertex : GfxRenderer->Vertices(m_geometry.handle)) + // the positions alone: the vertices of an EU07M model on Vulkan would be made and kept whole for it + for (auto const &position : GfxRenderer->Positions(m_geometry.handle)) { - squaredradius = glm::length2(submodeloffset + vertex.position); + squaredradius = glm::length2(submodeloffset + position); if (squaredradius > m_boundingradius) { m_boundingradius = squaredradius; @@ -1651,9 +1654,9 @@ float TSubModel::MaxY(float4x4 const &m) if (m_geometry.handle != null_handle) { - for (auto const &vertex : GfxRenderer->Vertices(m_geometry.handle)) + for (auto const &position : GfxRenderer->Positions(m_geometry.handle)) { - maxy = std::max(maxy, m[0][1] * vertex.position.x + m[1][1] * vertex.position.y + m[2][1] * vertex.position.z + m[3][1]); + maxy = std::max(maxy, m[0][1] * position.x + m[1][1] * position.y + m[2][1] * position.z + m[3][1]); } } else if (false == Vertices.empty()) @@ -1795,17 +1798,30 @@ glm::vec3 TSubModel::offset(float const Geometrytestoffsetthreshold) const // offset of zero generally means the submodel has optimized identity matrix // for such cases we resort to an estimate from submodel geometry // TODO: do proper bounding area calculation for submodel when loading mesh and grab the centre point from it here - auto const &vertices{(m_geometry.handle != null_handle ? GfxRenderer->Vertices(m_geometry.handle) : Vertices)}; - if (false == vertices.empty()) + // the positions alone: the vertices of an EU07M model on Vulkan would be made and kept whole for them + gfx::position_array positions; + if (m_geometry.handle != null_handle) + { + positions = GfxRenderer->Positions(m_geometry.handle); + } + else + { + positions.reserve(Vertices.size()); + for (auto const &vertex : Vertices) + { + positions.push_back(vertex.position); + } + } + if (false == positions.empty()) { // transformation matrix for the submodel can still contain rotation and/or scaling, // so we pass the vertex positions through it rather than just grab them directly offset = glm::vec3(); - auto const vertexfactor{1.f / vertices.size()}; + auto const vertexfactor{1.f / positions.size()}; auto const transformationmatrix{glm::make_mat4(parentmatrix.readArray())}; - for (auto const &vertex : vertices) + for (auto const &position : positions) { - offset += glm::vec3{transformationmatrix * glm::vec4{vertex.position, 1}} * vertexfactor; + offset += glm::vec3{transformationmatrix * glm::vec4{position, 1}} * vertexfactor; } } } @@ -1815,6 +1831,27 @@ glm::vec3 TSubModel::offset(float const Geometrytestoffsetthreshold) const namespace { +// modelformat eu07m: an .eu07m older than the .e3d / .t3d it was made from isn't used, the model was changed after it was +// converted (the hash of the source in its header would need the source read whole to be compared) +bool eu07m_up_to_date(std::string const &Eu07m, std::initializer_list const Sources) +{ + std::error_code error; + auto const made{std::filesystem::last_write_time(Eu07m, error)}; + if (error) + return false; + for (auto const &source : Sources) + { + if (source.empty()) + continue; + if (auto const changed{std::filesystem::last_write_time(source, error)}; (false == bool(error)) && (changed > made)) + { + WriteLog("Model \"" + source + "\" is newer than its \"" + Eu07m + "\", which isn't used", logtype::model); + return false; + } + } + return true; +} + // Fazy szczegółowości nazwane "_LOD" (części sieci trakcyjnej) dostają zakresy widoczności tutaj, // żeby nie trzeba było wpisywać ich w modelach: kolejne fazy zmieniają się na 20, 40, 100, 300 i 400 m, // a ostatnia faza, jaką część ma, zostaje widoczna do 400 m (drobnica: model mieszczący się w promieniu 0,5 m @@ -1916,7 +1953,8 @@ bool TModel3d::LoadFromFile(std::string const &FileName, bool dynamic) Init(); assign_lod_ranges(Root, name); } - else if (auto const eu07mfile{Global.modelformat_eu07m ? FileCased(name + ".eu07m") : std::string{}}; (false == eu07mfile.empty()) && LoadFromEU07M(eu07mfile, dynamic)) + else if (auto const eu07mfile{Global.modelformat_eu07m ? FileCased(name + ".eu07m") : std::string{}}; + (false == eu07mfile.empty()) && eu07m_up_to_date(eu07mfile, {binaryfile, textfile}) && LoadFromEU07M(eu07mfile, dynamic)) { // modelformat eu07m: the .eu07m made from the model takes its place; one which doesn't load leaves the .e3d / .t3d to go on asBinary = ""; @@ -2789,6 +2827,7 @@ void TSubModel::BinInit(TSubModel *s, float4x4 *m, std::vector *t, float opacity = mat->get_or_guess_opacity(); // set phase flag based on material opacity + m_passguessed = true; if (opacity == 0.0f) iFlags |= 0x20; // translucent else diff --git a/model/Model3d.h b/model/Model3d.h index ffcd1446a..da92b2ce2 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -110,6 +110,9 @@ public: // bit 13: =1 wystarczy przesunięcie zamiast mnożenia macierzy (trzy jedynki) // bit 14: =1 wymagane przechowanie macierzy (animacje) // bit 15: =1 wymagane przechowanie macierzy (transform niejedynkowy) + // the pass bits (0x30) weren't in the file but guessed on load from the material (BinInit); a converter keeps them out, + // so the guess is made again with the real material where the model is drawn + bool m_passguessed{false}; union { // transform, nie każdy submodel musi mieć float4x4 *fMatrix = nullptr; // pojedyncza precyzja wystarcza diff --git a/model/clip.cpp b/model/clip.cpp index 2013227f7..ae3e51e80 100644 --- a/model/clip.cpp +++ b/model/clip.cpp @@ -140,6 +140,8 @@ glm::mat4 joint_transform(joint_binding const &Joint, float const Value) { value = std::clamp(value, std::min(Joint.minimum, Joint.maximum), std::max(Joint.minimum, Joint.maximum)); } + // the node is modelled at the rest value of the joint: at that value it stays as modelled + value -= Joint.rest_value; auto const length{glm::length(Joint.axis)}; if (length <= 0.f) { diff --git a/model/clip.h b/model/clip.h index e6fe7f9fd..6b699ac2e 100644 --- a/model/clip.h +++ b/model/clip.h @@ -97,6 +97,7 @@ struct joint_binding float maximum{0.f}; float pitch{0.f}; // metres for each turn of a screw glm::mat4 rest{1.f}; // the transform of the node within its parent, which the joint moves from + float rest_value{0.f}; // the value of the joint the node is modelled at (JOIN.rest): the joint moves by the value less it }; enum class binding_target : std::uint8_t diff --git a/model/eu07m/eu07m_build.cpp b/model/eu07m/eu07m_build.cpp index 3d5519be3..7875996b3 100644 --- a/model/eu07m/eu07m_build.cpp +++ b/model/eu07m/eu07m_build.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "model/eu07m/eu07m_build.h" #include +#include #include #include @@ -62,11 +63,8 @@ std::unordered_map matrix_lookup(model const &Model) glm::mat4 node_transform(model const &Model, std::uint32_t const Node, std::unordered_map const &Matrices) { auto const &node{Model.nodes[Node]}; if ((node.flags & node_flags::matrix) != 0) { - if (auto const lookup{Matrices.find(Node)}; lookup != Matrices.end()) { - glm::mat4 matrix; - std::memcpy(&matrix[0][0], Model.transforms[lookup->second].matrix.data(), sizeof(float) * 16); - return matrix; - } + if (auto const lookup{Matrices.find(Node)}; lookup != Matrices.end()) + return glm::make_mat4(Model.transforms[lookup->second].matrix.data()); } return compose(node); } diff --git a/model/eu07m/eu07m_convert.cpp b/model/eu07m/eu07m_convert.cpp index 05ccea067..6b5b358a4 100644 --- a/model/eu07m/eu07m_convert.cpp +++ b/model/eu07m/eu07m_convert.cpp @@ -24,10 +24,13 @@ http://mozilla.org/MPL/2.0/. #include "utilities/wholefile.h" #include +#include #include #include #include +#include #include +#include namespace eu07m { @@ -69,8 +72,16 @@ class converter { model m_model; bool m_userdata{false}; std::vector m_stars; // the nodes whose STAR components wait for their meshes + std::unordered_map m_nodeof; // the node made of each submodel }; +// the pass bits of the submodel as they come from the model file: the ones BinInit guessed from a material are left out, so +// where the model is drawn the guess is made again with the real material (the converter loads through the null renderer, +// whose materials all guess opaque) +std::uint32_t file_flags(TSubModel const &Submodel) { + return Submodel.m_passguessed ? Submodel.iFlags & ~0x30u : Submodel.iFlags; +} + bool converter::any_userdata(TSubModel const *First) const { for (auto const *submodel{First}; submodel != nullptr; submodel = submodel->Next) { if (submodel->m_geometry.handle != null_handle && false == GfxRenderer->UserData(submodel->m_geometry.handle).empty()) @@ -101,7 +112,8 @@ void converter::node(TSubModel &Submodel, std::int32_t const Parent) { auto &record{m_model.nodes.back()}; record.name = Submodel.pName.empty() ? no_index : m_model.intern(Submodel.pName); record.parent = Parent; - record.legacy_flags = Submodel.iFlags; + record.legacy_flags = file_flags(Submodel); + m_nodeof.try_emplace(&Submodel, index); record.range_min_sq = Submodel.fSquareMinDist; record.range_max_sq = Submodel.fSquareMaxDist; if ((Submodel.iFlags & 0x4000) != 0) @@ -172,8 +184,12 @@ bool converter::has_geometry(TSubModel const &Submodel) { std::uint32_t converter::material(TSubModel const &Submodel) { material_record record; - if (Submodel.m_material < 0) + if (Submodel.m_material < 0) { record.replaceable = std::max(Submodel.m_material, -4); + // the pass of a replaceable skin: bit k-1 of the E3D flags for the skin -k + if ((Submodel.iFlags & (1u << (-record.replaceable - 1))) != 0) + record.flags |= material_flags::translucent; + } else if (false == Submodel.m_materialname.empty()) record.name = m_model.intern(Submodel.m_materialname); record.selfillum = Submodel.fLight; @@ -241,7 +257,8 @@ void converter::geometry(TSubModel const &Submodel, std::uint32_t const Node) { primitive.node = Node; primitive.material = material(Submodel); auto const kind{Submodel.eType == TP_STARS ? 0u : static_cast(Submodel.eType)}; - primitive.flags = kind | ((Submodel.iFlags & 0x10) != 0 ? primitive_flags::opaque : 0u) | ((Submodel.iFlags & 0x20) != 0 ? primitive_flags::translucent : 0u); + auto const flags{file_flags(Submodel)}; + primitive.flags = kind | ((flags & 0x10) != 0 ? primitive_flags::opaque : 0u) | ((flags & 0x20) != 0 ? primitive_flags::translucent : 0u); vertices(Submodel, vertexdata, GfxRenderer->UserData(Submodel.m_geometry.handle)); if (auto const &indexdata{GfxRenderer->Indices(Submodel.m_geometry.handle)}; false == indexdata.empty()) indices(Submodel, indexdata, primitive); @@ -261,22 +278,30 @@ void converter::geometry(TSubModel const &Submodel, std::uint32_t const Node) { void converter::light_slots() { // the numbered lights the lights event of the scenery switches (TModel3d::instance_parts) + // the submodel the game finds by the name (GetFromName, which looks at the following submodels before the children), so + // with two of one name the same one counts + auto const found{[this](std::string const &Name) -> std::optional { + auto const *submodel{m_source.GetFromName(Name)}; + if (submodel == nullptr) + return std::nullopt; + auto const lookup{m_nodeof.find(submodel)}; + return lookup == m_nodeof.end() ? std::nullopt : std::optional{lookup->second}; + }}; for (int slot = 0; slot < 8; ++slot) { - auto const on{find_nodes(m_model, std::format("Light_On{:02}", slot))}; - auto const off{find_nodes(m_model, std::format("Light_Off{:02}", slot))}; - if (on.empty() && off.empty()) + auto const on{found(std::format("Light_On{:02}", slot))}; + auto const off{found(std::format("Light_Off{:02}", slot))}; + if (false == on.has_value() && false == off.has_value()) continue; payload::light_slot record; record.slot = static_cast(slot); - // as GetFromName, the first submodel of the name counts - record.on_count = on.empty() ? 0 : 1; - record.off_count = off.empty() ? 0 : 1; + record.on_count = on.has_value() ? 1 : 0; + record.off_count = off.has_value() ? 1 : 0; payload_writer writer; writer.put(record); - if (false == on.empty()) - writer.put(on.front()); - if (false == off.empty()) - writer.put(off.front()); + if (on.has_value()) + writer.put(*on); + if (off.has_value()) + writer.put(*off); m_model.add_component(component::light_slot, target_kind::model, 0, writer.data()); } } @@ -306,10 +331,18 @@ bool load_source(std::string const &Input, bool const Dynamic, TModel3d &Source, return true; } -void start_tools(int const Argc, char *Argv[]) { - Global.iConvertModels = Argc > 6 ? std::stoi(Argv[6]) : 0; +bool start_tools(int const Argc, char *Argv[]) { + Global.iConvertModels = 0; + if (Argc > 6) { + auto const flags{std::string_view{Argv[6]}}; + if (auto const [end, error]{std::from_chars(flags.data(), flags.data() + flags.size(), Global.iConvertModels)}; error != std::errc{} || end != flags.data() + flags.size()) { + std::cerr << std::format("the convertmodels flags \"{}\" aren't a number\n", flags); + return false; + } + } Global.iWriteLogEnabled = 2; GfxRenderer = gfx_renderer_factory::get_instance()->create("null"); + return true; } // the differences between two loaded models, submodel by submodel in the order of the tree @@ -448,7 +481,8 @@ int command_diff(int const Argc, char *Argv[]) { std::cerr << "usage: -eu07m diff [dynamic 0|1]\n"; return 2; } - start_tools(Argc, Argv); + if (false == start_tools(Argc, Argv)) + return 2; auto const dynamic{Argc > 5 && std::string_view{Argv[5]} == "1"}; TModel3d source; TModel3d converted; @@ -475,7 +509,14 @@ int command_convert(int const Argc, char *Argv[]) { std::string const input{Argv[3]}; std::string const output{Argv[4]}; auto const dynamic{Argc > 5 && std::string_view{Argv[5]} == "1"}; - start_tools(Argc, Argv); + if (dynamic && extension_of(input) != ".e3d") { + // the game prepares a vehicle's text model only after the vehicle marked its animated parts (WillBeAnimated); made here + // at once, their vertices would be turned into the frame of the model instead of keeping their matrices + std::cerr << "a vehicle's model is converted from the .e3d the game makes of it (convertmodels), not from its .t3d\n"; + return 2; + } + if (false == start_tools(Argc, Argv)) + return 2; TModel3d source; if (false == load_source(input, dynamic, source)) return 1; diff --git a/model/eu07m/eu07m_io.cpp b/model/eu07m/eu07m_io.cpp index dabbb1eaa..a3c0edda9 100644 --- a/model/eu07m/eu07m_io.cpp +++ b/model/eu07m/eu07m_io.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "zstd.h" #include +#include #include #include #include @@ -23,6 +24,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include namespace eu07m { @@ -341,6 +343,8 @@ bool section_bytes::strings(std::vector &Output, std::string &Error // the largest section unpacked, so a broken file can't make the reader take all the memory constexpr std::uint64_t section_size_limit{std::uint64_t{1} << 30}; +// and the most all the sections of a model may unpack to together +constexpr std::uint64_t model_size_limit{std::uint64_t{2} << 30}; class file_reader { public: @@ -377,6 +381,8 @@ bool file_reader::read_header(file_header &Header) { return fail(std::format("the model has version {}.{}, this program reads version {}", Header.major, Header.minor, version_major)); if (Header.file_size > m_file.size()) return fail(std::format("the file is cut short: {} bytes of {}", m_file.size(), Header.file_size)); + if (Header.file_size < sizeof(file_header)) + return fail(std::format("the file claims {} bytes, less than its header", Header.file_size)); m_file = m_file.first(Header.file_size); if (m_options.verify_hash && hash_bytes(m_file.subspan(sizeof(file_header))) != Header.content_hash) return fail("the content of the file doesn't match its hash"); @@ -390,15 +396,19 @@ bool file_reader::read_entries(file_header const &Header, std::vector seen; + std::unordered_set seen; + seen.reserve(Entries.size()); + std::uint64_t total{0}; for (auto const &entry : Entries) { if (entry.offset > m_file.size() || entry.stored_size > m_file.size() - entry.offset) return fail(std::format("section {} lies outside the file", fourcc_name(entry.id))); if (entry.size > section_size_limit) return fail(std::format("section {} claims {} bytes", fourcc_name(entry.id), entry.size)); - if (std::ranges::find(seen, entry.id) != seen.end()) + if (false == seen.insert(entry.id).second) return fail(std::format("section {} appears twice", fourcc_name(entry.id))); - seen.push_back(entry.id); + total += entry.size; + if (total > model_size_limit) + return fail(std::format("the sections claim more than {} bytes together", model_size_limit)); } return true; } @@ -523,11 +533,18 @@ bool file_reader::read_streams(std::vector const &Sections, model std::vector streams; std::ranges::copy_if(Sections, std::back_inserter(streams), [](section_entry const &Entry) { return is_vertex_stream(Entry.id); }); std::vector errors(streams.size()); + // a stream which can't be had (its memory, say) is an error of the file like the others: an exception left in a thread + // of its own would end the program auto const unpack_one{[this, &streams, &errors, &Model](std::size_t const Index) { - file_reader worker{m_file, m_options}; - bool handled{false}; - if (false == worker.vertex_stream(streams[Index], Model, handled)) - errors[Index] = std::move(worker.m_error); + try { + file_reader worker{m_file, m_options}; + bool handled{false}; + if (false == worker.vertex_stream(streams[Index], Model, handled)) // NOSONAR: S2259 false positive, worker is a local object and no pointer is null here + errors[Index] = std::move(worker.m_error); + } + catch (std::exception const &Error) { + errors[Index] = std::format("section {} can't be unpacked: {}", fourcc_name(streams[Index].id), Error.what()); + } }}; { std::vector workers; @@ -543,6 +560,21 @@ bool file_reader::read_streams(std::vector const &Sections, model return true; } +// the sections this reader reads: every case of dispatch() below, kept in step with it (a section left out would be +// passed over by the game as one it doesn't know) +constexpr std::array known_sections{section::strings, section::name_index, section::nodes, section::transforms, + section::meshes, section::primitives, section::positions, section::attributes, + section::skin_weights, section::skin_weights_wide, section::userdata, section::bindings, + section::indices16, section::indices32, section::materials, section::skins, + section::skin_joints, section::vertex_groups, section::vertex_group_items, section::vertex_group_weights, + section::components, section::component_data, section::bounds, section::edit, + section::clips, section::clip_tracks, section::key_times, section::key_vectors, + section::key_rotations, section::geometry_references}; + +bool known_section(std::uint32_t const Id) { + return std::ranges::find(known_sections, Id) != known_sections.end(); +} + bool file_reader::dispatch(section_entry const &Entry, section_bytes const &Section, model &Model) { std::string error; bool known{true}; @@ -609,6 +641,17 @@ read_result file_reader::run(model &Model) { for (auto const &entry : sections) { if (is_vertex_stream(entry.id)) continue; + if (false == known_section(entry.id)) { + // a section this reader doesn't know: one the model needs is refused before its codec is looked at; one it can + // do without is passed over before it is unpacked, unless the tools keep it to write it back, and always when it + // is in the codec of the streams, which this reader unpacks only for the streams it knows + if ((entry.flags & section_flags::required) != 0) { + Model = model{}; + return {false, std::format("the model needs section {}, which this program doesn't know", fourcc_name(entry.id))}; + } + if (false == m_options.keep_unknown || (entry.flags & section_flags::meshopt) != 0) + continue; + } std::span bytes; if (false == unpack(entry, storage, bytes) || false == dispatch(entry, section_bytes{entry.id, bytes}, Model)) { Model = model{}; @@ -622,7 +665,7 @@ read_result file_reader::run(model &Model) { } } // the geometry kept in the store of the family goes back in its place in the streams - if (std::string error; false == insert_blocks(Model, m_options.blocks, error)) { + if (std::string error; false == insert_blocks(Model, m_options.blocks, error, m_options.verify_hash)) { Model = model{}; return {false, error}; } @@ -872,11 +915,16 @@ void validator::node(std::uint32_t const Index, node_record const &Node) { void validator::nodes() { for (std::uint32_t idx = 0; idx < m_model.nodes.size() && false == full(); ++idx) node(idx, m_model.nodes[idx]); - // a node within the subtree of another has it as an ancestor: the subtrees nest + // the subtrees nest, and the parent of each node is the innermost node whose subtree holds it, so the tree the ranges + // give is the one the parents give + std::vector open; for (std::uint32_t idx = 0; idx < m_model.nodes.size() && false == full(); ++idx) { - auto const parent{m_model.nodes[idx].parent}; - if (parent >= 0 && parent < static_cast(idx) && idx >= m_model.nodes[parent].subtree_end) - fault(std::format("node {} lies outside the subtree of its parent", idx)); + while (false == open.empty() && m_model.nodes[open.back()].subtree_end <= idx) + open.pop_back(); + auto const holder{open.empty() ? std::int64_t{-1} : std::int64_t{open.back()}}; + if (m_model.nodes[idx].parent != holder) + fault(std::format("node {} has parent {}, but lies in the subtree of node {}", idx, m_model.nodes[idx].parent, holder)); + open.push_back(idx); } } diff --git a/model/eu07m/eu07m_load.cpp b/model/eu07m/eu07m_load.cpp index b8538f826..130b611c5 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -15,14 +15,18 @@ http://mozilla.org/MPL/2.0/. #include "model/eu07m/eu07m_io.h" #include "rendering/renderer.h" #include "utilities/Logs.h" +#include "utilities/utilities.h" #include "utilities/wholefile.h" +#include #include #include #include #include +#include #include +#include #include #include #include @@ -145,6 +149,10 @@ void submodel_builder::build(std::uint32_t const Index, TSubModel &Submodel) { // 0 is no limit (a model made anew); a converted one carries the range of its E3D submodel. the submodel keeps its default Submodel.fSquareMaxDist = node.range_max_sq > 0.f ? node.range_max_sq : Submodel.fSquareMaxDist; transform(Index, Submodel); + // a model made anew has no E3D flags (legacy_flags 0): a node of it with a transform keeps it as one converted from E3D does + // (0x8000), or the walk and posed_transform() would leave it out, and with it the joints of the skins + if ((node.legacy_flags == 0) && (Submodel.iMatrix >= 0) && (m_transforms[Index] != glm::mat4{1.f})) + Submodel.iFlags |= 0x8000; auto const parts{parts_of(m_model, node)}; Submodel.b_Anim = parts.animation; Submodel.eType = TP_ROTATOR; @@ -334,12 +342,24 @@ void submodel_builder::fill_geometry() { // the biggest first, so the threads end at about the same time std::ranges::sort(m_jobs, std::ranges::greater{}, [](geometry_job const &Job) { return Job.primitive->vertex_count; }); std::atomic next{0}; - auto const work{[this, &next] { - while (true) { - auto const index{next.fetch_add(1)}; - if (index >= m_jobs.size()) - break; - fill(m_jobs[index]); + // the first exception of a worker (no memory for the vertices) is thrown again here, after all of them ended: left in a + // thread of its own it would end the program instead of the model falling back to its .e3d + std::exception_ptr failure; + std::mutex failurelock; + auto const work{[this, &next, &failure, &failurelock] { + try { + while (true) { + auto const index{next.fetch_add(1)}; + if (index >= m_jobs.size()) + break; + fill(m_jobs[index]); + } + } + catch (...) { + std::scoped_lock lock{failurelock}; + if (failure == nullptr) + failure = std::current_exception(); + next = m_jobs.size(); } }}; { @@ -349,6 +369,8 @@ void submodel_builder::fill_geometry() { workers.emplace_back(work); work(); } // the workers join here + if (failure != nullptr) + std::rethrow_exception(failure); } // the track of the file as the game samples it: the rotations unpacked, the vectors as glm @@ -381,6 +403,20 @@ animation::node_tracks &node_entry(animation::clip &Clip, eu07m::model const &Mo entry.rest_translation = {record.translation[0], record.translation[1], record.translation[2]}; entry.rest_rotation = glm::quat{record.rotation[3], record.rotation[0], record.rotation[1], record.rotation[2]}; entry.rest_scale = {record.scale[0], record.scale[1], record.scale[2]}; + if ((record.flags & eu07m::node_flags::matrix) != 0) { + // the TRS fields of a node with a matrix (XFRM) are only an approximation of it: the parts the tracks leave are taken from + // the matrix itself, so the node doesn't jump when a clip starts moving one of its parts + auto const matrix{eu07m::local_transform(Model, Node)}; + glm::vec3 scale{glm::length(glm::vec3{matrix[0]}), glm::length(glm::vec3{matrix[1]}), glm::length(glm::vec3{matrix[2]})}; + if (glm::determinant(glm::mat3{matrix}) < 0.f) + scale.x = -scale.x; // a mirroring matrix: the rotation stays a proper one + if ((scale.x != 0.f) && (scale.y != 0.f) && (scale.z != 0.f)) { + glm::mat3 const rotation{glm::vec3{matrix[0]} / scale.x, glm::vec3{matrix[1]} / scale.y, glm::vec3{matrix[2]} / scale.z}; + entry.rest_translation = glm::vec3{matrix[3]}; + entry.rest_rotation = glm::normalize(glm::quat_cast(rotation)); + entry.rest_scale = scale; + } + } return Clip.nodes.emplace_back(entry); } @@ -422,6 +458,7 @@ std::optional make_joint(eu07m::model const &Model, st result.maximum = joint.maximum; result.pitch = joint.pitch; result.rest = Locals[record.target]; + result.rest_value = joint.rest; return result; } @@ -472,10 +509,16 @@ bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) { } eu07m::model model; // the game has no use for the sections it doesn't know; the geometry shared by the family comes from the store of the folder - eu07m::read_options options{false, false}; - options.blocks = eu07m::store_source(eu07m::family_store(FileName)); - if (auto const result{eu07m::read(std::as_bytes(std::span{file.data.get(), file.size}), model, options)}; false == result.ok) { - ErrorLog("Bad model: \"" + FileName + "\" isn't a valid EU07M file: " + result.error, logtype::model); + try { + eu07m::read_options options{false, false}; + options.blocks = eu07m::store_source(eu07m::family_store(FileName)); + if (auto const result{eu07m::read(std::as_bytes(std::span{file.data.get(), file.size}), model, options)}; false == result.ok) { + ErrorLog("Bad model: \"" + FileName + "\" isn't a valid EU07M file: " + result.error, logtype::model); + return false; + } + } + catch (std::exception const &Error) { + ErrorLog("Bad model: \"" + FileName + "\" can't be read: " + Error.what(), logtype::model); return false; } if (model.nodes.empty()) { @@ -493,9 +536,21 @@ bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) { iSubModelsCount = static_cast(model.nodes.size()); Root = new TSubModel[model.nodes.size()]; submodel_builder builder{model, Textures, Names, Matrices}; - for (std::uint32_t idx = 0; idx < model.nodes.size(); ++idx) - builder.build(idx, Root[idx]); - builder.fill_geometry(); + try { + for (std::uint32_t idx = 0; idx < model.nodes.size(); ++idx) + builder.build(idx, Root[idx]); + builder.fill_geometry(); + } + catch (std::exception const &Error) { + // nothing of the model is kept, so its .e3d / .t3d is loaded in its place + SafeDeleteArray(Root); + iSubModelsCount = 0; + Textures.clear(); + Names.clear(); + Matrices.clear(); + ErrorLog("Bad model: \"" + FileName + "\" can't be built: " + Error.what(), logtype::model); + return false; + } // the skins, with their joints as the submodels of the nodes m_skins.clear(); for (auto const &record : model.skins) { diff --git a/model/eu07m/eu07m_pack.cpp b/model/eu07m/eu07m_pack.cpp index c808c9f5d..3e366e5c3 100644 --- a/model/eu07m/eu07m_pack.cpp +++ b/model/eu07m/eu07m_pack.cpp @@ -50,15 +50,24 @@ std::vector read_file(std::filesystem::path const &Path) { bool write_file(std::filesystem::path const &Path, std::span Data) { // next to it first, so a failed write leaves the file as it was auto const temporary{std::filesystem::path{Path}.concat(".tmp")}; + std::error_code error; { std::ofstream file{temporary, std::ios::binary}; file.write(reinterpret_cast(Data.data()), static_cast(Data.size())); - if (false == file.good()) + // closed before the check: what still sat in the buffer of the stream is written by the close + file.close(); + if (file.fail()) { + std::filesystem::remove(temporary, error); return false; + } } - std::error_code error; std::filesystem::rename(temporary, Path, error); - return false == bool(error); + if (error) { + std::error_code ignored; + std::filesystem::remove(temporary, ignored); + return false; + } + return true; } bool is_model(std::filesystem::directory_entry const &Entry) { @@ -167,6 +176,29 @@ bool write_checked(folder_model const &Item, model const &Packed, geometry_store return true; } +// the store of the folder made of the blocks it has (when it has one which can be read) and the new ones +bool write_bridge_store(std::filesystem::path const &Folder, std::vector> const &Blocks, std::ostream &Log) { + auto all{Blocks}; + std::error_code error; + if (auto const path{Folder / store_file_name}; std::filesystem::exists(path, error)) { + geometry_store old; + if (std::string reason; old.open(path, reason)) { + for (auto const &id : old.blocks()) { + if (std::vector block; old.block(id, block)) + all.push_back(std::move(block)); + } + } + else { + Log << std::format("the old store can't be read ({}), its blocks aren't kept\n", reason); + } + } + if (false == write_file(Folder / store_file_name, write_store(all))) { + Log << "can't write the store\n"; + return false; + } + return true; +} + } // namespace pack_result pack_folder(std::filesystem::path const &Folder, std::size_t const MinBytes, std::ostream &Log) { @@ -187,7 +219,11 @@ pack_result pack_folder(std::filesystem::path const &Folder, std::size_t const M Log << std::format("the store made isn't valid: {}\n", reason); return result; } - // the models first, each checked against the store; the store replaces the old one once they all are written + // first a store with the blocks of the old one and the new ones together: while the models are written one by one, the folder + // holds models packed against either, and a write failing half way leaves them all loading + if (false == write_bridge_store(Folder, blocks, Log)) + return result; + // then the models, each checked against the store; the store of the new blocks alone replaces the other once they all are for (auto const &item : models) { auto packed{item.loaded}; packed.geometry_references = references(packed, candidates, MinBytes); diff --git a/model/eu07m/eu07m_store.cpp b/model/eu07m/eu07m_store.cpp index f86871b44..a51bca2fd 100644 --- a/model/eu07m/eu07m_store.cpp +++ b/model/eu07m/eu07m_store.cpp @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "model/eu07m/eu07m_store.h" +#include "utilities/Logs.h" #include "zstd.h" #include @@ -76,9 +77,13 @@ std::size_t stream_offset(block_header const &Header, std::uint32_t const Bit) { return offset; } +// the largest block unpacked, so a broken index can't make the reader take all the memory +constexpr std::uint32_t block_size_limit{std::uint32_t{1} << 30}; + // whether the index of the store fits in a file of Size bytes and is sorted bool valid_index(std::vector const &Index, std::uint64_t const Size) { - return std::ranges::all_of(Index, [Size](store_entry const &Entry) { return Entry.offset + Entry.stored_size <= Size; }) && std::ranges::is_sorted(Index, {}, &store_entry::hash); + auto const fits{[Size](store_entry const &Entry) { return Entry.offset <= Size && Entry.stored_size <= Size - Entry.offset && Entry.size <= block_size_limit; }}; + return std::ranges::all_of(Index, fits) && std::ranges::is_sorted(Index, {}, &store_entry::hash); } bool valid_header(store_header const &Header, std::uint64_t const Size) { @@ -156,7 +161,7 @@ struct block_view { primitive_record primitive; }; -bool read_block(model const &Model, geometry_reference_record const &Reference, block_source const &Source, block_view &View, std::string &Error) { +bool read_block(model const &Model, geometry_reference_record const &Reference, block_source const &Source, bool const Verify, block_view &View, std::string &Error) { if (Reference.primitive >= Model.primitives.size()) { Error = std::format("a geometry reference names primitive {}, which the model hasn't", Reference.primitive); return false; @@ -166,7 +171,9 @@ bool read_block(model const &Model, geometry_reference_record const &Reference, Error = std::format("the geometry store hasn't the block of primitive {}", Reference.primitive); return false; } - if (View.bytes.size() < sizeof(block_header) || block_hash(View.bytes) != Reference.hash) { + // the block is found by its hash; its bytes are hashed again only when the content of the file is checked too (verify_hash), + // which the game doesn't do, as the store is read from the same disk as the model + if (View.bytes.size() < sizeof(block_header) || (Verify && block_hash(View.bytes) != Reference.hash)) { Error = std::format("the block of primitive {} in the geometry store isn't the one the model refers to", Reference.primitive); return false; } @@ -278,13 +285,13 @@ block_id block_hash(std::span const Block) { return {hash_bytes(Block), hash_bytes(Block, second_seed)}; } -bool insert_blocks(model &Model, block_source const &Source, std::string &Error) { +bool insert_blocks(model &Model, block_source const &Source, std::string &Error, bool const Verify) { if (Model.geometry_references.empty()) return true; std::vector blocks; blocks.reserve(Model.geometry_references.size()); for (auto const &reference : Model.geometry_references) { - if (false == read_block(Model, reference, Source, blocks.emplace_back(), Error)) + if (false == read_block(Model, reference, Source, Verify, blocks.emplace_back(), Error)) return false; } std::ranges::sort(blocks, {}, [](block_view const &Block) { return Block.primitive.base_vertex; }); @@ -450,24 +457,39 @@ block_source store_source(std::shared_ptr Store) { } std::shared_ptr family_store(std::filesystem::path const &ModelFile) { + // the store of a folder as it was opened: a file which changed since (packed anew while the game runs) is opened again, as + // its blocks are read from the file by the offsets of the index + struct cached { + std::shared_ptr store; + bool exists{false}; + std::uintmax_t size{0}; + std::filesystem::file_time_type time{}; + }; static std::mutex mutex; - static std::map> stores; + static std::map stores; auto path{ModelFile.parent_path() / store_file_name}; std::error_code error; if (auto canonical{std::filesystem::weakly_canonical(path, error)}; false == bool(error)) path = std::move(canonical); - std::scoped_lock lock{mutex}; - if (auto const found{stores.find(path)}; found != stores.end()) - return found->second; - std::shared_ptr result; - if (std::filesystem::exists(path, error)) { - auto store{std::make_shared()}; - std::string reason; - if (store->open(path, reason)) - result = std::move(store); + cached state; + state.exists = std::filesystem::exists(path, error); + if (state.exists) { + state.size = std::filesystem::file_size(path, error); + state.time = std::filesystem::last_write_time(path, error); } - stores.emplace(path, result); - return result; + std::scoped_lock lock{mutex}; + if (auto const found{stores.find(path)}; + found != stores.end() && found->second.exists == state.exists && found->second.size == state.size && found->second.time == state.time) + return found->second.store; + if (state.exists) { + auto store{std::make_shared()}; + if (std::string reason; store->open(path, reason)) + state.store = std::move(store); + else // once for the folder: its models which refer to the store then can't be read + ErrorLog("Bad model: the geometry store \"" + path.string() + "\" can't be used: " + reason, logtype::model); + } + stores.insert_or_assign(path, state); + return state.store; } } // namespace eu07m diff --git a/model/eu07m/eu07m_store.h b/model/eu07m/eu07m_store.h index f346a3c71..b094d090a 100644 --- a/model/eu07m/eu07m_store.h +++ b/model/eu07m/eu07m_store.h @@ -57,8 +57,9 @@ block_id block_hash(std::span Block); // gives the block of a reference; false when there's none using block_source = std::function &Block)>; // the blocks of the references of the model put back in the places of their primitives in the streams, which the file has without -// them. false with the reason when a block is missing or doesn't fit -bool insert_blocks(model &Model, block_source const &Source, std::string &Error); +// them. false with the reason when a block is missing or doesn't fit. Verify: the bytes of each block hashed again against the +// reference (the tools); the game finds the block by the hash and checks its counts only +bool insert_blocks(model &Model, block_source const &Source, std::string &Error, bool Verify = true); // the streams of the model without the ranges of the primitives it refers to, as the file keeps them model remove_referenced(model const &Model); diff --git a/model/skinning.cpp b/model/skinning.cpp index f20bdf3e3..4e346b8f4 100644 --- a/model/skinning.cpp +++ b/model/skinning.cpp @@ -58,15 +58,18 @@ std::vector palette(glm::mat4 const &Mesh, std::span return result; } -bool rest_pose(std::span const Palette, float const Tolerance) +bool rest_pose(std::span const Palette, float const Tolerance, float const Scale) { glm::mat4 const identity{1.f}; - return std::ranges::all_of(Palette, [&](glm::mat4 const &Matrix) { + // the translation is rounded in proportion to the distances the palette was made of + auto const translation{Tolerance * std::max(1.f, Scale)}; + return std::ranges::all_of(Palette, [&identity, Tolerance, translation](glm::mat4 const &Matrix) { for (int column = 0; column < 4; ++column) { + auto const limit{column == 3 ? translation : Tolerance}; for (int row = 0; row < 4; ++row) { - if (std::abs(Matrix[column][row] - identity[column][row]) > Tolerance) + if (std::abs(Matrix[column][row] - identity[column][row]) > limit) { return false; } @@ -76,6 +79,17 @@ bool rest_pose(std::span const Palette, float const Tolerance) }); } +float palette_scale(glm::mat4 const &Mesh, std::span const Joints) +{ + auto const reach{[](glm::mat4 const &Matrix) { return std::max({std::abs(Matrix[3][0]), std::abs(Matrix[3][1]), std::abs(Matrix[3][2])}); }}; + auto scale{reach(Mesh)}; + for (auto const &joint : Joints) + { + scale = std::max(scale, reach(joint)); + } + return scale; +} + namespace { @@ -102,6 +116,15 @@ glm::vec3 direction(glm::mat3 const &Rotation, glm::vec3 const &Vector) return length > 0.f ? moved / length : Vector; } +// what moves the normals: the inverse transpose of the rotation, here as its cofactors (the same direction, without the +// division), with the sign of the determinant so a mirroring matrix keeps the normals facing out. the rotation itself would +// tilt the normals of a part squashed by a scale +glm::mat3 normal_matrix(glm::mat3 const &Rotation) +{ + glm::mat3 const cofactors{glm::cross(Rotation[1], Rotation[2]), glm::cross(Rotation[2], Rotation[0]), glm::cross(Rotation[0], Rotation[1])}; + return glm::dot(Rotation[0], cofactors[0]) < 0.f ? -cofactors : cofactors; +} + } // namespace void skin_vertices(std::span const Rest, std::span const Weights, std::span const Palette, std::span const Out) @@ -119,7 +142,7 @@ void skin_vertices(std::span const Rest, std::span vertex_weights unpack(std::array co // Mesh and Joint posed from the root of the model, so the placement of the instance cancels out std::vector palette(glm::mat4 const &Mesh, std::span Joints, std::span InverseBind); -// true when every matrix of the palette leaves the vertices where they are (within Tolerance): the rest pose -bool rest_pose(std::span Palette, float Tolerance = 1e-5f); +// true when every matrix of the palette leaves the vertices where they are: the rest pose. the rotation within Tolerance, the +// translation within Tolerance times Scale (at least 1), the distance from the origin of what the palette was made of +// (palette_scale()), as the float chain rounds in proportion to it +bool rest_pose(std::span Palette, float Tolerance = 1e-5f, float Scale = 1.f); +// the largest distance from the origin along an axis of the mesh and the joints a palette is made of +float palette_scale(glm::mat4 const &Mesh, std::span Joints); // the vertices moved by the palette: positions by the blended matrix, normals and tangents by its rotation, renormalised. a joint out // of the palette counts as the identity. Out has as many vertices as Rest diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index c4a52d44e..033df86ba 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -1035,8 +1035,9 @@ void scene_walk::Queue_Instances( scene::basic_cell const *Cell ) } } if( m_instancecullpass && bucket_has_lights( instancebucket ) ) { - // the culling of the gpu takes the light states of the instances from their records - gfx::walk_sync::change change; + // the culling of the gpu takes the light states of the instances from their records. only the first pass of the frame has + // them to refresh (Refresh_Light_Records() checks again under the lock), so the others don't stop the walkers for it + gfx::walk_sync::change change { instancebucket.lightsframe != m_framestamp }; Refresh_Light_Records( instancebucket ); } if( buckettests && Bucket_Culled( instancebucket ) ) { diff --git a/rendering/common/skincache.cpp b/rendering/common/skincache.cpp index b5026218d..a2bbf6f15 100644 --- a/rendering/common/skincache.cpp +++ b/rendering/common/skincache.cpp @@ -65,8 +65,9 @@ geometry_handle skin_cache::geometry(TSubModel &Submodel, TModel3d const &Model, { joints.emplace_back(joint != nullptr ? joint->posed_transform() : glm::mat4{1.f}); } - auto palette{skinning::palette(Submodel.posed_transform(), joints, skin.inverse_bind)}; - cached.posed = (false == skinning::rest_pose(palette)); + auto const mesh{Submodel.posed_transform()}; + auto palette{skinning::palette(mesh, joints, skin.inverse_bind)}; + cached.posed = (false == skinning::rest_pose(palette, 1e-5f, skinning::palette_scale(mesh, joints))); if (cached.posed && (palette != cached.palette)) { cached.pending = true; diff --git a/rendering/geometrybank.cpp b/rendering/geometrybank.cpp index 7e82cce68..ce84c9be1 100644 --- a/rendering/geometrybank.cpp +++ b/rendering/geometrybank.cpp @@ -496,6 +496,24 @@ geometry_bank::indices( gfx::geometry_handle const &Geometry ) const { return geometry_bank::chunk( Geometry ).indices; } +// the positions of the vertices of specified chunk: of a chunk of the compact layout its stream as it is, without making the +// basic_vertex of it which vertices() keeps for good +position_array +geometry_bank::positions( gfx::geometry_handle const &Geometry ) const { + + auto const &chunk { geometry_bank::chunk( Geometry ) }; + std::scoped_lock lock { m_decodemutex }; + if( chunk.compact() ) { + return chunk.positions; + } + position_array positions; + positions.reserve( chunk.vertices.size() ); + for( auto const &vertex : chunk.vertices ) { + positions.push_back( vertex.position ); + } + return positions; +} + // provides direct access to vertex data of specfied chunk vertex_array const & geometry_bank::vertices( gfx::geometry_handle const &Geometry ) const { @@ -751,6 +769,12 @@ geometrybank_manager::indices( gfx::geometry_handle const &Geometry ) const { } // provides direct access to vertex data of specfied chunk +gfx::position_array +geometrybank_manager::positions( gfx::geometry_handle const &Geometry ) const { + + return bank( Geometry ).first->positions( Geometry ); +} + gfx::vertex_array const & geometrybank_manager::vertices( gfx::geometry_handle const &Geometry ) const { diff --git a/rendering/geometrybank.h b/rendering/geometrybank.h index 8f1b20370..b44ee7f4b 100644 --- a/rendering/geometrybank.h +++ b/rendering/geometrybank.h @@ -181,6 +181,8 @@ public: void release(); // provides direct access to index data of specfied chunk auto indices( gfx::geometry_handle const &Geometry ) const -> gfx::index_array const &; + // the positions of the vertices of specified chunk, without the basic_vertex of a chunk of the compact layout being made + auto positions( gfx::geometry_handle const &Geometry ) const -> gfx::position_array; // provides direct access to vertex data of specfied chunk auto vertices( gfx::geometry_handle const &Geometry ) const -> gfx::vertex_array const &; // provides direct access to vertex user data of specfied chunk @@ -324,6 +326,8 @@ public: ++First; } } // provides direct access to index data of specfied chunk auto indices( gfx::geometry_handle const &Geometry ) const -> gfx::index_array const &; + // the positions of the vertices of specified chunk (geometry_bank::positions()) + auto positions( gfx::geometry_handle const &Geometry ) const -> gfx::position_array; // provides direct access to vertex data of specfied chunk auto vertices( gfx::geometry_handle const &Geometry ) const -> gfx::vertex_array const &; // what the banks keep in the process, for the debug panel: banks, chunks with their vertex bytes, index bytes and user data bytes diff --git a/rendering/renderer.h b/rendering/renderer.h index 14712c926..4b3898b45 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -134,6 +134,15 @@ public: virtual auto Indices( gfx::geometry_handle const &Geometry ) const->gfx::index_array const & = 0; // provides direct access to vertex data of specfied chunk virtual auto Vertices( gfx::geometry_handle const &Geometry ) const ->gfx::vertex_array const & = 0; + // the positions of the vertices of specified chunk, for what needs no more of them (the bounds of a model as it loads): a renderer + // keeping the compact streams of an EU07M model gives them without making and keeping the basic_vertex Vertices() would + virtual auto Positions( gfx::geometry_handle const &Geometry ) const -> gfx::position_array { + auto const &vertices { Vertices( Geometry ) }; + gfx::position_array positions; + positions.reserve( vertices.size() ); + for( auto const &vertex : vertices ) { + positions.push_back( vertex.position ); } + return positions; } // provides direct access to vertex user data of specfied chunk virtual auto UserData( gfx::geometry_handle const &Geometry ) const ->gfx::userdata_array const & = 0; // kind of geometry of specified chunk, -1 when the renderer doesn't tell diff --git a/rendering/vulkan14/vulkan14geometry.cpp b/rendering/vulkan14/vulkan14geometry.cpp index 65e43b687..36d095780 100644 --- a/rendering/vulkan14/vulkan14geometry.cpp +++ b/rendering/vulkan14/vulkan14geometry.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14texture.h" #include +#include namespace vk14 { @@ -25,8 +26,24 @@ gfx::vertex_userdata const no_userdata{glm::vec4{0.f, 0.f, 0.f, 1.f}}; // the numbers the data of the banks get, unique across the banks (a bank made where another one was gets a new one) std::atomic g_generation{0}; +// set when a variant of a program for the compact layout didn't compile (compact_layout_failed()) +std::atomic g_compactfailed{false}; + } // namespace +void compact_layout_failed(std::string_view const Program) +{ + if (false == g_compactfailed.exchange(true)) + { + log_error(std::format("the compact vertex variant of \"{}\" didn't compile; EU07M models are drawn from basic_vertex from now on", Program)); + } +} + +bool compact_layout_usable() +{ + return false == g_compactfailed.load(); +} + VkPrimitiveTopology topology_of(unsigned int const Type) { switch (Type) @@ -150,7 +167,7 @@ bool vulkan14_geometrybank::build() release_(); // the compact layout when every chunk of the bank is of it (an EU07M model); otherwise its chunks go as basic_vertex - m_compact = (false == m_chunks.empty()) && std::ranges::all_of(m_chunks, [](geometry_chunk const &Chunk) { return Chunk.compact(); }); + m_compact = compact_layout_usable() && (false == m_chunks.empty()) && std::ranges::all_of(m_chunks, [](geometry_chunk const &Chunk) { return Chunk.compact(); }); if (false == m_compact) { for (auto &chunk : m_chunks) @@ -303,7 +320,8 @@ bool vulkan14_geometrybank::source(gfx::geometry_handle const &Geometry, chunk_s return false; } std::lock_guard lock(m_mutex); - if (m_layoutdirty) + // a bank of the compact layout whose programs can't be had is made anew of basic_vertex + if (m_layoutdirty || (m_compact && (false == compact_layout_usable()))) { build(); } diff --git a/rendering/vulkan14/vulkan14geometry.h b/rendering/vulkan14/vulkan14geometry.h index daed8db8d..7ad767074 100644 --- a/rendering/vulkan14/vulkan14geometry.h +++ b/rendering/vulkan14/vulkan14geometry.h @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include namespace vk14 { @@ -56,6 +57,12 @@ struct chunk_source // the vulkan primitive of a primitive of opengl (GL_TRIANGLES ...) VkPrimitiveTopology topology_of(unsigned int Type); +// a variant of a scene program for the compact layout didn't compile: the banks of EU07M models are made of basic_vertex +// from then on, those made already when they are drawn next, so the models stay in sight. told once in the log +void compact_layout_failed(std::string_view Program); +// false once compact_layout_failed() was called +bool compact_layout_usable(); + class vulkan14_geometrybank : public gfx::geometry_bank { public: diff --git a/rendering/vulkan14/vulkan14indirect.cpp b/rendering/vulkan14/vulkan14indirect.cpp index 611f139fb..48f5d5d5d 100644 --- a/rendering/vulkan14/vulkan14indirect.cpp +++ b/rendering/vulkan14/vulkan14indirect.cpp @@ -320,6 +320,11 @@ std::shared_ptr make_variant(vk14::shader_library &Shaders, catch (gfx::shader_exception const &Exception) { vk14::log_error(Exception.what()); + if (Kind.compact) + { + // without the variant the chunks of the compact layout would be left out for good: their banks go back to basic_vertex + vk14::compact_layout_failed(Name); + } } return nullptr; } diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 49e6d5fb9..c28460167 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -90,6 +90,7 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk bool Skin_Geometry(gfx::geometry_handle const &Geometry, std::shared_ptr const &Source, std::span Palette) override; gfx::index_array const &Indices(gfx::geometry_handle const &Geometry) const override; gfx::vertex_array const &Vertices(gfx::geometry_handle const &Geometry) const override; + gfx::position_array Positions(gfx::geometry_handle const &Geometry) const override; gfx::userdata_array const &UserData(gfx::geometry_handle const &Geometry) const override; int Primitive(gfx::geometry_handle const &Geometry) const override; // the sleepers and timbers are drawn by the walk of the scene (gfx::scene_walk), as in the opengl renderer diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index 1026a7229..7ccf9599f 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -1353,6 +1353,11 @@ gfx::vertex_array const &vulkan14_renderer::Vertices(gfx::geometry_handle const return m_geometry.vertices(Geometry); } +gfx::position_array vulkan14_renderer::Positions(gfx::geometry_handle const &Geometry) const +{ + return m_geometry.positions(Geometry); +} + gfx::userdata_array const &vulkan14_renderer::UserData(gfx::geometry_handle const &Geometry) const { return m_geometry.userdata(Geometry); diff --git a/shaders/ogl46/instance_cull.comp b/shaders/ogl46/instance_cull.comp index 5a6fd6ca4..c874d880e 100644 --- a/shaders/ogl46/instance_cull.comp +++ b/shaders/ogl46/instance_cull.comp @@ -226,7 +226,11 @@ void write(uint entry, instance_record record, vec3 location, instance_cull_job modelviews[slot] = originview * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(record.position, 1.0)); return; } - modelviews[slot] = view * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + // the word of the light parts (w of the first column, instance_light_bits()) is put back after the product, so a view with a + // translation can't add to the first column with it + mat4 modelview = view * mat4(vec4(record.rotationscale[0].xyz, 0.0), record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + modelview[0][3] = record.rotationscale[0].w; + modelviews[slot] = modelview; } void main() diff --git a/shaders/vk14/instance_cull.comp b/shaders/vk14/instance_cull.comp index c6b8e0983..b07a59b48 100644 --- a/shaders/vk14/instance_cull.comp +++ b/shaders/vk14/instance_cull.comp @@ -234,7 +234,11 @@ void write(uint entry, instance_record record, vec3 location, instance_cull_job modelviews[slot] = originview * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(record.position, 1.0)); return; } - modelviews[slot] = view * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + // the word of the light parts (w of the first column, instance_light_bits()) is put back after the product, so a view with a + // translation can't add to the first column with it + mat4 modelview = view * mat4(vec4(record.rotationscale[0].xyz, 0.0), record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + modelview[0][3] = record.rotationscale[0].w; + modelviews[slot] = modelview; } void main() diff --git a/shaders/vk14/skin.comp b/shaders/vk14/skin.comp index 2f26b9130..7f5d8846e 100644 --- a/shaders/vk14/skin.comp +++ b/shaders/vk14/skin.comp @@ -64,7 +64,12 @@ void main() } vec3 position = (blended * vec4(source.position_u.xyz, 1.0)).xyz; mat3 rotation = mat3(blended); - vec3 normal = skin_direction(rotation, source.normal_v.xyz); + // the normals by the cofactors of the rotation (the direction of its inverse transpose), with the sign of its determinant, + // as skinning::skin_vertices() moves them on the cpu + mat3 cofactors = mat3(cross(rotation[1], rotation[2]), cross(rotation[2], rotation[0]), cross(rotation[0], rotation[1])); + if (dot(rotation[0], cofactors[0]) < 0.0) + cofactors = -cofactors; + vec3 normal = skin_direction(cofactors, source.normal_v.xyz); vec3 tangent = skin_direction(rotation, source.tangent.xyz); uint target = (skin_counts.y + index) * 12u; skin_output[target + 0u] = position.x; diff --git a/tests/unit/test_clip.cpp b/tests/unit/test_clip.cpp index c1d061911..ba22b4f9e 100644 --- a/tests/unit/test_clip.cpp +++ b/tests/unit/test_clip.cpp @@ -139,6 +139,11 @@ TEST_CASE("clip: the clips go through the file and its checks") { CHECK(read.clip_tracks.size() == 1); CHECK(read.key_times.size() == 3); CHECK(read.key_rotations.size() == 3); + // as the game reads it: without the sections it doesn't know, which the clips aren't + eu07m::model game; + REQUIRE(eu07m::read(eu07m::write(model, {true, 9}), game, {false, false}).ok); + CHECK(game.clips.size() == 1); + CHECK(game.key_rotations.size() == 3); auto broken{model}; broken.clip_tracks[0].interpolation = eu07m::track_interpolation::cubic; @@ -176,6 +181,11 @@ TEST_CASE("clip: a joint turns or moves its node from the rest, within its limit slider.type = animation::joint_type::slider; slider.axis = {0.f, 1.f, 0.f}; CHECK(animation::joint_transform(slider, 0.25f)[3].y == doctest::Approx(0.25f)); + // a part modelled half out (JOIN.rest 0.1): there at the value 0.1, at its modelled place at 0 + slider.rest_value = 0.1f; + CHECK(animation::joint_transform(slider, 0.1f)[3].y == doctest::Approx(0.f)); + CHECK(animation::joint_transform(slider, 0.f)[3].y == doctest::Approx(-0.1f)); + slider.rest_value = 0.f; // a screw of 0.012 m a turn moves 0.006 m in half a turn animation::joint_binding screw; diff --git a/tests/unit/test_eu07m.cpp b/tests/unit/test_eu07m.cpp index 1d71b7cf3..5fac0167e 100644 --- a/tests/unit/test_eu07m.cpp +++ b/tests/unit/test_eu07m.cpp @@ -300,6 +300,17 @@ TEST_CASE("eu07m: broken files are refused with a reason, and leave the model em rehash(File); }, "don't hold together"}, + {"a header that claims fewer bytes than itself", + [](std::vector &File) { put_at(File, offsetof(eu07m::file_header, file_size), std::uint64_t{32}); }, + "less than its header"}, + {"a node in the subtree of another node than its parent", + [§ion](std::vector &File) { + // the body (node 1) reaches over the hose (node 2), whose parent is the root + put_at(File, section(eu07m::section::nodes).offset + sizeof(eu07m::table_header) + sizeof(eu07m::node_record) + offsetof(eu07m::node_record, subtree_end), + std::uint32_t{5}); + rehash(File); + }, + "lies in the subtree of node 1"}, {"a record too short for its table", [§ion](std::vector &File) { put_at(File, section(eu07m::section::primitives).offset + 4, std::uint32_t{20}); @@ -506,13 +517,49 @@ TEST_CASE("eu07m: the streams in the codecs of meshoptimizer, with and without z CHECK(loaded.nodes.empty()); } +TEST_CASE("eu07m: a section the reader doesn't know is passed over unless the tools keep it") +{ + auto const file{sample_file()}; + eu07m::model kept; + REQUIRE(eu07m::read(file, kept, {true, true}).ok); + CHECK(kept.unknown.size() == 1); + eu07m::model skipped; + auto const result{eu07m::read(file, skipped, {true, false})}; + REQUIRE_MESSAGE(result.ok, result.error); + CHECK(skipped.unknown.empty()); + kept.unknown.clear(); + CHECK(eu07m::dump(skipped) == eu07m::dump(kept)); +} + +TEST_CASE("eu07m: an unknown section in the codec of the streams doesn't stop the reading, unless the model needs it") +{ + // a later version may put a new optional stream in the codec; this one passes it over, the tools too + auto file{sample_file(false)}; + auto const offset{entry_offset(file, eu07m::fourcc("ZZZZ"))}; + auto entry{get_at(file, offset)}; + entry.flags |= eu07m::section_flags::meshopt; + put_at(file, offset, entry); + rehash(file); + eu07m::model loaded; + auto const result{eu07m::read(file, loaded, {true, true})}; + REQUIRE_MESSAGE(result.ok, result.error); + CHECK(loaded.unknown.empty()); + // one the model needs is refused as unknown, not for its codec + entry.flags |= eu07m::section_flags::required; + put_at(file, offset, entry); + rehash(file); + auto const required{eu07m::read(file, loaded, {true, true})}; + CHECK_FALSE(required.ok); + CHECK(required.error.find("doesn't know") != std::string::npos); +} + TEST_CASE("eu07m: a file with random bytes changed is read or refused, never more") { // the sample, too small for the codecs, and the grid, in them for (auto const variant : {0, 1, 2}) { auto const compress{variant == 1}; auto const good{variant < 2 ? sample_file(compress) : eu07m::write(grid_model(), {true, 9, true})}; - std::mt19937 random{static_cast(7 + variant * 4)}; + std::mt19937 random{static_cast(7 + variant * 4)}; // NOSONAR: seeded on purpose, the test changes the same bytes every run; nothing secret std::uniform_int_distribution position{0, good.size() - 1}; std::uniform_int_distribution value{0, 255}; for (int attempt = 0; attempt < 3000; ++attempt) { @@ -533,7 +580,7 @@ TEST_CASE("eu07m: a file with random bytes changed is read or refused, never mor TEST_CASE("eu07m: the tangent frame survives its packing") { - std::mt19937 random{3}; + std::mt19937 random{3}; // NOSONAR: seeded on purpose, the test packs the same frames every run; nothing secret std::uniform_real_distribution coordinate{-1.f, 1.f}; for (int attempt = 0; attempt < 2000; ++attempt) { glm::vec3 normal{coordinate(random), coordinate(random), coordinate(random)}; diff --git a/tests/unit/test_gref.cpp b/tests/unit/test_gref.cpp index 8020eb640..f70fc3150 100644 --- a/tests/unit/test_gref.cpp +++ b/tests/unit/test_gref.cpp @@ -152,6 +152,7 @@ TEST_CASE("gref: a block which isn't the one referred to is refused") { REQUIRE(store.open(eu07m::write_store({block}), error)); eu07m::model read; eu07m::read_options options; + options.verify_hash = true; // the game finds a block by its hash and checks its counts, the tools hash its bytes again options.blocks = [&store, &block](eu07m::geometry_reference_record const &, std::vector &Out) { return store.block(eu07m::block_hash(block), Out); }; CHECK_FALSE(eu07m::read(file, read, options).ok); } diff --git a/tests/unit/test_skinning.cpp b/tests/unit/test_skinning.cpp index 2bfb0bb7d..9c57c01b9 100644 --- a/tests/unit/test_skinning.cpp +++ b/tests/unit/test_skinning.cpp @@ -140,8 +140,29 @@ TEST_CASE("skinning: the bind pose leaves the vertices where they are") { auto const placed{glm::translate(glm::rotate(glm::mat4{1.f}, 0.7f, glm::vec3{0.f, 1.f, 0.f}), glm::vec3{10.f, 5.f, -3.f})}; std::vector const placedjoints{placed, placed * tipbind}; CHECK(skinning::rest_pose(skinning::palette(placed, placedjoints, inversebind), 1e-4f)); + // the default tolerance, scaled by the distances the palette was made of: a model far from the origin is at rest as well + auto const distant{glm::translate(glm::mat4{1.f}, glm::vec3{1500.f, 40.f, -2300.f})}; + std::vector const distantjoints{distant, distant * tipbind}; + CHECK(skinning::rest_pose(skinning::palette(distant, distantjoints, inversebind), 1e-5f, skinning::palette_scale(distant, distantjoints))); std::vector const moved{glm::translate(glm::mat4{1.f}, glm::vec3{0.f, 0.1f, 0.f})}; CHECK_FALSE(skinning::rest_pose(moved)); + CHECK_FALSE(skinning::rest_pose(moved, 1e-5f, skinning::palette_scale(distant, distantjoints))); +} + +TEST_CASE("skinning: the normals of a part scaled unevenly stay square to its surface") { + // a joint stretched twice along x: a surface at 45 degrees leans towards y, its normal towards x less + std::vector const palette{glm::scale(glm::mat4{1.f}, glm::vec3{2.f, 1.f, 1.f})}; + auto vertex{vertex_at({0.f, 0.f, 0.f})}; + vertex.normal = glm::normalize(glm::vec3{1.f, 1.f, 0.f}); + std::vector const rest{vertex}; + std::vector const weights{{{0, 0, 0, 0}, {1.f, 0.f, 0.f, 0.f}}}; + std::vector out(1); + skinning::skin_vertices(rest, weights, palette, out); + CHECK(close_to(out[0].normal, glm::normalize(glm::vec3{0.5f, 1.f, 0.f}))); + // a mirroring joint keeps the normal facing out + std::vector const mirror{glm::scale(glm::mat4{1.f}, glm::vec3{-1.f, 1.f, 1.f})}; + skinning::skin_vertices(rest, weights, mirror, out); + CHECK(close_to(out[0].normal, glm::normalize(glm::vec3{-1.f, 1.f, 0.f}))); } TEST_CASE("skinning: a joint turned moves its vertices, blended by the weights") { diff --git a/world/Event.cpp b/world/Event.cpp index 613c6e2b7..4d3dc50e9 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -1662,16 +1662,23 @@ animation_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) >> m_animationparams[ 3 ]; } else if( token == "clip" ) { - // an animation clip of the model (EU07M): its name and pace; a pace of 0 stops the clips playing - Input.getTokens(); + // an animation clip of the model (EU07M): its name, as written (the parser would lowercase it), and pace; a pace of 0 + // stops the clips playing + Input.getTokens( 1, false ); Input >> m_animationsubmodel; m_animationtype = clip_animation; Input.getTokens( 1 ); + if( is_keyword( Input.peek() ) ) { + // no pace: the clip plays at its own, and the keyword read is the next token of the event, not a number of it + m_animationparams[ 0 ] = 1.0; + ErrorLog( "Bad event: \"" + m_name + "\" (type: " + type() + ") gives no pace for clip \"" + m_animationsubmodel + "\", it plays at its own" ); + return; + } Input >> m_animationparams[ 0 ]; } else if( token == "channel" ) { - // a channel of the model (EU07M): its name and value - Input.getTokens(); + // a channel of the model (EU07M): its name, as written (the parser would lowercase it), and value + Input.getTokens( 1, false ); Input >> m_animationsubmodel; m_animationtype = channel_animation; Input.getTokens( 1 );