diff --git a/docs/e4d-format.md b/docs/e4d-format.md index 105b6375d..990fb14a7 100644 --- a/docs/e4d-format.md +++ b/docs/e4d-format.md @@ -222,7 +222,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 a7d3d5cb3..1c743f80a 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -2742,6 +2742,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 8e75ae274..a2a60ac50 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 8526fbfdb..23254066e 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 4fbfaa366..76d90fa62 100644 --- a/model/e4d/e4d_convert.cpp +++ b/model/e4d/e4d_convert.cpp @@ -22,10 +22,13 @@ http://mozilla.org/MPL/2.0/. #include "utilities/wholefile.h" #include +#include #include #include #include +#include #include +#include namespace e4d { @@ -67,8 +70,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()) @@ -99,7 +110,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) @@ -170,8 +182,12 @@ bool converter::has_geometry(TSubModel const &Submodel) { std::uint32_t converter::material(TSubModel const &Submodel) { material_record record; - if (Submodel.m_material < 0) + if (Submodel.m_material < 0) { record.replaceable = std::max(Submodel.m_material, -4); + // the pass of a replaceable skin: bit k-1 of the E3D flags for the skin -k + if ((Submodel.iFlags & (1u << (-record.replaceable - 1))) != 0) + record.flags |= material_flags::translucent; + } else if (false == Submodel.m_materialname.empty()) record.name = m_model.intern(Submodel.m_materialname); record.selfillum = Submodel.fLight; @@ -239,7 +255,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); @@ -259,22 +276,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()); } } @@ -304,10 +329,18 @@ bool load_source(std::string const &Input, bool const Dynamic, TModel3d &Source, return true; } -void start_tools(int const Argc, char *Argv[]) { - Global.iConvertModels = Argc > 6 ? std::stoi(Argv[6]) : 0; +bool start_tools(int const Argc, char *Argv[]) { + Global.iConvertModels = 0; + if (Argc > 6) { + auto const flags{std::string_view{Argv[6]}}; + if (auto const [end, error]{std::from_chars(flags.data(), flags.data() + flags.size(), Global.iConvertModels)}; error != std::errc{} || end != flags.data() + flags.size()) { + std::cerr << std::format("the convertmodels flags \"{}\" aren't a number\n", flags); + return false; + } + } Global.iWriteLogEnabled = 2; GfxRenderer = gfx_renderer_factory::get_instance()->create("null"); + return true; } // the differences between two loaded models, submodel by submodel in the order of the tree @@ -446,7 +479,8 @@ int command_diff(int const Argc, char *Argv[]) { std::cerr << "usage: -e4d diff [dynamic 0|1]\n"; return 2; } - start_tools(Argc, Argv); + if (false == start_tools(Argc, Argv)) + return 2; auto const dynamic{Argc > 5 && std::string_view{Argv[5]} == "1"}; TModel3d source; TModel3d converted; @@ -473,7 +507,14 @@ int command_convert(int const Argc, char *Argv[]) { std::string const input{Argv[3]}; std::string const output{Argv[4]}; auto const dynamic{Argc > 5 && std::string_view{Argv[5]} == "1"}; - start_tools(Argc, Argv); + if (dynamic && extension_of(input) != ".e3d") { + // the game prepares a vehicle's text model only after the vehicle marked its animated parts (WillBeAnimated); made here + // at once, their vertices would be turned into the frame of the model instead of keeping their matrices + std::cerr << "a vehicle's model is converted from the .e3d the game makes of it (convertmodels), not from its .t3d\n"; + return 2; + } + if (false == start_tools(Argc, Argv)) + return 2; TModel3d source; if (false == load_source(input, dynamic, source)) return 1; diff --git a/model/e4d/e4d_io.cpp b/model/e4d/e4d_io.cpp index d26f7823b..782f472ec 100644 --- a/model/e4d/e4d_io.cpp +++ b/model/e4d/e4d_io.cpp @@ -15,12 +15,14 @@ http://mozilla.org/MPL/2.0/. #include "meshoptimizer.h" #include "zstd.h" +#include #include #include #include #include #include #include +#include namespace e4d { @@ -339,6 +341,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: @@ -375,6 +379,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"); @@ -388,15 +394,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; } @@ -521,11 +531,18 @@ bool file_reader::read_streams(std::vector const &Sections, model std::vector streams; std::ranges::copy_if(Sections, std::back_inserter(streams), [](section_entry const &Entry) { return is_vertex_stream(Entry.id); }); std::vector errors(streams.size()); + // a stream which can't be had (its memory, say) is an error of the file like the others: an exception left in a thread + // of its own would end the program auto const unpack_one{[this, &streams, &errors, &Model](std::size_t const Index) { - file_reader worker{m_file, m_options}; - bool handled{false}; - if (false == worker.vertex_stream(streams[Index], Model, handled)) - errors[Index] = std::move(worker.m_error); + try { + file_reader worker{m_file, m_options}; + bool handled{false}; + if (false == worker.vertex_stream(streams[Index], Model, handled)) // NOSONAR: S2259 false positive, worker is a local object and no pointer is null here + errors[Index] = std::move(worker.m_error); + } + catch (std::exception const &Error) { + errors[Index] = std::format("section {} can't be unpacked: {}", fourcc_name(streams[Index].id), Error.what()); + } }}; { std::vector workers; @@ -541,6 +558,18 @@ bool file_reader::read_streams(std::vector const &Sections, model 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}; @@ -601,6 +630,17 @@ read_result file_reader::run(model &Model) { for (auto const &entry : sections) { if (is_vertex_stream(entry.id)) continue; + if (false == known_section(entry.id)) { + // a section this reader doesn't know: one the model needs is refused before its codec is looked at; one it can + // do without is passed over before it is unpacked, unless the tools keep it to write it back, and always when it + // is in the codec of the streams, which this reader unpacks only for the streams it knows + if ((entry.flags & section_flags::required) != 0) { + Model = model{}; + return {false, std::format("the model needs section {}, which this program doesn't know", fourcc_name(entry.id))}; + } + if (false == m_options.keep_unknown || (entry.flags & section_flags::meshopt) != 0) + continue; + } std::span bytes; if (false == unpack(entry, storage, bytes) || false == dispatch(entry, section_bytes{entry.id, bytes}, Model)) { Model = model{}; @@ -842,11 +882,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 6ead18c0c..6166e8ea8 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}); @@ -506,13 +517,49 @@ TEST_CASE("e4d: the streams in the codecs of meshoptimizer, with and without zst CHECK(loaded.nodes.empty()); } +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: an unknown section in the codec of the streams doesn't stop the reading, unless the model needs it") +{ + // a later version may put a new optional stream in the codec; this one passes it over, the tools too + auto file{sample_file(false)}; + auto const offset{entry_offset(file, e4d::fourcc("ZZZZ"))}; + auto entry{get_at(file, offset)}; + entry.flags |= e4d::section_flags::meshopt; + put_at(file, offset, entry); + rehash(file); + e4d::model loaded; + auto const result{e4d::read(file, loaded, {true, true})}; + REQUIRE_MESSAGE(result.ok, result.error); + CHECK(loaded.unknown.empty()); + // one the model needs is refused as unknown, not for its codec + entry.flags |= e4d::section_flags::required; + put_at(file, offset, entry); + rehash(file); + auto const required{e4d::read(file, loaded, {true, true})}; + CHECK_FALSE(required.ok); + CHECK(required.error.find("doesn't know") != std::string::npos); +} + TEST_CASE("e4d: a file with random bytes changed is read or refused, never more") { // the sample, too small for the codecs, and the grid, in them for (auto const variant : {0, 1, 2}) { auto const compress{variant == 1}; auto const good{variant < 2 ? sample_file(compress) : e4d::write(grid_model(), {true, 9, true})}; - std::mt19937 random{static_cast(7 + variant * 4)}; + std::mt19937 random{static_cast(7 + variant * 4)}; // NOSONAR: seeded on purpose, the test changes the same bytes every run; nothing secret std::uniform_int_distribution position{0, good.size() - 1}; std::uniform_int_distribution value{0, 255}; for (int attempt = 0; attempt < 3000; ++attempt) { @@ -533,7 +580,7 @@ TEST_CASE("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)};