From 0d095e225c8349843a7eb8c38d497ea2c57bd46c Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:25:23 +0100 Subject: [PATCH 01/10] fix(model): E4D review of #535: no guessed pass in the file, the header and the tree checked, unknown sections passed over - The pass bits (0x30) BinInit guesses from a material when the E3D has none are marked (TSubModel::m_passguessed) and the converter leaves them out of legacy_flags and the primitive flags: it loads through the null renderer, whose materials all guess opaque, so the game makes the guess again with the real material. - A vehicle's model isn't converted from its .t3d (dynamic 1): the game prepares it only after the vehicle marked its animated parts, so the .e3d the game makes of it is converted instead. - read_header refuses a file_size smaller than the header, which made the hash check read outside the span. - Sections seen twice are found with a set, not O(n^2); all the sections together may claim at most 2 GiB; a section the reader doesn't know and the model can do without is passed over before it is unpacked when keep_unknown is off. - validate() checks that the parent of each node is the innermost node whose subtree holds it, so the tree of the ranges is the tree of the parents. - Light_OnNN / Light_OffNN found by the game's GetFromName, so of two submodels of a name the same one counts; a replaceable skin drawn translucent gets material_flags::translucent; the convertmodels flags parsed without stoi. - S3519: the matrix made with glm::make_mat4 instead of a memcpy into its first column; NOSONAR on the seeded engines of the tests (S2245). - The spec: u16 indices up to 65 536 vertices, and the two rules above. Tests: a file_size below the header, a node in the subtree of another than its parent, an unknown section passed over. --- docs/e4d-format.md | 5 ++- model/Model3d.cpp | 1 + model/Model3d.h | 3 ++ model/e4d/e4d_build.cpp | 8 ++--- model/e4d/e4d_convert.cpp | 66 ++++++++++++++++++++++++++++++--------- model/e4d/e4d_io.cpp | 45 +++++++++++++++++++++----- tests/unit/test_e4d.cpp | 29 +++++++++++++++-- 7 files changed, 128 insertions(+), 29 deletions(-) diff --git a/docs/e4d-format.md b/docs/e4d-format.md index 9646efcd5..21c41a303 100644 --- a/docs/e4d-format.md +++ b/docs/e4d-format.md @@ -215,7 +215,10 @@ go w E4D: - `iFlags`, zakres widoczności i kolory zostają w węźle i w slocie materiału. - `TP_FREESPOTLIGHT` → `LGHT`; `Light_On##` / `Light_Off##` → `LSLT`; `smokesource_*` → `EMIT`; animacja `anim:` → `LANM`; `TP_TEXT` → `LTXT`; `TP_STARS` → `STAR`. -- Indeksy są zapisywane jako `u16`, gdy prymityw ma mniej niż 65 536 wierzchołków. +- Indeksy są zapisywane jako `u16`, gdy prymityw ma co najwyżej 65 536 wierzchołków (indeksy 0–65 535). +- Bity fazy rysowania (0x30) zgadnięte przy wczytaniu E3D z materiału nie trafiają do `legacy_flags` ani do flag prymitywu: + zgaduje je na nowo gra, z prawdziwym materiałem. Model pojazdu konwertuje się z `.e3d`, który robi z niego gra, nie z `.t3d`. +- Wymienna skóra `-k` w przebiegu przezroczystym (bit k−1 flag E3D) ma w `MATL` flagę `translucent`. Pozostałe polecenia: `eu07 -e4d dump ` (zawartość jako tekst) i `eu07 -e4d validate ` (sprawdzenie pliku wraz z hashem zawartości). diff --git a/model/Model3d.cpp b/model/Model3d.cpp index f3ddbc4a5..df9adb775 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -2729,6 +2729,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 9be9a4f0f..42dee42bf 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -102,6 +102,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/e4d/e4d_build.cpp b/model/e4d/e4d_build.cpp index d20232856..11122354a 100644 --- a/model/e4d/e4d_build.cpp +++ b/model/e4d/e4d_build.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "model/e4d/e4d_build.h" #include +#include #include #include @@ -58,11 +59,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/e4d/e4d_convert.cpp b/model/e4d/e4d_convert.cpp index dee1a6415..2fa6fe76e 100644 --- a/model/e4d/e4d_convert.cpp +++ b/model/e4d/e4d_convert.cpp @@ -21,8 +21,11 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include "utilities/wholefile.h" +#include #include #include +#include +#include namespace e4d { @@ -63,8 +66,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()) @@ -95,7 +106,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) @@ -154,8 +166,12 @@ void converter::components(TSubModel const &Submodel, std::uint32_t const Node) 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; @@ -226,7 +242,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); @@ -246,22 +263,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()); } } @@ -279,7 +304,20 @@ 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"}; - Global.iConvertModels = Argc > 6 ? std::stoi(Argv[6]) : 0; + 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; + } + 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 2; + } + } Global.iWriteLogEnabled = 2; GfxRenderer = gfx_renderer_factory::get_instance()->create("null"); TModel3d source; diff --git a/model/e4d/e4d_io.cpp b/model/e4d/e4d_io.cpp index cd6c680c3..6fb0fe449 100644 --- a/model/e4d/e4d_io.cpp +++ b/model/e4d/e4d_io.cpp @@ -14,8 +14,10 @@ http://mozilla.org/MPL/2.0/. #include "zstd.h" +#include #include #include +#include namespace e4d { @@ -283,6 +285,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: @@ -314,6 +318,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"); @@ -327,15 +333,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; } @@ -359,6 +369,18 @@ bool file_reader::unpack(section_entry const &Entry, std::vector &Sto return true; } +// the sections this reader reads (dispatch() below) +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}; + +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}; @@ -413,6 +435,10 @@ read_result file_reader::run(model &Model) { Model.source_hash = header.source_hash; std::vector storage; for (auto const &entry : sections) { + // a section this reader doesn't know and the model can do without is passed over before it is unpacked, unless the + // tools keep it to write it back + if (false == known_section(entry.id) && (entry.flags & section_flags::required) == 0 && false == m_options.keep_unknown) + continue; std::span bytes; if (false == unpack(entry, storage, bytes) || false == dispatch(entry, section_bytes{entry.id, bytes}, Model)) { Model = model{}; @@ -648,11 +674,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/tests/unit/test_e4d.cpp b/tests/unit/test_e4d.cpp index df541c285..7cea0f303 100644 --- a/tests/unit/test_e4d.cpp +++ b/tests/unit/test_e4d.cpp @@ -300,6 +300,17 @@ TEST_CASE("e4d: broken files are refused with a reason, and leave the model empt rehash(File); }, "don't hold together"}, + {"a header that claims fewer bytes than itself", + [](std::vector &File) { put_at(File, offsetof(e4d::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(e4d::section::nodes).offset + sizeof(e4d::table_header) + sizeof(e4d::node_record) + offsetof(e4d::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(e4d::section::primitives).offset + 4, std::uint32_t{20}); @@ -406,11 +417,25 @@ TEST_CASE("e4d: parts of several nodes and light slots merged into one primitive } } +TEST_CASE("e4d: a section the reader doesn't know is passed over unless the tools keep it") +{ + auto const file{sample_file()}; + e4d::model kept; + REQUIRE(e4d::read(file, kept, {true, true}).ok); + CHECK(kept.unknown.size() == 1); + e4d::model skipped; + auto const result{e4d::read(file, skipped, {true, false})}; + REQUIRE_MESSAGE(result.ok, result.error); + CHECK(skipped.unknown.empty()); + kept.unknown.clear(); + CHECK(e4d::dump(skipped) == e4d::dump(kept)); +} + TEST_CASE("e4d: a file with random bytes changed is read or refused, never more") { for (auto const compress : {false, true}) { auto const good{sample_file(compress)}; - std::mt19937 random{compress ? 7u : 11u}; + std::mt19937 random{compress ? 7u : 11u}; // 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) { @@ -431,7 +456,7 @@ TEST_CASE("e4d: a file with random bytes changed is read or refused, never more" TEST_CASE("e4d: 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)}; From ee631c7b41ac31e8257a4247c018beb5a1112185 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:29:35 +0100 Subject: [PATCH 02/10] fix(model): E4D review of #536: a stale .e4d isn't used, a model which can't be built falls back to its .e3d - modelformat e4d: an .e4d older than its .e3d / .t3d isn't loaded, with a line in the log; the model was changed after it was converted. - LoadFromE4D catches what reading and building throw (no memory for what a broken file declares) and leaves nothing of the model, so its .e3d / .t3d loads instead; a worker of fill_geometry() hands its exception to the caller after the join instead of ending the program. - ref/meshoptimizer is cloned shallow like the other submodules. The pass bits the converter no longer bakes (#535) are guessed again by BinInit, which finish_binary() runs, so the loader needs no change for them. --- .gitmodules | 1 + model/Model3d.cpp | 26 ++++++++++++++++++- model/e4d/e4d_load.cpp | 57 ++++++++++++++++++++++++++++++++++-------- 3 files changed, 72 insertions(+), 12 deletions(-) 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/model/Model3d.cpp b/model/Model3d.cpp index 1c743f80a..791146795 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 //--------------------------------------------------------------------------- @@ -1774,6 +1776,27 @@ glm::vec3 TSubModel::offset(float const Geometrytestoffsetthreshold) const namespace { +// modelformat e4d: an .e4d 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 e4d_up_to_date(std::string const &E4d, std::initializer_list const Sources) +{ + std::error_code error; + auto const made{std::filesystem::last_write_time(E4d, 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 \"" + E4d + "\", 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 @@ -1875,7 +1898,8 @@ bool TModel3d::LoadFromFile(std::string const &FileName, bool dynamic) Init(); assign_lod_ranges(Root, name); } - else if (auto const e4dfile{Global.modelformat_e4d ? FileCased(name + ".e4d") : std::string{}}; (false == e4dfile.empty()) && LoadFromE4D(e4dfile, dynamic)) + else if (auto const e4dfile{Global.modelformat_e4d ? FileCased(name + ".e4d") : std::string{}}; + (false == e4dfile.empty()) && e4d_up_to_date(e4dfile, {binaryfile, textfile}) && LoadFromE4D(e4dfile, dynamic)) { // modelformat e4d: the .e4d made from the model takes its place; one which doesn't load leaves the .e3d / .t3d to go on asBinary = ""; diff --git a/model/e4d/e4d_load.cpp b/model/e4d/e4d_load.cpp index 204da371c..475face2b 100644 --- a/model/e4d/e4d_load.cpp +++ b/model/e4d/e4d_load.cpp @@ -15,13 +15,16 @@ http://mozilla.org/MPL/2.0/. #include "model/e4d/e4d_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 @@ -281,12 +284,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(); } }}; { @@ -296,6 +311,8 @@ void submodel_builder::fill_geometry() { workers.emplace_back(work); work(); } // the workers join here + if (failure != nullptr) + std::rethrow_exception(failure); } } // namespace @@ -309,8 +326,14 @@ bool TModel3d::LoadFromE4D(std::string const &FileName, bool const dynamic) { } e4d::model model; // the game has no use for the sections it doesn't know - if (auto const result{e4d::read(std::as_bytes(std::span{file.data.get(), file.size}), model, {false, false})}; false == result.ok) { - ErrorLog("Bad model: \"" + FileName + "\" isn't a valid E4D file: " + result.error, logtype::model); + try { + if (auto const result{e4d::read(std::as_bytes(std::span{file.data.get(), file.size}), model, {false, false})}; false == result.ok) { + ErrorLog("Bad model: \"" + FileName + "\" isn't a valid E4D 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()) { @@ -328,9 +351,21 @@ bool TModel3d::LoadFromE4D(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; + } m_vertexcount += builder.vertex_count; m_indexcount += builder.index_count; // the tangents come with the vertices From 3b9d8b2fa3ba88f91e6aa8aa752f410ded38c263 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:12:50 +0100 Subject: [PATCH 03/10] fix(render): EU07M review of #537: no whole vertices kept for the bounds, the compact variant checked by CI and given up when it fails - The bounding radius, offset() and MaxY() read the positions of a chunk alone (Positions(), geometry_bank::positions()): on Vulkan the compact streams are no longer decoded into basic_vertex and kept for the life of the bank as every model loads, so the host memory of EU07M models stays below that of E3D. What still needs whole vertices (the editor, the picking, the export) decodes them on first use as before. - A COMPACT_VERTEX variant which doesn't compile is told once in the log and the banks of EU07M models go back to basic_vertex (compact_layout_failed()), those built already when they are drawn next, instead of the models being left out for the session. - The shader validator compiles the vk14 shaders which have COMPACT_VERTEX with it, alone and with MODEL_DRAWS, as the renderer makes the variants. --- ci_shadervalidator/main.cpp | 11 +++++++++ model/Model3d.cpp | 32 ++++++++++++++++++------- rendering/geometrybank.cpp | 24 +++++++++++++++++++ rendering/geometrybank.h | 4 ++++ rendering/renderer.h | 9 +++++++ rendering/vulkan14/vulkan14geometry.cpp | 22 +++++++++++++++-- rendering/vulkan14/vulkan14geometry.h | 7 ++++++ rendering/vulkan14/vulkan14indirect.cpp | 5 ++++ rendering/vulkan14/vulkan14renderer.h | 1 + rendering/vulkan14/vulkan14scene.cpp | 5 ++++ 10 files changed, 109 insertions(+), 11 deletions(-) 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/model/Model3d.cpp b/model/Model3d.cpp index c526c8ff9..485bb7054 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1486,9 +1486,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; @@ -1612,9 +1613,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()) @@ -1756,17 +1757,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; } } } 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 17ba4db31..5021e9992 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -123,6 +123,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 1cf0c35a7..b1f9f59b8 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) @@ -297,7 +314,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 de445152e..23e017f67 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -88,6 +88,7 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk void Erase(gfx::geometry_handle const &Geometry) 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 4ad5f432b..1fb38ec6f 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -1352,6 +1352,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); From 99bc0b125c5f75ecef4da01ddec8690247d86fec Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:14:35 +0100 Subject: [PATCH 04/10] fix(render): EU07M review of #538: an instance with light colours of its own drawn alone, the light records locked only when stale - An instance with lightcolors of its own isn't instanced: the colours go onto the shared submodels as the instance is prepared, which the instances of a bucket don't each get, so they all showed the colours of one of them. - The walk takes the exclusive lock for the light records of a bucket only when they are stale in this frame (Refresh_Light_Records() checks again under it): the later passes of the frame no longer stop the other walkers. - instance_cull.comp (both renderers) puts the word of the light parts into [0][3] after the product with the view, so a view with a translation can't stretch the first column of a lit instance. - The spec: ls_Dark / ls_Home switch without the fade too, and the instances with light colours of their own. --- docs/eu07m-format.md | 5 ++++- model/AnimModel.cpp | 5 +++++ rendering/common/scenewalk.cpp | 5 +++-- shaders/ogl46/instance_cull.comp | 6 +++++- shaders/vk14/instance_cull.comp | 6 +++++- 5 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index 8723fd89e..514a08cfb 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -257,7 +257,10 @@ egzemplarz osobno. Dotyczy to modeli EU07M i E3D tak samo. w shaderze macierz zerową (`instance_hides_part()` w `common.glsl`). - Egzemplarz pokazuje całą część zapaloną albo całą zgaszoną. Przy miganiu i przy przełączaniu (`ls_On` / `ls_Off` / `ls_Blink`) zamiana następuje w połowie przejścia (krycie 0,5), a nie płynnym przenikaniem jak bez instancjonowania. - Stany stałe wyglądają tak samo jak bez instancjonowania. + Stany stałe wyglądają tak samo jak bez instancjonowania. Tak samo bez płynnego przejścia (`fVisible`) zmieniają się + `ls_Dark` i `ls_Home`. +- Egzemplarz z własnymi kolorami świateł (`lightcolors` węzła) jest rysowany osobno: kolory są nadawane wspólnym + submodelom przy przygotowaniu egzemplarza, którego egzemplarze kubełka nie dostają każdy z osobna. - Pomiar (Vulkan, 200 głowic `s4ipcpb_dd`): z `gfx.gpucull 0` klatka 9,2 ms → 1,5–2,5 ms i 2400 → 16 drawcalli, z `gfx.gpucull 1` 9,1 ms → 3,0 ms i 2410 → 26 drawcalli. diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 91cf164d1..8c347163b 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "model/AnimModel.h" +#include + #include "rendering/renderer.h" #include "model/MdlMngr.h" #include "simulation/simulation.h" @@ -569,6 +571,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; diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index 1b348c25d..0e69fad1b 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -1034,8 +1034,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/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() From 115c13b2747da7defe22a1db390a9a4df1565b1b Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:16:19 +0100 Subject: [PATCH 05/10] fix(model): EU07M review of #539: a model made anew keeps its transforms, normals of scaled joints, the rest pose far from the origin - A node of a model made anew (legacy_flags 0) with a transform gets 0x8000, as a converted one has it: the walk and posed_transform() left such nodes out, so a skin was drawn off its place in the bind pose (the tube: the upper half 2 m off) and jumped when an animation set 0x4000 on the joint. - Normals are skinned by the cofactors of the blended rotation (the direction of its inverse transpose), with the sign of its determinant, not by the rotation: a joint scaled unevenly tilted the normals of its part. - rest_pose() takes the translation within the tolerance times the distance from the origin of the mesh and the joints (palette_scale()): the float chain rounds in proportion to it, and a model a few kilometres out counted as posed in the bind pose, with a geometry copy and a skinning pass of its own. Tests: the rest pose far from the origin, the normals of a stretched and of a mirroring joint. --- model/eu07m/eu07m_load.cpp | 4 ++++ model/skinning.cpp | 31 +++++++++++++++++++++++++++---- model/skinning.h | 8 ++++++-- rendering/common/skincache.cpp | 5 +++-- tests/unit/test_skinning.cpp | 21 +++++++++++++++++++++ 5 files changed, 61 insertions(+), 8 deletions(-) diff --git a/model/eu07m/eu07m_load.cpp b/model/eu07m/eu07m_load.cpp index 987f25191..509afcd15 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -148,6 +148,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; 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/skincache.cpp b/rendering/common/skincache.cpp index 9a23ce500..68398ed23 100644 --- a/rendering/common/skincache.cpp +++ b/rendering/common/skincache.cpp @@ -64,8 +64,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.vertices.resize(source->rest.size()); diff --git a/tests/unit/test_skinning.cpp b/tests/unit/test_skinning.cpp index 39f4970ec..bd0c2a5d8 100644 --- a/tests/unit/test_skinning.cpp +++ b/tests/unit/test_skinning.cpp @@ -139,8 +139,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") { From 474c9ab5aea4f0a4be6eec6939f3b4105929eefb Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:17:49 +0100 Subject: [PATCH 06/10] fix(model): EU07M review of #540: stopped clips held per instance, events over clips, the rest of a matrix node from its matrix - stop_clips() holds each clip at the moment it was stopped instead of dropping it: the pose lives in the submodels the instances of a model share, so an instance whose clips were cleared snapped back to rest as soon as another instance of the model played one (two doors of one model). - RaPrepare() applies the clips before the animation events of the scenery, so an event moving a node (rotate, translate...) takes it over from a clip, one ended or stopped included; before, a finished clip overrode the events on its nodes on every draw. - A node with a matrix (XFRM) has its TRS fields only as an approximation: the parts the tracks of a clip don't move are taken from the decomposed matrix, so the node no longer jumps or skews when a clip starts moving another part of it. - The spec says so. --- docs/eu07m-format.md | 9 +++++++-- model/AnimModel.cpp | 16 +++++++++++++--- model/AnimModel.h | 6 +++++- model/eu07m/eu07m_load.cpp | 15 +++++++++++++++ 4 files changed, 40 insertions(+), 6 deletions(-) diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index b4d52aaf5..998f9e16c 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -261,8 +261,13 @@ Części węzła bez ścieżki zostają takie, jak w jego TRS. - **Czas.** Klip idzie po czasie symulacji od chwili startu, z tempem `speed`. Zapętlony zaczyna od nowa po swojej długości, inny zatrzymuje się na końcu. Klip z flagą 0x2 startuje sam, gdy egzemplarz jest rysowany pierwszy raz. - **W grze.** `TAnimModel::play_clip(nazwa, tempo)` startuje klip (komenda self-testu `clip [tempo]`), - a `stop_clips()` zatrzymuje wszystkie. Przy każdym rysowaniu egzemplarza `RaPrepare()` próbkuje grające klipy i - ustawia transformy węzłów (`TSubModel::SetClipTransform()`, animacja `at_Clip`), tak jak inne animacje egzemplarza. + a `stop_clips()` zatrzymuje wszystkie: każdy zostaje wstrzymany w chwili zatrzymania i dalej ustawia swoje węzły, bo + poza tym, co ustawia egzemplarz przy rysowaniu, węzły trzymają wspólne submodele wszystkich egzemplarzy. Przy każdym + rysowaniu egzemplarza `RaPrepare()` próbkuje klipy i ustawia transformy węzłów (`TSubModel::SetClipTransform()`, + animacja `at_Clip`), przed animacjami eventów: event scenerii ruszający węzeł (`rotate`, `translate`…) bierze go od + klipu, także zakończonego albo zatrzymanego. +- Węzeł z macierzą (`XFRM`) ma pola TRS tylko w przybliżeniu: części, których ścieżki klipu nie ruszają, są brane z + rozkładu samej macierzy, więc węzeł nie skacze, gdy klip zaczyna ruszać inną jego część. Węzły, które klipy przesuwają, są przy wczytaniu oznaczane jako animowane, więc model z klipami nie jest instancjonowany. Klip ruszający jointami skóry zgina skinowane części (sekcja „Skinning”). - **Jeszcze nie:** event scenerii, który startuje klip, oraz powiązanie kanałów `CHNL` z czasem klipu. Obecne wydanie diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index d4abeb0b3..a0357af24 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -755,10 +755,12 @@ void TAnimModel::RaPrepare() TSubModel::iVariantSeed = 0; TSubModel::pasText = &asText; // przekazanie tekstu do wyświetlacza (!!!! do przemyślenia) + // the clips first: an animation event of the scenery on a node (rotate, translate...) takes over from a clip on the same node, + // one which ended or was stopped included, as the later one set on the submodel counts + apply_clips(); for (auto entry : m_animlist) { entry->PrepareModel(); } - apply_clips(); } // the state of the lit and the dark part of a numbered light, as RaPrepare() shows them @@ -813,7 +815,15 @@ bool TAnimModel::play_clip( std::string_view const Name, float const Speed ) { 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; } @@ -835,7 +845,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 986103591..3faee6144 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 }; @@ -192,7 +194,8 @@ public: // starts the animation clip of the model (EU07M) with the name from its beginning, at Speed times its pace; a clip already playing // starts over. false when the model has no clip of the name bool play_clip( std::string_view Name, float Speed = 1.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(); // radius() subclass details, calculates node's bounding radius @@ -245,6 +248,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/eu07m/eu07m_load.cpp b/model/eu07m/eu07m_load.cpp index 9f58c3bec..06bd45c7b 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include "utilities/wholefile.h" +#include #include #include @@ -398,6 +399,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); } From 4018a5cba43ac88c75ff8c650755955069ee09e6 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:18:11 +0100 Subject: [PATCH 07/10] fix(render): EU07M review of #541: the skinning kernel moves normals as the cpu does skin.comp moves the normals by the cofactors of the blended rotation with the sign of its determinant, as skinning::skin_vertices() now does (#539), so a joint scaled unevenly lights its part the same on both paths. --- shaders/vk14/skin.comp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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; From 7b6bdf22bb3da1c5909a018d02086704fa61c52c Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:19:19 +0100 Subject: [PATCH 08/10] fix(events): EU07M review of #542: clip names keep their case and match regardless of it, an event without a pace told - The clip event reads the name of the clip as written (getTokens lowercased it), and play_clip() finds the clip regardless of case, as the submodels are found by their names: a clip named Open or Armature|Wave couldn't be started from a scenery. - An event without a pace (clip endevent) plays the clip at its own pace with a line in the log, and leaves the keyword it met to the event: before, endevent was read as a pace of 0 (stopping the clips) and the next token was swallowed. - Pace 0 with several instances of one model is held by #540's fix (the clips stopped stay set per instance). - The spec says so. --- docs/eu07m-format.md | 4 +++- model/AnimModel.cpp | 9 ++++++++- world/Event.cpp | 11 +++++++++-- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index feeb14ddb..050f7debe 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -267,7 +267,9 @@ Części węzła bez ścieżki zostają takie, jak w jego TRS. instancjonowany. Klip ruszający jointami skóry zgina skinowane części (sekcja „Skinning”). - **Event scenerii.** `event animation clip endevent` startuje klip od początku w podanym tempie (klip już grający zaczyna od nowa), a tempo 0 zatrzymuje klipy modelu; węzły zostają tam, - gdzie klip je zostawił. Klip, którego model nie ma, daje w logu `Bad event: ... can't find clip`. To nowa forma + gdzie klip je zostawił. Nazwa klipu jest porównywana bez względu na wielkość liter, jak nazwy submodeli. Event bez + tempa (`clip endevent`) gra klip w jego tempie i daje w logu `Bad event: ... gives no pace for clip`. Klip, + którego model nie ma, daje w logu `Bad event: ... can't find clip`. To nowa forma eventu `animation`, której obecne wydanie nie czyta; dotychczasowe formy (`rotate`, `translate`, `digital`, `.vmd`) czytają się jak dotąd. - **Jeszcze nie:** powiązanie kanałów `CHNL` z czasem klipu. Obecne wydanie nie czyta sekcji klipów, a plik bez nich diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index d4abeb0b3..b5a5d1c1a 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" @@ -802,7 +805,11 @@ bool TAnimModel::play_clip( std::string_view const Name, float const Speed ) { 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; } ); diff --git a/world/Event.cpp b/world/Event.cpp index cf02e9409..e7c055e75 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -1662,11 +1662,18 @@ 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.ends_with(".vmd") ) // na razie tu, może będzie inaczej From ce40e11b9421725420c7bba278faa42d4ab1cffd Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:20:09 +0100 Subject: [PATCH 09/10] fix(model): EU07M review of #543: channel names keep their case, the joint moves from its rest value - The channel event reads the name of the channel as written (getTokens lowercased it), and set_channel() finds it regardless of case: a channel named doorLeft couldn't be set from a scenery. - JOIN.rest is read: the node is modelled at the rest value of its joint, which moves it by the value less rest (the limits stay values of the joint). A part modelled half open no longer jumps when its channel is set. Files without it (rest 0) move as before. - The spec says so, and that no vehicle sets channels yet. Test: a slider modelled half out. --- docs/eu07m-format.md | 7 +++++-- model/AnimModel.cpp | 9 ++++++++- model/clip.cpp | 2 ++ model/clip.h | 1 + model/eu07m/eu07m_load.cpp | 1 + tests/unit/test_clip.cpp | 5 +++++ world/Event.cpp | 4 ++-- 7 files changed, 24 insertions(+), 5 deletions(-) diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index 3614ea493..dcda7226e 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -286,10 +286,13 @@ 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 `). +- **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 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. - **Scenery event.** `event animation channel endevent` sets the channel. A channel the diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 22fa34c39..55b4ac9a1 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" @@ -825,7 +828,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() ); 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_load.cpp b/model/eu07m/eu07m_load.cpp index db361131d..9080d637f 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -439,6 +439,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; } diff --git a/tests/unit/test_clip.cpp b/tests/unit/test_clip.cpp index 43aeaf788..ba22b4f9e 100644 --- a/tests/unit/test_clip.cpp +++ b/tests/unit/test_clip.cpp @@ -181,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/world/Event.cpp b/world/Event.cpp index 613c6e2b7..24ab6d4c3 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -1670,8 +1670,8 @@ animation_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) 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 ); From 1638fc919b0d0ff04cf4362d432a728ec95026e1 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:22:04 +0100 Subject: [PATCH 10/10] fix(model): EU07M review of #545: a pack failing half way leaves the folder loading, a store packed anew opened again - pack_folder() writes a store of the old blocks and the new ones together before the models, then the models, then the store of the new blocks alone: a failure on any model (a rename refused, the disk full) leaves models packed against either store, all of which load. Before, models 1..k referred to blocks no store on the disk had. - write_file() closes the stream before it checks it (what sat in its buffer is written by the close) and removes the .tmp of a failed write. - family_store() opens the store of a folder again when its size or time changed (packed anew while the game runs): its blocks are read from the file by the offsets of the index, which then belonged to another file. A store which can't be opened is told in the log once, with the reason, instead of every model of the folder reporting a missing block. - The game finds a block by its hash and checks its counts; the bytes are hashed again only with verify_hash, as the tools read (insert_blocks(..., Verify)), so a load no longer hashes every block twice. - The index of a store is checked without the offset and the size wrapping, and a block may unpack to 1 GiB at most. --- model/eu07m/eu07m_io.cpp | 2 +- model/eu07m/eu07m_pack.cpp | 44 ++++++++++++++++++++++++++--- model/eu07m/eu07m_store.cpp | 56 ++++++++++++++++++++++++++----------- model/eu07m/eu07m_store.h | 5 ++-- tests/unit/test_gref.cpp | 1 + 5 files changed, 84 insertions(+), 24 deletions(-) diff --git a/model/eu07m/eu07m_io.cpp b/model/eu07m/eu07m_io.cpp index 2a8c98bc5..a3c0edda9 100644 --- a/model/eu07m/eu07m_io.cpp +++ b/model/eu07m/eu07m_io.cpp @@ -665,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}; } 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/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); }