18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-02 17:46:48 +01:00

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.
This commit is contained in:
maj00r
2026-11-29 17:25:23 +01:00
parent d6bace0fda
commit 0d095e225c
7 changed files with 128 additions and 29 deletions
+4 -1
View File
@@ -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 <plik.e4d>` (zawartość jako tekst) i `eu07 -e4d validate <plik.e4d>` (sprawdzenie
pliku wraz z hashem zawartości).
+1
View File
@@ -2729,6 +2729,7 @@ void TSubModel::BinInit(TSubModel *s, float4x4 *m, std::vector<std::string> *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
+3
View File
@@ -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
+3 -5
View File
@@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/.
#include "model/e4d/e4d_build.h"
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <limits>
#include <unordered_map>
@@ -58,11 +59,8 @@ std::unordered_map<std::uint32_t, std::size_t> matrix_lookup(model const &Model)
glm::mat4 node_transform(model const &Model, std::uint32_t const Node, std::unordered_map<std::uint32_t, std::size_t> 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);
}
+52 -14
View File
@@ -21,8 +21,11 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/utilities.h"
#include "utilities/wholefile.h"
#include <charconv>
#include <format>
#include <iostream>
#include <optional>
#include <unordered_map>
namespace e4d {
@@ -63,8 +66,16 @@ class converter {
model m_model;
bool m_userdata{false};
std::vector<std::uint32_t> m_stars; // the nodes whose STAR components wait for their meshes
std::unordered_map<TSubModel const *, std::uint32_t> 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<std::uint32_t>(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<std::uint32_t> {
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<std::uint16_t>(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;
+38 -7
View File
@@ -14,8 +14,10 @@ http://mozilla.org/MPL/2.0/.
#include "zstd.h"
#include <array>
#include <format>
#include <span>
#include <unordered_set>
namespace e4d {
@@ -283,6 +285,8 @@ bool section_bytes::strings(std::vector<std::string> &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<section_en
Entries.resize(Header.section_count);
if (false == Entries.empty())
std::memcpy(Entries.data(), m_file.data() + Header.toc_offset, tablesize);
std::vector<std::uint32_t> seen;
std::unordered_set<std::uint32_t> 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<std::byte> &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<std::byte> 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<std::byte const> 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<std::uint32_t> 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<std::int64_t>(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);
}
}
+27 -2
View File
@@ -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<std::byte> &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",
[&section](std::vector<std::byte> &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",
[&section](std::vector<std::byte> &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<std::size_t> position{0, good.size() - 1};
std::uniform_int_distribution<int> 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<float> coordinate{-1.f, 1.f};
for (int attempt = 0; attempt < 2000; ++attempt) {
glm::vec3 normal{coordinate(random), coordinate(random), coordinate(random)};