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 1/2] 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 2/2] 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