From d8e6c6e36eedf848eec93d8fbac91eea3ae23cfa Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:55:57 +0100 Subject: [PATCH] feat(model): the game loads .e4d models, behind modelformat e4d in eu07.ini Stage 2 of the E4D model format. With modelformat e4d a model with an .e4d file beside its .e3d / .t3d is loaded from it; legacy, the default, leaves the .e4d files alone and the game loads models exactly as before. The key is written to the log at the start. - TModel3d::LoadFromE4D (model/e4d/e4d_load.cpp) builds the same tree of submodels LoadFromBinFile builds from E3D, and both go on through the same finish_binary() (the end of the E3D loading, moved out of deserialize unchanged). .mmd, events, GetFromName and the editor work as before. A file that can't be read or isn't valid is logged and the .e3d / .t3d is loaded instead. TModelsManager finds a model which comes as an .e4d alone. - Format additions found by comparing loads (the format isn't released, so still version 1.0): - the LMAT component: the material of a node without geometry (light points, rotators), whose light threshold, colours and material the lights use; - node_flags::no_transform: an E3D submodel without a matrix, told apart from one with the identity matrix; - section_flags::meshopt: the vertex and index streams in the codecs of meshoptimizer (vertex codec version 1, index sequence codec), lossless, several times faster to unpack than zstd on this data. zstd packs the other sections; zstd over the coded streams is an option for archives (write_options::compress_streams). - meshoptimizer v1.3 (MIT) as a submodule in ref/meshoptimizer; only its vertex and index codecs are built, into eu07_core. - Loading speed: the big streams unpack on threads of their own, and a model of 100 000 vertices or more fills the vertices and indices of its submodels on up to 8 threads (std::jthread); the vertices are written once, without the zeroes of resize(). QTangent decoding takes the two matrix columns it needs without a square root. - eu07 -e4d diff [dynamic] compares the two loads submodel by submodel and times them. Checked: - 250 random models of the installed game: all convert, and loaded from E4D they give the same tree, names, flags, materials and indices as from E3D; positions and UVs bit for bit, transforms within 6.5e-5, normals within 0.03 deg (4 vertices with a broken normal in the E3D get a proper one). - Size 39% of the E3D (263 MB against 682 MB). Load outside the game, with the files in the system's cache: 516 ms against 561 ms, 0.75 of the time for the models of 5 MB and more, 1.21 for the smaller ones. - In the game on Vulkan (self-test, the same 250 models): 3.05 s against 3.15 s to load them, the same frame time and device memory, the picture within 1/255 of the legacy one. - Unit tests 1189/1189, among them the codecs with and without zstd, a codec on a wrong section and a cut stream. Not built with GCC here. No asset change is needed: the game data has no .e4d files, and the release doesn't read them. --- .gitmodules | 3 + CMakeLists.txt | 6 + docs/e4d-format.md | 11 +- model/MdlMngr.cpp | 4 + model/Model3d.cpp | 13 ++ model/Model3d.h | 5 + model/e4d/e4d_build.cpp | 26 ++- model/e4d/e4d_build.h | 2 + model/e4d/e4d_convert.cpp | 221 +++++++++++++++++++++++-- model/e4d/e4d_format.h | 12 ++ model/e4d/e4d_io.cpp | 236 +++++++++++++++++++++++--- model/e4d/e4d_io.h | 4 + model/e4d/e4d_load.cpp | 340 ++++++++++++++++++++++++++++++++++++++ ref/meshoptimizer | 1 + tests/unit/test_e4d.cpp | 108 +++++++++++- utilities/Globals.cpp | 10 ++ utilities/Globals.h | 1 + 17 files changed, 955 insertions(+), 48 deletions(-) create mode 100644 model/e4d/e4d_load.cpp create mode 160000 ref/meshoptimizer diff --git a/.gitmodules b/.gitmodules index 0fd7ef906..b9c60f72a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -36,3 +36,6 @@ path = ref/wamr url = https://github.com/bytecodealliance/wasm-micro-runtime shallow = true +[submodule "ref/meshoptimizer"] + path = ref/meshoptimizer + url = https://github.com/zeux/meshoptimizer.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 4dece9499..2622bb8f0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -177,6 +177,7 @@ set(SOURCES "EU07.cpp" "export_e3d_standalone.cpp" "model/e4d/e4d_convert.cpp" +"model/e4d/e4d_load.cpp" "export_btf_standalone.cpp" "nodebank_previews_standalone.cpp" "world/Event.cpp" @@ -798,6 +799,9 @@ set(CORE_SOURCES "model/e4d/e4d_build.cpp" "model/e4d/e4d_dump.cpp" "${DEPS_DIR}/zstd/zstd.c" +# the codecs of the vertex and index streams of E4D +"${DEPS_DIR}/meshoptimizer/src/vertexcodec.cpp" +"${DEPS_DIR}/meshoptimizer/src/indexcodec.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) @@ -837,6 +841,7 @@ target_include_directories(eu07_settings INTERFACE "${DEPS_DIR}/glad/include" "${DEPS_DIR}/dds-ktx/include" "${DEPS_DIR}/zstd" + "${DEPS_DIR}/meshoptimizer/src" "${CMAKE_BINARY_DIR}/geninc" "${GLOBAL_INCLUDE_DIR}") @@ -877,6 +882,7 @@ if(NOT ${CMAKE_VERSION} VERSION_LESS "3.16.0") target_precompile_headers(eu07_core PRIVATE "$<$:${CMAKE_CURRENT_SOURCE_DIR}/stdafx.h>") set_source_files_properties("/glad/src/glad.c" "ref/dds-ktx/src/dds-ktx.c" "ref/zstd/zstd.c" "stb/stb_image.c" "imgui/imgui.cpp" "imgui/imgui_demo.cpp" "imgui/imgui_draw.cpp" "imgui/imgui_widgets.cpp" "imgui/imgui_tables.cpp" "imgui/imgui_impl_glfw.cpp" "imgui/ImGuizmo.cpp" + "ref/meshoptimizer/src/vertexcodec.cpp" "ref/meshoptimizer/src/indexcodec.cpp" PROPERTIES SKIP_PRECOMPILE_HEADERS TRUE) endif() endif() diff --git a/docs/e4d-format.md b/docs/e4d-format.md index 9646efcd5..105b6375d 100644 --- a/docs/e4d-format.md +++ b/docs/e4d-format.md @@ -42,7 +42,7 @@ Stan: wersja 1.0, etap 1 (format, czytnik, pisarz, konwersja z E3D/T3D). Gra jes | Typ | Pole | |---|---| | u32 | FourCC | -| u32 | flagi: bit 0 = wymagana, bit 1 = zstd | +| u32 | flagi: bit 0 = wymagana, bit 1 = zstd, bit 2 = kodek meshoptimizer (tylko strumienie wierzchołków i indeksów) | | u64 | offset w pliku | | u64 | rozmiar w pliku | | u64 | rozmiar po rozpakowaniu | @@ -50,6 +50,12 @@ Stan: wersja 1.0, etap 1 (format, czytnik, pisarz, konwersja z E3D/T3D). Gra jes Sekcje są wyrównane do 16 B, a strumienie wierzchołków i indeksów do 64 B. Sekcja może być skompresowana zstd. Każda sekcja występuje najwyżej raz. +Strumienie wierzchołków (`VPOS`, `VATT`, `VSKN`, `VSKW`, `VUSR`, `VBND`) mogą być zapisane kodekiem wierzchołków +meshoptimizera (wersja 1), a strumienie indeksów (`IDX2`, `IDX4`) jego kodekiem sekwencji indeksów (`ref/meshoptimizer`, +licencja MIT). Kodek jest bezstratny co do bajtu, a rozpakowuje się kilka razy szybciej niż zstd na tych danych. Gdy sekcja ma +obie flagi, zstd pakuje wynik kodeka; czytnik najpierw rozpakowuje zstd (najwyżej do granicy rozmiaru kodeka), potem dekoduje. +Rozmiar po rozpakowaniu we wpisie spisu to zawsze rozmiar surowego strumienia. Flaga kodeka na innej sekcji odrzuca plik. + ## Sekcje `[T]` oznacza tablicę: `u32 count`, `u32 stride`, potem `count` rekordów co `stride` bajtów. `[S]` oznacza surowy @@ -93,7 +99,7 @@ zakresy siatek skinowanych. | 0 | u32 | nazwa (string) | | 4 | i32 | rodzic, −1 dla korzenia | | 8 | u32 | koniec poddrzewa: indeks za ostatnim węzłem poddrzewa | -| 12 | u32 | flagi: bit 0 animowany, bit 1 ukryty, bit 2 przekształcenie w `XFRM` | +| 12 | u32 | flagi: bit 0 animowany, bit 1 ukryty, bit 2 przekształcenie w `XFRM`, bit 3 bez własnego przekształcenia (submodel E3D bez macierzy; TRS to tożsamość) | | 16 | f32 × 3 | translacja | | 28 | f32 × 4 | obrót, kwaternion x y z w | | 44 | f32 × 3 | skala | @@ -204,6 +210,7 @@ Odwołania wewnątrz danych to indeksy: string, węzeł albo komponent; `0xFFFFF | `LANM` | animacja E3D (`TAnimType`): `u32` | | `LTXT` | wyświetlacz tekstu E3D (`TP_TEXT`); dzieci węzła to znaki nazwane swoim znakiem. Bez danych. | | `STAR` | gwiazdy E3D (`TP_STARS`): `u32 count`, potem kolory RGB `u32` (jak w E3D), po jednym na wierzchołek siatki węzła | +| `LMAT` | materiał węzła bez geometrii (punkt świetlny, rotator), który E3D trzyma w każdym submodelu: `u32` slot `MATL`. Z niego światło bierze próg zapalenia (`fLight`), kolory i materiał | ## Konwersja z E3D i T3D diff --git a/model/MdlMngr.cpp b/model/MdlMngr.cpp index 72d103db7..71822523a 100644 --- a/model/MdlMngr.cpp +++ b/model/MdlMngr.cpp @@ -166,6 +166,10 @@ std::string TModelsManager::find_on_disk( std::string const &Name ) { std::vector extensions { { ".e3d" }, { ".t3d" } }; + if( Global.modelformat_e4d ) { + // a model may come as an .e4d alone + extensions.emplace_back( ".e4d" ); + } for( auto const &extension : extensions ) { if( false == FileCased( Name + extension ).empty() ) { diff --git a/model/Model3d.cpp b/model/Model3d.cpp index f3ddbc4a5..a7d3d5cb3 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1875,6 +1875,13 @@ 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)) + { + // modelformat e4d: the .e4d made from the model takes its place; one which doesn't load leaves the .e3d / .t3d to go on + asBinary = ""; + Init(); + assign_lod_ranges(Root, name); + } else if (false == binaryfile.empty()) { LoadFromBinFile(binaryfile, dynamic); @@ -2641,6 +2648,12 @@ void TModel3d::deserialize(std::istream &s, size_t size, bool dynamic) if (!Root) throw std::runtime_error("e3d: no submodels"); + finish_binary(dynamic, hastangents); +} + +// the submodels read from a file (E3D or E4D) tied together, their materials looked up and their geometry handed to the renderer +void TModel3d::finish_binary(bool const dynamic, bool const hastangents) +{ for (size_t i = 0; (int)i < iSubModelsCount; ++i) { Root[i].BinInit(Root, Matrices.data(), &Textures, &Names, dynamic); diff --git a/model/Model3d.h b/model/Model3d.h index 9be9a4f0f..8e75ae274 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -311,6 +311,8 @@ private: bool m_lodboundsfound { false }; std::uint32_t m_stateversion { 0 }; // see state_version() + void finish_binary( bool dynamic, bool hastangents ); + public: TModel3d() = default; ~TModel3d(); @@ -336,6 +338,9 @@ public: void AddTo(TSubModel *tmp, TSubModel *SubModel); void LoadFromTextFile(std::string const &FileName, bool dynamic); void LoadFromBinFile(std::string const &FileName, bool dynamic); + // the model from an E4D file (model/e4d/e4d_load.cpp), as LoadFromBinFile builds it from E3D. returns false, with the reason + // in the log and nothing loaded, when the file can't be read or isn't valid + bool LoadFromE4D(std::string const &FileName, bool dynamic); bool LoadFromFile(std::string const &FileName, bool dynamic); TSubModel *AppendChildFromGeometry(const std::string &name, const std::string &parent, const gfx::vertex_array &vertices, const gfx::index_array &indices); void SaveToBinFile(std::string const &FileName); diff --git a/model/e4d/e4d_build.cpp b/model/e4d/e4d_build.cpp index d20232856..8526fbfdb 100644 --- a/model/e4d/e4d_build.cpp +++ b/model/e4d/e4d_build.cpp @@ -139,12 +139,20 @@ std::array encode_qtangent(tangent_frame const &Frame) { } tangent_frame decode_qtangent(std::array const &Packed) { - glm::quat rotation{Packed[3] / snorm16_scale, Packed[0] / snorm16_scale, Packed[1] / snorm16_scale, Packed[2] / snorm16_scale}; + // the first and the third column of the rotation matrix of the quaternion, which 2 / |q|^2 makes unit without a square root: + // what glm::mat3_cast(glm::normalize(q)) gives, for the two columns needed, at a part of the cost (this runs for every vertex) + auto const x{Packed[0] / snorm16_scale}; + auto const y{Packed[1] / snorm16_scale}; + auto const z{Packed[2] / snorm16_scale}; + auto const w{Packed[3] / snorm16_scale}; tangent_frame frame; - frame.handedness = rotation.w < 0.f ? -1.f : 1.f; - auto const matrix{glm::mat3_cast(glm::normalize(rotation))}; - frame.tangent = matrix[0]; - frame.normal = matrix[2]; + frame.handedness = w < 0.f ? -1.f : 1.f; + auto const norm{x * x + y * y + z * z + w * w}; + if (norm < 1e-12f) + return frame; + auto const s{2.f / norm}; + frame.tangent = {1.f - s * (y * y + z * z), s * (x * y + w * z), s * (x * z - w * y)}; + frame.normal = {s * (x * z + w * y), s * (y * z - w * x), 1.f - s * (x * x + y * y)}; return frame; } @@ -152,6 +160,14 @@ glm::mat4 local_transform(model const &Model, std::uint32_t const Node) { return node_transform(Model, Node, matrix_lookup(Model)); } +std::vector local_transforms(model const &Model) { + auto const matrices{matrix_lookup(Model)}; + std::vector transforms(Model.nodes.size()); + for (std::uint32_t idx = 0; idx < Model.nodes.size(); ++idx) + transforms[idx] = node_transform(Model, idx, matrices); + return transforms; +} + std::vector model_transforms(model const &Model) { auto const matrices{matrix_lookup(Model)}; std::vector transforms(Model.nodes.size()); diff --git a/model/e4d/e4d_build.h b/model/e4d/e4d_build.h index 491425e6f..e7bd1f9ee 100644 --- a/model/e4d/e4d_build.h +++ b/model/e4d/e4d_build.h @@ -30,6 +30,8 @@ tangent_frame decode_qtangent(std::array const &Packed); // the transform of the node within its parent: the matrix of XFRM, or T * R * S glm::mat4 local_transform(model const &Model, std::uint32_t Node); +// the transforms of all nodes within their parents +std::vector local_transforms(model const &Model); // the transforms of all nodes within the model, in one pass (the parents come first) std::vector model_transforms(model const &Model); diff --git a/model/e4d/e4d_convert.cpp b/model/e4d/e4d_convert.cpp index dee1a6415..4fbfaa366 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 { @@ -55,6 +58,7 @@ class converter { void indices(TSubModel const &Submodel, gfx::index_array const &Indices, primitive_record &Primitive); void stars(gfx::vertex_array const &Vertices, std::uint32_t Node); std::uint32_t material(TSubModel const &Submodel); + static bool has_geometry(TSubModel const &Submodel); void light_slots(); bool any_userdata(TSubModel const *First) const; @@ -114,8 +118,10 @@ void converter::node(TSubModel &Submodel, std::int32_t const Parent) { void converter::transform(TSubModel const &Submodel, std::uint32_t const Node) { auto const *matrix{Submodel.GetMatrix()}; - if (matrix == nullptr) + if (matrix == nullptr) { + m_model.nodes[Node].flags |= node_flags::no_transform; return; + } auto const transform{glm::make_mat4(matrix->readArray())}; if (set_transform(m_model.nodes[Node], transform)) return; @@ -150,6 +156,16 @@ void converter::components(TSubModel const &Submodel, std::uint32_t const Node) m_model.add_component(component::legacy_animation, target_kind::node, Node, payload_writer{}.put(payload::legacy_animation{static_cast(Submodel.b_Anim)}).data()); if (Submodel.eType == TP_TEXT) m_model.add_component(component::legacy_text, target_kind::node, Node, {}); + if (false == has_geometry(Submodel)) { + // a light point or a rotator: E3D keeps the material and the colours of every submodel, and the lights use them + auto const index{material(Submodel)}; + m_model.add_component(component::legacy_material, target_kind::node, Node, payload_writer{}.put(payload::legacy_material{index}).data()); + } +} + +bool converter::has_geometry(TSubModel const &Submodel) { + auto const drawable{(Submodel.eType >= 0 && Submodel.eType <= gl_primitive_last) || Submodel.eType == TP_STARS}; + return drawable && Submodel.m_geometry.handle != null_handle && Submodel.m_geometry.vertex_count > 0 && false == GfxRenderer->Vertices(Submodel.m_geometry.handle).empty(); } std::uint32_t converter::material(TSubModel const &Submodel) { @@ -214,12 +230,9 @@ void converter::stars(gfx::vertex_array const &Vertices, std::uint32_t const Nod } void converter::geometry(TSubModel const &Submodel, std::uint32_t const Node) { - auto const drawable{(Submodel.eType >= 0 && Submodel.eType <= gl_primitive_last) || Submodel.eType == TP_STARS}; - if (false == drawable || Submodel.m_geometry.handle == null_handle || Submodel.m_geometry.vertex_count <= 0) + if (false == has_geometry(Submodel)) return; auto const &vertexdata{GfxRenderer->Vertices(Submodel.m_geometry.handle)}; - if (vertexdata.empty()) - return; primitive_record primitive; primitive.base_vertex = static_cast(m_model.positions.size()); primitive.vertex_count = static_cast(vertexdata.size()); @@ -271,6 +284,187 @@ std::string extension_of(std::string const &Path) { return dot == std::string::npos ? std::string{} : ToLower(Path.substr(dot)); } +// the model loaded the way the converter and the comparison take it: with the null renderer, which keeps the geometry +// Milliseconds gets the time of reading the file into the submodels, without Init() +bool load_source(std::string const &Input, bool const Dynamic, TModel3d &Source, double *Milliseconds = nullptr) { + auto const start{std::chrono::steady_clock::now()}; + if (extension_of(Input) == ".e3d") + Source.LoadFromBinFile(Input, Dynamic); + else if (extension_of(Input) == ".e4d") + Source.LoadFromE4D(Input, Dynamic); + else + Source.LoadFromTextFile(Input, Dynamic); + if (Milliseconds != nullptr) + *Milliseconds = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + Source.Init(); + if (Source.GetSMRoot() == nullptr) { + std::cerr << std::format("can't load model \"{}\"\n", Input); + return false; + } + return true; +} + +void start_tools(int const Argc, char *Argv[]) { + Global.iConvertModels = Argc > 6 ? std::stoi(Argv[6]) : 0; + Global.iWriteLogEnabled = 2; + GfxRenderer = gfx_renderer_factory::get_instance()->create("null"); +} + +// the differences between two loaded models, submodel by submodel in the order of the tree +class model_diff { + public: + void compare(TSubModel *Left, TSubModel *Right); + std::vector differences; + std::size_t submodels{0}; + std::size_t vertices{0}; + float matrix{0.f}; // the largest difference of an element of a transform + float normal{0.f}; // the largest angle between normals, in degrees + float tangent{0.f}; // the same for the tangents + std::size_t bent{0}; // the vertices whose normal turned by more than half a degree + + private: + void fields(TSubModel const &Left, TSubModel const &Right); + void light(TSubModel const &Left, TSubModel const &Right); + void geometry(TSubModel const &Left, TSubModel const &Right); + void vertex(TSubModel const &Left, gfx::basic_vertex const &A, gfx::basic_vertex const &B, std::size_t Index); + template void check(TSubModel const &Submodel, std::string_view What, Type_ const &A, Type_ const &B); + void report(TSubModel const &Submodel, std::string_view What); +}; + +void model_diff::report(TSubModel const &Submodel, std::string_view const What) { + if (differences.size() < 50) + differences.push_back(std::format("submodel {} \"{}\": {}", submodels, Submodel.pName, What)); +} + +template void model_diff::check(TSubModel const &Submodel, std::string_view const What, Type_ const &A, Type_ const &B) { + if (false == (A == B)) + report(Submodel, What); +} + +void model_diff::compare(TSubModel *Left, TSubModel *Right) { + while (Left != nullptr && Right != nullptr) { + ++submodels; + fields(*Left, *Right); + compare(Left->Child, Right->Child); + if ((Left->Child == nullptr) != (Right->Child == nullptr)) + report(*Left, "children differ"); + Left = Left->Next; + Right = Right->Next; + } + if ((Left == nullptr) != (Right == nullptr)) + differences.emplace_back("the trees differ in the number of submodels"); +} + +void model_diff::fields(TSubModel const &Left, TSubModel const &Right) { + check(Left, "name", Left.pName, Right.pName); + check(Left, "type", Left.eType, Right.eType); + check(Left, "flags", Left.iFlags, Right.iFlags); + check(Left, "visibility", Left.iVisible, Right.iVisible); + check(Left, "animation", Left.b_Anim, Right.b_Anim); + check(Left, "material name", Left.m_materialname, Right.m_materialname); + // the null renderer gives each fetch of a material a handle of its own, so a fetched material is told by its name + if (Left.m_material > 0 && Right.m_material > 0) + check(Left, "material", GfxRenderer->Material(Left.m_material)->GetName(), GfxRenderer->Material(Right.m_material)->GetName()); + else + check(Left, "material", Left.m_material, Right.m_material); + check(Left, "selfillum", Left.fLight, Right.fLight); + check(Left, "colours", std::tie(Left.f4Ambient, Left.f4Diffuse, Left.f4Specular, Left.f4Emision), std::tie(Right.f4Ambient, Right.f4Diffuse, Right.f4Specular, Right.f4Emision)); + check(Left, "ranges", std::tie(Left.fSquareMinDist, Left.fSquareMaxDist), std::tie(Right.fSquareMinDist, Right.fSquareMaxDist)); + check(Left, "normalisation", Left.m_normalizenormals, Right.m_normalizenormals); + check(Left, "matrix present", Left.GetMatrix() == nullptr, Right.GetMatrix() == nullptr); + if (Left.GetMatrix() != nullptr && Right.GetMatrix() != nullptr) { + for (int idx = 0; idx < 16; ++idx) + matrix = std::max(matrix, std::abs(Left.GetMatrix()->e[idx] - Right.GetMatrix()->e[idx])); + } + if (Left.eType == TP_FREESPOTLIGHT) + light(Left, Right); + geometry(Left, Right); +} + +void model_diff::light(TSubModel const &Left, TSubModel const &Right) { + check(Left, "light power and size", std::tie(Left.fHotspotPower, Left.fLightRadius), std::tie(Right.fHotspotPower, Right.fLightRadius)); + check(Left, "light attenuation", std::tie(Left.fNearAttenStart, Left.fNearAttenEnd, Left.bUseNearAtten, Left.iFarAttenDecay, Left.fFarDecayRadius), + std::tie(Right.fNearAttenStart, Right.fNearAttenEnd, Right.bUseNearAtten, Right.iFarAttenDecay, Right.fFarDecayRadius)); + check(Left, "light cones", std::tie(Left.fCosFalloffAngle, Left.fCosHotspotAngle), std::tie(Right.fCosFalloffAngle, Right.fCosHotspotAngle)); + check(Left, "light flags", std::tie(Left.bShadeSelf, Left.bCastShadows, Left.bSoftFalloff, Left.bLightOnly), + std::tie(Right.bShadeSelf, Right.bCastShadows, Right.bSoftFalloff, Right.bLightOnly)); +} + +float angle_between(glm::vec3 const &A, glm::vec3 const &B) { + auto const lengths{glm::length(A) * glm::length(B)}; + if (lengths < 1e-12f) + return glm::length(A - B) < 1e-6f ? 0.f : 180.f; + return glm::degrees(std::acos(std::clamp(glm::dot(A, B) / lengths, -1.f, 1.f))); +} + +void model_diff::vertex(TSubModel const &Left, gfx::basic_vertex const &A, gfx::basic_vertex const &B, std::size_t const Index) { + if (A.position != B.position || A.texture != B.texture) { + report(Left, std::format("vertex {} has another position or uv", Index)); + return; + } + if (Left.eType == TP_STARS) { + // the colour of a star, kept in 8 bits a channel + if (glm::any(glm::greaterThan(glm::abs(A.normal - B.normal), glm::vec3{0.5f / 255.f + 1e-6f}))) + report(Left, std::format("star {} has another colour", Index)); + return; + } + auto const turned{angle_between(A.normal, B.normal)}; + normal = std::max(normal, turned); + if (turned > 0.5f) + ++bent; + tangent = std::max(tangent, angle_between(glm::vec3{A.tangent}, glm::vec3{B.tangent})); +} + +void model_diff::geometry(TSubModel const &Left, TSubModel const &Right) { + auto const lefthandle{Left.m_geometry.handle}; + auto const righthandle{Right.m_geometry.handle}; + auto const &leftvertices{lefthandle != null_handle ? GfxRenderer->Vertices(lefthandle) : gfx::vertex_array{}}; + auto const &rightvertices{righthandle != null_handle ? GfxRenderer->Vertices(righthandle) : gfx::vertex_array{}}; + auto const drawable{(Left.eType >= 0 && Left.eType <= gl_primitive_last) || Left.eType == TP_STARS}; + if (false == drawable) + return; + if (leftvertices.size() != rightvertices.size()) { + report(Left, std::format("{} vertices against {}", leftvertices.size(), rightvertices.size())); + return; + } + auto const &leftindices{lefthandle != null_handle ? GfxRenderer->Indices(lefthandle) : gfx::index_array{}}; + auto const &rightindices{righthandle != null_handle ? GfxRenderer->Indices(righthandle) : gfx::index_array{}}; + check(Left, "indices", leftindices, rightindices); + auto const &leftuser{lefthandle != null_handle ? GfxRenderer->UserData(lefthandle) : gfx::userdata_array{}}; + auto const &rightuser{righthandle != null_handle ? GfxRenderer->UserData(righthandle) : gfx::userdata_array{}}; + auto const sameuser{std::ranges::equal(leftuser, rightuser, [](gfx::vertex_userdata const &A, gfx::vertex_userdata const &B) { return A.data == B.data; })}; + // a model with user data gives the submodels without any of their own the default value + if (false == sameuser && false == leftuser.empty()) + report(Left, "user data"); + for (std::size_t idx = 0; idx < leftvertices.size(); ++idx) + vertex(Left, leftvertices[idx], rightvertices[idx], idx); + vertices += leftvertices.size(); +} + +int command_diff(int const Argc, char *Argv[]) { + if (Argc < 5) { + std::cerr << "usage: -e4d diff [dynamic 0|1]\n"; + return 2; + } + start_tools(Argc, Argv); + auto const dynamic{Argc > 5 && std::string_view{Argv[5]} == "1"}; + TModel3d source; + TModel3d converted; + double sourcetime{0.0}; + double convertedtime{0.0}; + if (false == load_source(Argv[3], dynamic, source, &sourcetime) || false == load_source(Argv[4], dynamic, converted, &convertedtime)) + return 1; + model_diff diff; + diff.compare(source.GetSMRoot(), converted.GetSMRoot()); + for (auto const &difference : diff.differences) + std::cout << difference << '\n'; + std::cout << std::format("{}: {} submodels, {} vertices, {} differences; transforms within {:.2g}, normals within {:.3f} deg ({} past 0.5 deg), tangents within {:.3f} deg\n", Argv[4], + diff.submodels, diff.vertices, diff.differences.size(), diff.matrix, diff.normal, diff.bent, diff.tangent); + // with the files in the system's cache or not, as they came: a run right after another one of the same files finds them there + std::cout << std::format("load: source {:.2f} ms, e4d {:.2f} ms\n", sourcetime, convertedtime); + return diff.differences.empty() ? 0 : 1; +} + int command_convert(int const Argc, char *Argv[]) { if (Argc < 5) { std::cerr << "usage: -e4d convert [dynamic 0|1] [convertmodels flags]\n"; @@ -279,19 +473,10 @@ 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; - Global.iWriteLogEnabled = 2; - GfxRenderer = gfx_renderer_factory::get_instance()->create("null"); + start_tools(Argc, Argv); TModel3d source; - if (extension_of(input) == ".e3d") - source.LoadFromBinFile(input, dynamic); - else - source.LoadFromTextFile(input, dynamic); - source.Init(); - if (source.GetSMRoot() == nullptr) { - std::cerr << std::format("can't load model \"{}\"\n", input); + if (false == load_source(input, dynamic, source)) return 1; - } std::vector faults; auto converted{convert(source, faults)}; for (auto const &fault : faults) @@ -352,7 +537,9 @@ int run_command_line(int const Argc, char *Argv[]) { return command_read(Argc, Argv, true); if (command == "validate") return command_read(Argc, Argv, false); - std::cerr << "usage: -e4d convert|dump|validate ...\n"; + if (command == "diff") + return command_diff(Argc, Argv); + std::cerr << "usage: -e4d convert|dump|validate|diff ...\n"; return 2; } diff --git a/model/e4d/e4d_format.h b/model/e4d/e4d_format.h index 9f67d7ffc..e52985a15 100644 --- a/model/e4d/e4d_format.h +++ b/model/e4d/e4d_format.h @@ -78,6 +78,7 @@ constexpr std::uint32_t collision{fourcc("COLL")}; constexpr std::uint32_t legacy_animation{fourcc("LANM")}; constexpr std::uint32_t legacy_text{fourcc("LTXT")}; constexpr std::uint32_t legacy_stars{fourcc("STAR")}; +constexpr std::uint32_t legacy_material{fourcc("LMAT")}; } // namespace component struct file_header { @@ -111,6 +112,9 @@ static_assert(sizeof(section_entry) == 32); namespace section_flags { constexpr std::uint32_t required{0x1}; // a reader which doesn't know the section refuses the file constexpr std::uint32_t zstd{0x2}; +// a vertex stream in the vertex codec of meshoptimizer (version 1), an index stream in its index sequence codec; zstd, when +// set too, packs the result of the codec. only the vertex and index streams may have it +constexpr std::uint32_t meshopt{0x4}; } // the head of a section holding a table of records. the stride lets a later version add fields at the end of a record @@ -131,6 +135,7 @@ namespace node_flags { constexpr std::uint32_t animated{0x1}; // moved at run time, keeps its own transform constexpr std::uint32_t hidden{0x2}; // not drawn until something shows it constexpr std::uint32_t matrix{0x4}; // the transform is the matrix in XFRM, the TRS fields are only an approximation +constexpr std::uint32_t no_transform{0x8}; // no transform of its own (an E3D submodel without a matrix); the TRS fields are the identity } struct node_record { @@ -561,6 +566,13 @@ struct legacy_stars { static_assert(sizeof(legacy_stars) == 4); // STAR: the count, then count packed RGB colours (std::uint32_t), one for each vertex of the mesh of the node +// LMAT: the material of a node without geometry, which E3D keeps in every submodel: the light threshold, the colours and the +// material a light point or a rotator carries +struct legacy_material { + std::uint32_t material{no_index}; // in MATL +}; +static_assert(sizeof(legacy_material) == 4); + } // namespace payload } // namespace e4d diff --git a/model/e4d/e4d_io.cpp b/model/e4d/e4d_io.cpp index cd6c680c3..d26f7823b 100644 --- a/model/e4d/e4d_io.cpp +++ b/model/e4d/e4d_io.cpp @@ -12,9 +12,14 @@ http://mozilla.org/MPL/2.0/. #include "model/e4d/e4d_io.h" #include "model/e4d/e4d_dump.h" +#include "meshoptimizer.h" #include "zstd.h" #include +#include +#include +#include +#include #include namespace e4d { @@ -103,13 +108,58 @@ template void append_array(std::vector &Output, std: std::memcpy(Output.data() + offset, Values.data(), Values.size() * sizeof(Type_)); } +// which codec of meshoptimizer a stream may go through +enum class stream_codec { + none, + vertices, + indices +}; + struct pending_section { std::uint32_t id{0}; std::uint32_t flags{0}; std::size_t alignment{section_alignment}; std::vector data; + stream_codec codec{stream_codec::none}; + std::size_t element{0}; // the size of an element of the stream }; +// the sections smaller than this stay as they are, unpacking them costs more than reading them +constexpr std::size_t packing_threshold{512}; + +// the vertex codec of meshoptimizer, version 1, level 2 +constexpr int vertex_codec_version{1}; +constexpr int vertex_codec_level{2}; + +template std::size_t encode_indices(std::vector const &Data, std::vector &Encoded) { + std::vector indices(Data.size() / sizeof(Index_)); + std::memcpy(indices.data(), Data.data(), indices.size() * sizeof(Index_)); + auto const last{std::ranges::max(indices)}; + Encoded.resize(meshopt_encodeIndexSequenceBound(indices.size(), std::size_t{last} + 1)); + return meshopt_encodeIndexSequence(reinterpret_cast(Encoded.data()), Encoded.size(), indices.data(), indices.size()); +} + +// the stream in its codec. false when it has none, is too small, or the codec doesn't make it smaller +bool encode_stream(pending_section const &Section, std::vector &Encoded) { + if (Section.codec == stream_codec::none || Section.data.size() < packing_threshold || Section.data.size() % Section.element != 0) + return false; + auto const count{Section.data.size() / Section.element}; + std::size_t size{0}; + if (Section.codec == stream_codec::vertices) { + Encoded.resize(meshopt_encodeVertexBufferBound(count, Section.element)); + size = meshopt_encodeVertexBufferLevel(reinterpret_cast(Encoded.data()), Encoded.size(), Section.data.data(), count, Section.element, vertex_codec_level, + vertex_codec_version); + } + else if (Section.element == sizeof(std::uint16_t)) + size = encode_indices(Section.data, Encoded); + else + size = encode_indices(Section.data, Encoded); + if (size == 0 || size >= Section.data.size()) + return false; + Encoded.resize(size); + return true; +} + class file_builder { public: template void table(std::uint32_t const Id, std::vector const &Records, bool const Required) { @@ -120,12 +170,14 @@ class file_builder { append_array(data, Records); add(Id, Required, section_alignment, std::move(data)); } - template void stream(std::uint32_t const Id, std::vector const &Values, bool const Required) { + template void stream(std::uint32_t const Id, std::vector const &Values, bool const Required, stream_codec const Codec = stream_codec::none) { if (Values.empty() && false == Required) return; std::vector data; append_array(data, Values); add(Id, Required, gpu_alignment, std::move(data)); + m_sections.back().codec = Codec; + m_sections.back().element = sizeof(Type_); } void raw(std::uint32_t const Id, std::uint32_t const Flags, std::vector Data) { m_sections.push_back({Id, Flags & section_flags::required, section_alignment, std::move(Data)}); @@ -140,18 +192,17 @@ class file_builder { while (Output.size() % Alignment != 0) Output.push_back(std::byte{0}); } - static bool compress(pending_section const &Section, std::vector &Packed, int const Level); + static bool compress(std::span Data, std::vector &Packed, int Level); std::vector m_sections; }; -bool file_builder::compress(pending_section const &Section, std::vector &Packed, int const Level) { - // small sections stay as they are, unpacking them costs more than reading them - if (Section.data.size() < 512) +bool file_builder::compress(std::span const Data, std::vector &Packed, int const Level) { + if (Data.size() < packing_threshold) return false; - Packed.resize(ZSTD_compressBound(Section.data.size())); - auto const size{ZSTD_compress(Packed.data(), Packed.size(), Section.data.data(), Section.data.size(), Level)}; - if (ZSTD_isError(size) || size > Section.data.size() - Section.data.size() / 8) + Packed.resize(ZSTD_compressBound(Data.size())); + auto const size{ZSTD_compress(Packed.data(), Packed.size(), Data.data(), Data.size(), Level)}; + if (ZSTD_isError(size) || size > Data.size() - Data.size() / 8) return false; Packed.resize(size); return true; @@ -162,6 +213,7 @@ std::vector file_builder::finish(model const &Model, write_options co std::vector entries; entries.reserve(m_sections.size()); std::vector packed; + std::vector encoded; for (auto const §ion : m_sections) { pad_to(output, section.alignment); section_entry entry; @@ -169,13 +221,17 @@ std::vector file_builder::finish(model const &Model, write_options co entry.flags = section.flags; entry.offset = output.size(); entry.size = section.data.size(); - if (Options.compress && compress(section, packed, Options.level)) { + std::span bytes{section.data}; + auto const coded{Options.codec && encode_stream(section, encoded)}; + if (coded) { + entry.flags |= section_flags::meshopt; + bytes = encoded; + } + if (Options.compress && (false == coded || Options.compress_streams) && compress(bytes, packed, Options.level)) { entry.flags |= section_flags::zstd; - output.insert(output.end(), packed.begin(), packed.end()); - } - else { - output.insert(output.end(), section.data.begin(), section.data.end()); + bytes = packed; } + output.insert(output.end(), bytes.begin(), bytes.end()); entry.stored_size = output.size() - entry.offset; entries.push_back(entry); } @@ -294,6 +350,11 @@ class file_reader { bool read_entries(file_header const &Header, std::vector &Entries); bool unpack(section_entry const &Entry, std::vector &Storage, std::span &Bytes); bool dispatch(section_entry const &Entry, section_bytes const &Section, model &Model); + bool vertex_stream(section_entry const &Entry, model &Model, bool &Handled); + bool read_streams(std::vector const &Sections, model &Model); + template bool unpack_into(section_entry const &Entry, std::vector &Output, stream_codec Codec); + bool unzstd(section_entry const &Entry, std::size_t Limit, std::vector &Output); + bool decode(section_entry const &Entry, std::span Encoded, void *Output, std::size_t Element, stream_codec Codec); bool fail(std::string Error) { m_error = std::move(Error); return false; @@ -342,6 +403,8 @@ bool file_reader::read_entries(file_header const &Header, std::vector &Storage, std::span &Bytes) { auto const stored{m_file.subspan(Entry.offset, Entry.stored_size)}; + if ((Entry.flags & section_flags::meshopt) != 0) + return fail(std::format("section {} is in a codec only the vertex and index streams may be in", fourcc_name(Entry.id))); if ((Entry.flags & section_flags::zstd) == 0) { if (Entry.stored_size != Entry.size) return fail(std::format("section {} has {} bytes stored and {} declared", fourcc_name(Entry.id), Entry.stored_size, Entry.size)); @@ -359,6 +422,125 @@ bool file_reader::unpack(section_entry const &Entry, std::vector &Sto return true; } +// the zstd frame of the section, of at most Limit bytes +bool file_reader::unzstd(section_entry const &Entry, std::size_t const Limit, std::vector &Output) { + auto const stored{m_file.subspan(Entry.offset, Entry.stored_size)}; + auto const size{ZSTD_getFrameContentSize(stored.data(), stored.size())}; + if (size == ZSTD_CONTENTSIZE_UNKNOWN || size == ZSTD_CONTENTSIZE_ERROR || size > Limit) + return fail(std::format("section {} doesn't unpack to a size its codec can have", fourcc_name(Entry.id))); + Output.resize(static_cast(size)); + auto const unpacked{ZSTD_decompress(Output.data(), Output.size(), stored.data(), stored.size())}; + if (ZSTD_isError(unpacked) || unpacked != size) + return fail(std::format("section {} doesn't unpack to its {} bytes", fourcc_name(Entry.id), size)); + return true; +} + +bool file_reader::decode(section_entry const &Entry, std::span const Encoded, void *const Output, std::size_t const Element, stream_codec const Codec) { + auto const count{static_cast(Entry.size) / Element}; + auto const *data{reinterpret_cast(Encoded.data())}; + auto const result{Codec == stream_codec::vertices ? meshopt_decodeVertexBuffer(Output, count, Element, data, Encoded.size()) + : meshopt_decodeIndexSequence(Output, count, Element, data, Encoded.size())}; + if (result != 0) + return fail(std::format("section {} doesn't decode to its {} bytes", fourcc_name(Entry.id), Entry.size)); + return true; +} + +// a stream unpacked straight into its vector, without a copy in between: the vertices and the indices are most of the file +template bool file_reader::unpack_into(section_entry const &Entry, std::vector &Output, stream_codec const Codec) { + if (Entry.size % sizeof(Type_) != 0) + return fail(std::format("section {} of {} bytes isn't a whole number of elements of {} bytes", fourcc_name(Entry.id), Entry.size, sizeof(Type_))); + auto const stored{m_file.subspan(Entry.offset, Entry.stored_size)}; + if ((Entry.flags & section_flags::meshopt) != 0) { + auto const count{static_cast(Entry.size) / sizeof(Type_)}; + // the result of the codec is never larger than its bound, which caps what a broken zstd frame can claim + std::size_t bound{0}; + if constexpr (std::is_integral_v) + bound = meshopt_encodeIndexSequenceBound(count, std::size_t{std::numeric_limits::max()}); + else + bound = meshopt_encodeVertexBufferBound(count, sizeof(Type_)); + std::vector unpacked; + if ((Entry.flags & section_flags::zstd) != 0 && false == unzstd(Entry, bound, unpacked)) + return false; + auto const encoded{(Entry.flags & section_flags::zstd) != 0 ? std::span{unpacked} : stored}; + Output.resize(count); + return decode(Entry, encoded, Output.data(), sizeof(Type_), Codec); + } + if ((Entry.flags & section_flags::zstd) == 0) { + if (Entry.stored_size != Entry.size) + return fail(std::format("section {} has {} bytes stored and {} declared", fourcc_name(Entry.id), Entry.stored_size, Entry.size)); + Output.resize(Entry.size / sizeof(Type_)); + if (false == Output.empty()) + std::memcpy(Output.data(), stored.data(), Entry.size); + return true; + } + if (ZSTD_getFrameContentSize(stored.data(), stored.size()) != Entry.size) + return fail(std::format("section {} doesn't unpack to its {} bytes", fourcc_name(Entry.id), Entry.size)); + Output.resize(Entry.size / sizeof(Type_)); + auto const size{ZSTD_decompress(Output.data(), Entry.size, stored.data(), stored.size())}; + if (ZSTD_isError(size) || size != Entry.size) + return fail(std::format("section {} doesn't unpack to its {} bytes", fourcc_name(Entry.id), Entry.size)); + return true; +} + +bool file_reader::vertex_stream(section_entry const &Entry, model &Model, bool &Handled) { + using enum stream_codec; + Handled = true; + switch (Entry.id) { + case section::positions: return unpack_into(Entry, Model.positions, vertices); + case section::attributes: return unpack_into(Entry, Model.vertex_attributes, vertices); + case section::skin_weights: return unpack_into(Entry, Model.weights, vertices); + case section::skin_weights_wide: return unpack_into(Entry, Model.weights_wide, vertices); + case section::userdata: return unpack_into(Entry, Model.vertex_userdata, vertices); + case section::bindings: return unpack_into(Entry, Model.bindings, vertices); + case section::indices16: return unpack_into(Entry, Model.indices16, indices); + case section::indices32: return unpack_into(Entry, Model.indices32, indices); + default: Handled = false; return true; + } +} + +bool is_vertex_stream(std::uint32_t const Id) { + switch (Id) { + case section::positions: + case section::attributes: + case section::skin_weights: + case section::skin_weights_wide: + case section::userdata: + case section::bindings: + case section::indices16: + case section::indices32: return true; + default: return false; + } +} + +// a stream of this size or more unpacks on a thread of its own, beside the others +constexpr std::uint64_t parallel_stream_size{std::uint64_t{1} << 20}; + +// the vertex and index streams, the big ones at once: each goes into a vector of its own, and the errors are kept apart +// and told in the order of the sections +bool file_reader::read_streams(std::vector const &Sections, model &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()); + 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); + }}; + { + std::vector workers; + for (std::size_t idx = 0; idx < streams.size(); ++idx) { + if (streams[idx].size >= parallel_stream_size) + workers.emplace_back(unpack_one, idx); + else + unpack_one(idx); + } + } // the workers join here + if (auto const failed{std::ranges::find_if(errors, [](std::string const &Error) { return false == Error.empty(); })}; failed != errors.end()) + return fail(*failed); + return true; +} + bool file_reader::dispatch(section_entry const &Entry, section_bytes const &Section, model &Model) { std::string error; bool known{true}; @@ -412,7 +594,13 @@ read_result file_reader::run(model &Model) { Model.flags = header.flags; Model.source_hash = header.source_hash; std::vector storage; + if (false == read_streams(sections, Model)) { + Model = model{}; + return {false, m_error}; + } for (auto const &entry : sections) { + if (is_vertex_stream(entry.id)) + continue; std::span bytes; if (false == unpack(entry, storage, bytes) || false == dispatch(entry, section_bytes{entry.id, bytes}, Model)) { Model = model{}; @@ -587,6 +775,10 @@ bool valid_payload(model const &Model, component_record const &Record, std::span } case component::legacy_animation: return valid_fixed(reader); case component::legacy_stars: return valid_stars(Model, Record, reader); + case component::legacy_material: { + payload::legacy_material material; + return reader.get(material) && material.material < Model.materials.size(); + } default: return true; // a type of a later version, or a marker without data (LTXT) } } @@ -642,6 +834,8 @@ void validator::node(std::uint32_t const Index, node_record const &Node) { fault(std::format("node {} has mesh {} out of range", Index, Node.mesh)); if ((Node.flags & node_flags::matrix) != 0 && std::ranges::none_of(m_model.transforms, [Index](transform_record const &Transform) { return Transform.node == Index; })) fault(std::format("node {} has no matrix in XFRM", Index)); + if ((Node.flags & node_flags::matrix) != 0 && (Node.flags & node_flags::no_transform) != 0) + fault(std::format("node {} has a matrix in XFRM and no transform at once", Index)); component_ranges(Node.component_first, Node.component_count, target_kind::node, Index, std::format("node {}", Index)); } @@ -910,15 +1104,15 @@ std::vector write(model const &Model, write_options const &Options) { builder.add(section::component_data, false, section_alignment, Model.component_data); builder.table(section::bounds, Model.bounds, false); builder.table(section::edit, Model.edit, false); - builder.stream(section::positions, Model.positions, true); - builder.stream(section::attributes, Model.vertex_attributes, true); - builder.stream(section::skin_weights, Model.weights, false); - builder.stream(section::skin_weights_wide, Model.weights_wide, false); - builder.stream(section::userdata, Model.vertex_userdata, false); + builder.stream(section::positions, Model.positions, true, stream_codec::vertices); + builder.stream(section::attributes, Model.vertex_attributes, true, stream_codec::vertices); + builder.stream(section::skin_weights, Model.weights, false, stream_codec::vertices); + builder.stream(section::skin_weights_wide, Model.weights_wide, false, stream_codec::vertices); + builder.stream(section::userdata, Model.vertex_userdata, false, stream_codec::vertices); // required once present: the primitives which follow it draw wrong without it - builder.stream(section::bindings, Model.bindings, false == Model.bindings.empty()); - builder.stream(section::indices16, Model.indices16, false); - builder.stream(section::indices32, Model.indices32, false); + builder.stream(section::bindings, Model.bindings, false == Model.bindings.empty(), stream_codec::vertices); + builder.stream(section::indices16, Model.indices16, false, stream_codec::indices); + builder.stream(section::indices32, Model.indices32, false, stream_codec::indices); for (auto const §ion : Model.unknown) builder.raw(section.id, section.flags, section.data); return builder.finish(Model, Options); diff --git a/model/e4d/e4d_io.h b/model/e4d/e4d_io.h index 0bf7846d3..74a963c0b 100644 --- a/model/e4d/e4d_io.h +++ b/model/e4d/e4d_io.h @@ -21,6 +21,10 @@ namespace e4d { struct write_options { bool compress{true}; // zstd for the sections where it saves at least an eighth int level{9}; + bool codec{true}; // the codecs of meshoptimizer for the vertex and index streams, which unpack several times faster than zstd + // zstd also over the streams in a codec: the smallest file (for an archive), which loads slower. measured on a vehicle of + // 580 thousand vertices: 7.8 MB and 47 ms with it, 12.2 MB and 37 ms without it + bool compress_streams{false}; }; // the file of the model. the model is written as it is; validate() it first diff --git a/model/e4d/e4d_load.cpp b/model/e4d/e4d_load.cpp new file mode 100644 index 000000000..204da371c --- /dev/null +++ b/model/e4d/e4d_load.cpp @@ -0,0 +1,340 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" + +#include "model/Model3d.h" + +#include "model/e4d/e4d_build.h" +#include "model/e4d/e4d_io.h" +#include "rendering/renderer.h" +#include "utilities/Logs.h" +#include "utilities/wholefile.h" + +#include + +#include +#include +#include +#include +#include +#include + +// the loading of an E4D model into the tree of submodels the rest of the game works with: each node becomes a submodel, with +// what E3D keeps in the submodel taken from the node, its material, its primitive and its components. the result is what +// TModel3d::LoadFromBinFile() makes of the E3D the model was converted from + +namespace { + +// what E3D keeps in the submodel and E4D in the components of the node +struct legacy_parts { + std::optional light; + std::uint32_t material{e4d::no_index}; // of a node without geometry + TAnimType animation{TAnimType::at_None}; + bool text{false}; + std::span stars; // the packed colours, one for each vertex of the mesh +}; + +legacy_parts parts_of(e4d::model const &Model, e4d::node_record const &Node) { + legacy_parts parts; + for (auto idx = Node.component_first; idx < Node.component_first + Node.component_count; ++idx) { + auto const type{Model.components[idx].type}; + auto const data{Model.component_payload(idx)}; + e4d::payload_reader reader{data}; + if (type == e4d::component::light) { + if (e4d::payload::light light; reader.get(light)) + parts.light = light; + } + else if (type == e4d::component::legacy_animation) { + if (e4d::payload::legacy_animation animation; reader.get(animation)) + parts.animation = static_cast(animation.type); + } + else if (type == e4d::component::legacy_text) + parts.text = true; + else if (type == e4d::component::legacy_material) { + if (e4d::payload::legacy_material material; reader.get(material)) + parts.material = material.material; + } + else if (type == e4d::component::legacy_stars && data.size() >= sizeof(e4d::payload::legacy_stars)) + parts.stars = data.subspan(sizeof(e4d::payload::legacy_stars)); + } + return parts; +} + +glm::vec3 unpack_colour(std::span const Colours, std::size_t const Index) { + std::uint32_t packed{0}; + if ((Index + 1) * sizeof(packed) <= Colours.size()) + std::memcpy(&packed, Colours.data() + Index * sizeof(packed), sizeof(packed)); + return glm::vec3{static_cast(packed & 0xFF), static_cast((packed >> 8) & 0xFF), static_cast((packed >> 16) & 0xFF)} / 255.f; +} + +glm::vec4 to_vec4(std::array const &Value) { + return {Value[0], Value[1], Value[2], Value[3]}; +} + +// the vertices and the indices of a submodel, filled once the submodels are set up +struct geometry_job { + e4d::primitive_record const *primitive{nullptr}; + std::span stars; + TSubModel *submodel{nullptr}; +}; + +// a model with fewer vertices fills its submodels on the thread which loads it: starting threads would cost more +constexpr std::size_t parallel_vertex_threshold{100'000}; +constexpr unsigned parallel_thread_limit{8}; + +// fills the submodels from the nodes of the model +class submodel_builder { + public: + submodel_builder(e4d::model const &Model, std::vector &Textures, std::vector &Names, std::vector &Matrices) + : m_model(Model), m_textures(Textures), m_names(Names), m_matrices(Matrices), m_transforms(e4d::local_transforms(Model)) { + // texture 0 is "none" in the submodels + m_textures.emplace_back(); + } + void build(std::uint32_t Index, TSubModel &Submodel); + // the vertices and the indices of all the submodels, on several threads for a big model + void fill_geometry(); + + private: + void links(std::uint32_t Index, TSubModel &Submodel) const; + void transform(std::uint32_t Index, TSubModel &Submodel); + void material(std::uint32_t Material, TSubModel &Submodel); + static void light(e4d::payload::light const &Light, TSubModel &Submodel); + void geometry(e4d::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel); + void fill(geometry_job const &Job) const; + void indices(e4d::primitive_record const &Primitive, TSubModel &Submodel) const; + int texture(std::string_view Name); + + e4d::model const &m_model; + std::vector &m_textures; + std::vector &m_names; + std::vector &m_matrices; + std::vector m_transforms; + std::vector m_jobs; + int m_vertexoffset{0}; + int m_indexoffset{0}; + + public: + int vertex_count{0}; + int index_count{0}; +}; + +void submodel_builder::build(std::uint32_t const Index, TSubModel &Submodel) { + auto const &node{m_model.nodes[Index]}; + links(Index, Submodel); + if (node.name != e4d::no_index) { + Submodel.iName = static_cast(m_names.size()); + m_names.emplace_back(m_model.string(node.name)); + } + Submodel.iFlags = node.legacy_flags; + Submodel.fSquareMinDist = node.range_min_sq; + Submodel.fSquareMaxDist = node.range_max_sq; + transform(Index, Submodel); + auto const parts{parts_of(m_model, node)}; + Submodel.b_Anim = parts.animation; + Submodel.eType = TP_ROTATOR; + material(parts.material, Submodel); + if (parts.text) + Submodel.eType = TP_TEXT; + if (parts.light) { + Submodel.eType = TP_FREESPOTLIGHT; + light(*parts.light, Submodel); + } + if (node.mesh >= 0) { + auto const &mesh{m_model.meshes[node.mesh]}; + if (mesh.primitive_count > 0) + geometry(m_model.primitives[mesh.primitive_first], parts, Submodel); + } + // as in E3D the rotations of the text model were done when it was made + Submodel.m_rotation_init_done = true; +} + +// the submodels lie in the order of the nodes: the first child follows its parent, the next sibling follows the subtree +void submodel_builder::links(std::uint32_t const Index, TSubModel &Submodel) const { + auto const &node{m_model.nodes[Index]}; + auto const count{static_cast(m_model.nodes.size())}; + Submodel.iChild = (Index + 1 < node.subtree_end) ? static_cast(Index + 1) : 0; + auto const next{node.subtree_end}; + Submodel.iNext = (next < count && m_model.nodes[next].parent == node.parent) ? static_cast(next) : 0; +} + +void submodel_builder::transform(std::uint32_t const Index, TSubModel &Submodel) { + if ((m_model.nodes[Index].flags & e4d::node_flags::no_transform) != 0) { + Submodel.iMatrix = -1; + return; + } + Submodel.iMatrix = static_cast(m_matrices.size()); + m_matrices.emplace_back(glm::value_ptr(m_transforms[Index])); +} + +int submodel_builder::texture(std::string_view const Name) { + if (auto const found{std::ranges::find(m_textures, Name)}; found != m_textures.end()) + return static_cast(std::distance(m_textures.begin(), found)); + m_textures.emplace_back(Name); + return static_cast(m_textures.size() - 1); +} + +void submodel_builder::material(std::uint32_t const Material, TSubModel &Submodel) { + if (Material >= m_model.materials.size()) + return; + auto const &material{m_model.materials[Material]}; + if (material.replaceable != 0) + Submodel.iTexture = material.replaceable; + else if (material.name != e4d::no_index) + Submodel.iTexture = texture(m_model.string(material.name)); + Submodel.fLight = material.selfillum; + Submodel.f4Ambient = to_vec4(material.ambient); + Submodel.f4Diffuse = to_vec4(material.diffuse); + Submodel.f4Specular = to_vec4(material.specular); + Submodel.f4Emision = to_vec4(material.emission); +} + +void submodel_builder::light(e4d::payload::light const &Light, TSubModel &Submodel) { + namespace light_flags = e4d::payload::light_flags; + Submodel.f4Diffuse = to_vec4(Light.color); + Submodel.fHotspotPower = Light.hotspot_power; + Submodel.fLightRadius = Light.radius; + Submodel.fNearAttenStart = Light.near_start; + Submodel.fNearAttenEnd = Light.near_end; + Submodel.iFarAttenDecay = Light.far_decay; + Submodel.fFarDecayRadius = Light.far_radius; + Submodel.fCosFalloffAngle = Light.cos_falloff; + Submodel.fCosHotspotAngle = Light.cos_hotspot; + Submodel.bShadeSelf = (Light.flags & light_flags::shade_self) != 0; + Submodel.bCastShadows = (Light.flags & light_flags::no_shadows) == 0; + Submodel.bSoftFalloff = (Light.flags & light_flags::soft_falloff) != 0; + Submodel.bLightOnly = (Light.flags & light_flags::light_only) != 0; + Submodel.bUseNearAtten = (Light.flags & light_flags::near_attenuation) != 0; +} + +// what the submodel knows of its geometry; the vertices and the indices come later, in fill_geometry() +void submodel_builder::geometry(e4d::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel) { + Submodel.eType = Parts.stars.empty() ? static_cast(Primitive.flags & e4d::primitive_flags::topology_mask) : TP_STARS; + material(Primitive.material, Submodel); + auto const indexed{(Primitive.flags & e4d::primitive_flags::indexed) != 0}; + Submodel.m_geometry.vertex_count = static_cast(Primitive.vertex_count); + Submodel.m_geometry.vertex_offset = m_vertexoffset; + Submodel.m_geometry.index_count = indexed ? static_cast(Primitive.index_count) : 0; + Submodel.m_geometry.index_offset = m_indexoffset; + m_vertexoffset += Submodel.m_geometry.vertex_count; + m_indexoffset += Submodel.m_geometry.index_count; + vertex_count += Submodel.m_geometry.vertex_count; + index_count += Submodel.m_geometry.index_count; + m_jobs.push_back({&Primitive, Parts.stars, &Submodel}); +} + +void submodel_builder::fill(geometry_job const &Job) const { + auto const &primitive{*Job.primitive}; + auto &submodel{*Job.submodel}; + auto const stars{false == Job.stars.empty()}; + auto const userdata{m_model.vertex_userdata.size() == m_model.vertex_count()}; + // each vertex is written once: reserved and appended, without the zeroes resize() would write first + submodel.Vertices.clear(); + submodel.Vertices.reserve(primitive.vertex_count); + for (std::uint32_t idx = 0; idx < primitive.vertex_count; ++idx) { + auto const source{std::size_t{primitive.base_vertex} + idx}; + auto const &position{m_model.positions[source]}; + auto const &attribute{m_model.vertex_attributes[source]}; + auto const frame{e4d::decode_qtangent(attribute.qtangent)}; + gfx::basic_vertex vertex; + vertex.position = {position[0], position[1], position[2]}; + vertex.normal = stars ? unpack_colour(Job.stars, idx) : frame.normal; + vertex.tangent = glm::vec4{frame.tangent, frame.handedness}; + vertex.texture = {attribute.uv[0], attribute.uv[1]}; + submodel.Vertices.push_back(vertex); + } + if (userdata) { + submodel.Userdata.clear(); + submodel.Userdata.reserve(primitive.vertex_count); + for (auto const &data : std::span{m_model.vertex_userdata}.subspan(primitive.base_vertex, primitive.vertex_count)) + submodel.Userdata.push_back({glm::vec4{data[0], data[1], data[2], data[3]}}); + } + indices(primitive, submodel); +} + +void submodel_builder::indices(e4d::primitive_record const &Primitive, TSubModel &Submodel) const { + if ((Primitive.flags & e4d::primitive_flags::indexed) == 0) + return; + if ((Primitive.flags & e4d::primitive_flags::index32) != 0) { + auto const source{std::span{m_model.indices32}.subspan(Primitive.first_index, Primitive.index_count)}; + Submodel.Indices.assign(source.begin(), source.end()); + } + else { + auto const source{std::span{m_model.indices16}.subspan(Primitive.first_index, Primitive.index_count)}; + Submodel.Indices.assign(source.begin(), source.end()); + } +} + +void submodel_builder::fill_geometry() { + auto const threads{static_cast(vertex_count) < parallel_vertex_threshold ? 1u : std::clamp(std::thread::hardware_concurrency(), 1u, parallel_thread_limit)}; + if (threads <= 1 || m_jobs.size() <= 1) { + for (auto const &job : m_jobs) + fill(job); + return; + } + // 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]); + } + }}; + { + std::vector workers; + workers.reserve(threads - 1); + for (unsigned idx = 1; idx < threads; ++idx) + workers.emplace_back(work); + work(); + } // the workers join here +} + +} // namespace + +bool TModel3d::LoadFromE4D(std::string const &FileName, bool const dynamic) { + WriteLog("Loading E4D model data from \"" + FileName + "\"...", logtype::model); + auto const file{read_whole_file(FileName)}; + if (file.data == nullptr) { + ErrorLog("Bad model: can't read \"" + FileName + "\"", logtype::model); + return false; + } + 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); + return false; + } + if (model.nodes.empty()) { + ErrorLog("Bad model: \"" + FileName + "\" has no nodes", logtype::model); + return false; + } + + Root = nullptr; + if (m_geometrybank == null_handle) + m_geometrybank = GfxRenderer->Create_Bank(); + Textures.clear(); + Names.clear(); + Matrices.clear(); + Matrices.reserve(model.nodes.size()); + 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(); + m_vertexcount += builder.vertex_count; + m_indexcount += builder.index_count; + // the tangents come with the vertices + finish_binary(dynamic, true); + WriteLog("Finished loading E4D model data from \"" + FileName + "\"", logtype::model); + return true; +} diff --git a/ref/meshoptimizer b/ref/meshoptimizer new file mode 160000 index 000000000..9e1f07b15 --- /dev/null +++ b/ref/meshoptimizer @@ -0,0 +1 @@ +Subproject commit 9e1f07b159d3cb777f1c67ed31fc11fd117986f4 diff --git a/tests/unit/test_e4d.cpp b/tests/unit/test_e4d.cpp index df541c285..6ead18c0c 100644 --- a/tests/unit/test_e4d.cpp +++ b/tests/unit/test_e4d.cpp @@ -406,11 +406,113 @@ TEST_CASE("e4d: parts of several nodes and light slots merged into one primitive } } +namespace { + +// the sample with a grid of 64 x 64 vertices on the body: streams big enough for the codecs +e4d::model grid_model() { + auto model{sample_model()}; + auto const first{static_cast(model.positions.size())}; + constexpr std::uint32_t side{64}; + for (std::uint32_t row = 0; row < side; ++row) { + for (std::uint32_t column = 0; column < side; ++column) { + auto const x{static_cast(column) * 0.1f}; + auto const z{static_cast(row) * 0.1f}; + model.positions.push_back({x, std::sin(x) * std::cos(z), z}); + e4d::attributes attribute; + attribute.qtangent = e4d::encode_qtangent({glm::normalize(glm::vec3{std::sin(x), 1.f, std::cos(z)}), {1.f, 0.f, 0.f}, 1.f}); + attribute.uv = {x, z}; + model.vertex_attributes.push_back(attribute); + model.weights.push_back({}); + } + } + e4d::primitive_record grid; + grid.first_index = static_cast(model.indices16.size()); + for (std::uint32_t row = 0; row + 1 < side; ++row) { + for (std::uint32_t column = 0; column + 1 < side; ++column) { + auto const corner{static_cast(row * side + column)}; + for (auto const index : {corner, static_cast(corner + 1), static_cast(corner + side), static_cast(corner + 1), + static_cast(corner + side + 1), static_cast(corner + side)}) + model.indices16.push_back(index); + } + } + grid.index_count = static_cast(model.indices16.size()) - grid.first_index; + grid.base_vertex = first; + grid.vertex_count = side * side; + grid.material = 0; + grid.node = 0; + grid.flags = static_cast(e4d::topology::triangles) | e4d::primitive_flags::indexed | e4d::primitive_flags::opaque; + model.primitives.push_back(grid); + model.meshes.push_back({2, 1, -1, 0}); + model.nodes[0].mesh = 2; + e4d::compute_bounds(model); + return model; +} + +} // namespace + +TEST_CASE("e4d: the streams in the codecs of meshoptimizer, with and without zstd") +{ + auto const original{grid_model()}; + REQUIRE(e4d::validate(original).empty()); + for (auto const compress : {false, true}) { + for (auto const codec : {false, true}) { + CAPTURE(compress); + CAPTURE(codec); + auto const file{e4d::write(original, {compress, 9, codec})}; + auto const positions{get_at(file, entry_offset(file, e4d::section::positions))}; + auto const indices{get_at(file, entry_offset(file, e4d::section::indices16))}; + CHECK(((positions.flags & e4d::section_flags::meshopt) != 0) == codec); + CHECK(((indices.flags & e4d::section_flags::meshopt) != 0) == codec); + e4d::model loaded; + auto const result{read_file(file, loaded)}; + REQUIRE_MESSAGE(result.ok, result.error); + CHECK(loaded.positions == original.positions); + CHECK(loaded.indices16 == original.indices16); + CHECK(std::memcmp(loaded.vertex_attributes.data(), original.vertex_attributes.data(), original.vertex_attributes.size() * sizeof(e4d::attributes)) == 0); + CHECK(e4d::dump(loaded) == e4d::dump(original)); + } + } + // zstd over the codec, for an archive + { + auto const file{e4d::write(original, {true, 9, true, true})}; + auto const positions{get_at(file, entry_offset(file, e4d::section::positions))}; + CHECK((positions.flags & e4d::section_flags::meshopt) != 0); + e4d::model loaded; + auto const result{read_file(file, loaded)}; + REQUIRE_MESSAGE(result.ok, result.error); + CHECK(loaded.positions == original.positions); + CHECK(e4d::dump(loaded) == e4d::dump(original)); + } + // the codec on a section which isn't a stream, and a stream whose encoded bytes don't decode + auto const good{e4d::write(original, {false, 0, true})}; + auto onnodes{good}; + auto const nodesoffset{entry_offset(onnodes, e4d::section::nodes)}; + auto nodes{get_at(onnodes, nodesoffset)}; + nodes.flags |= e4d::section_flags::meshopt; + put_at(onnodes, nodesoffset, nodes); + e4d::model loaded; + auto const wrongsection{e4d::read(onnodes, loaded, {false, true})}; + CHECK_FALSE(wrongsection.ok); + CHECK(wrongsection.error.find("only the vertex and index streams") != std::string::npos); + auto broken{good}; + auto const positions{get_at(broken, entry_offset(broken, e4d::section::positions))}; + // the stream cut in the middle by a stored size of half of it + auto shortened{positions}; + shortened.stored_size /= 2; + put_at(broken, entry_offset(broken, e4d::section::positions), shortened); + auto const cut{e4d::read(broken, loaded, {false, true})}; + CHECK_FALSE(cut.ok); + CHECK(cut.error.find("doesn't decode") != std::string::npos); + CHECK(loaded.nodes.empty()); +} + 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}; + // 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::uniform_int_distribution position{0, good.size() - 1}; std::uniform_int_distribution value{0, 255}; for (int attempt = 0; attempt < 3000; ++attempt) { diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a4d5f6669..4056c9414 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -999,6 +999,15 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "modelformat") + { + // e4d: a model with an .e4d file beside its .e3d / .t3d is loaded from it; legacy: the .e4d files are left alone + std::string value; + ParseOne(Parser, value, 1); + modelformat_e4d = value == "e4d"; + return true; + } + if (token == "fpslimit") { float fpslimit = 0.f; @@ -2653,6 +2662,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "hiddenevents", iHiddenEvents ); export_as_text( Output, "pause", ( iPause & 1 ) != 0 ); export_as_text(Output, "priorityLoadText3D", priorityLoadText3D); + export_as_text(Output, "modelformat", std::string{modelformat_e4d ? "e4d" : "legacy"}); export_as_text( Output, "lang", asLang ); export_as_text( Output, "python.updatetime", PythonScreenUpdateRate ); Output diff --git a/utilities/Globals.h b/utilities/Globals.h index 3364c49a0..1ba452f1a 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -121,6 +121,7 @@ struct global_settings { int file_binary_terrain_skipped{0}; // number of terrain includes left out by the parser during the current scenery load // logs bool priorityLoadText3D{false}; // ladowanie T3D priorytetowo + bool modelformat_e4d{false}; // modelformat e4d: models are loaded from their .e4d files where there are some int iWriteLogEnabled{ 3 }; // maska bitowa: 1-zapis do pliku, 2-okienko, 4-nazwy torów bool MultipleLogs{ false }; bool crashdump_full{ false }; // crash dump with the whole memory of the process instead of the small one