From d930b6519d6cee56a39e92724d727f6630ff7f7e Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:03:49 +0100 Subject: [PATCH 1/3] feat(model): the geometry shared by the variants of a family kept once, in a store of the folder The variants of a vehicle repeat the same parts byte for byte, and each EU07M file carried them all again. PR #521 showed the problem on E3D; EU07M solves it in the format. - Block: the geometry of one primitive, its vertices in every vertex stream of the file and its indices, with a 16-byte header; its id is 128 bits, two FNV-1a 64 of its bytes. Only a primitive whose vertex and index ranges are its own can be shared. - Store: geometry.eu07mpack in the folder of the models, the blocks each once (zstd when it saves an eighth) and an index sorted by their id (model/eu07m/eu07m_store.{h,cpp}). - GREF, a new required section: the primitives kept in the store. The writer leaves their ranges out of the streams of the file; the reader takes their blocks from the store (read_options::blocks), checks the id and the counts of each and puts them back in place, so the model in memory has its whole streams and nothing past the reader knows the difference. A model with references and no store, or with a block which isn't the one referred to, is refused with the reason. The validator checks the references (primitive, counts, ranges of its own). - The game opens the store of a folder once and keeps it (eu07m::family_store()); dump and validate read it too. - Tools: "-eu07m pack [minimum bytes]" moves every block of at least 4 KiB (by default) which occurs more than once in the models of the folder into its store, made anew from all of them, and writes the models again referring to it, each read back and compared with what it was before it's replaced; "-eu07m unpack " writes them whole again. Measured on copies of the converted models of the game: cd/181_v2 60.8 MB -> 4.0 MB (7%), pkp/11xa_v2/main 69.3 MB -> 5.8 MB (8%), pkp/elf_v1 109.6 MB -> 39.0 MB (36%), pkp/en57_v1 104.1 MB -> 39.3 MB (38%), 2-4 s a folder. All 223 packed files pass -eu07m validate with their store. Four ELF parts drawn in the game (Vulkan) from the packed and from the whole files, with the auto exposure off and the same seed: no pixel differs by more than 1. Unit tests 1208/1208, 4 new ones for a round trip through a store, a model without its store, a wrong block, a primitive sharing its vertices and a folder packed, packed again and unpacked. The renderer still makes the geometry of each model on its own; sharing one range of the buffers between the models of a family is the next step. No asset change: the game data has no .eu07m files, and the release doesn't read them. --- CMakeLists.txt | 2 + docs/eu07m-format.md | 33 ++- model/eu07m/eu07m_convert.cpp | 15 +- model/eu07m/eu07m_dump.cpp | 2 + model/eu07m/eu07m_format.h | 13 + model/eu07m/eu07m_io.cpp | 35 +++ model/eu07m/eu07m_io.h | 7 +- model/eu07m/eu07m_load.cpp | 6 +- model/eu07m/eu07m_model.h | 1 + model/eu07m/eu07m_pack.cpp | 230 +++++++++++++++++ model/eu07m/eu07m_pack.h | 37 +++ model/eu07m/eu07m_store.cpp | 473 ++++++++++++++++++++++++++++++++++ model/eu07m/eu07m_store.h | 105 ++++++++ tests/unit/test_gref.cpp | 213 +++++++++++++++ 14 files changed, 1166 insertions(+), 6 deletions(-) create mode 100644 model/eu07m/eu07m_pack.cpp create mode 100644 model/eu07m/eu07m_pack.h create mode 100644 model/eu07m/eu07m_store.cpp create mode 100644 model/eu07m/eu07m_store.h create mode 100644 tests/unit/test_gref.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e868e15ac..b6ea75106 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -800,6 +800,8 @@ set(CORE_SOURCES "model/eu07m/eu07m_io.cpp" "model/eu07m/eu07m_build.cpp" "model/eu07m/eu07m_dump.cpp" +"model/eu07m/eu07m_store.cpp" +"model/eu07m/eu07m_pack.cpp" "model/skinning.cpp" "model/clip.cpp" "${DEPS_DIR}/zstd/zstd.c" diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index f3550ee16..d750f4890 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -7,7 +7,8 @@ and this description from drifting apart. State: version 1.0. The format, its reader, writer and the conversion from E3D/T3D (stage 1); the loading in the game behind a switch (stage 2); the compact streams in the Vulkan renderer (stage 3); the instancing of models with lights (stage 5); skinning -(stage 4); animation clips and channels (stage 8). See "In the game". +(stage 4); animation clips and channels (stage 8); the geometry shared by the variants of a family (`GREF`). See "In the game" +and "Geometry shared by a family". ## Principles @@ -93,6 +94,7 @@ the element count is the section size divided by the element size. | `ATRK` | no | [T] 24 B | a track of a clip: `u32` node, `u8` part (0 translation, 1 rotation, 2 scale), `u8` interpolation (0 step, 1 linear, 2 cubic), `u16` 0, `u32` key count, `u32` first time in `ATIM`, `u32` first value in `AVEC` or `AROT`, `u32` 0 | | `ATIM` | no | [S] 4 B | the times of the keys, `f32` seconds, from 0, not decreasing within a track | | `AVEC` | no | [S] 12 B | the values of translations and scales, `f32 × 3`; with cubic interpolation three for each key: in-tangent, value, out-tangent (as in glTF) | +| `GREF` | yes, when present | [T] 32 B | a primitive whose geometry is in the store of the family: `u32` primitive, `u32` 0, `u64 × 2` hash of the block, `u32` vertex count, `u32` index count. See "Geometry shared by a family" | | `AROT` | no | [S] 8 B | rotations, "smallest three": the three smaller components of the quaternion `snorm16 × 3` (multiplied by √2), `u16` index of the largest (0 x … 3 w), which is positive and rebuilt from the others | All the vertex streams (`VPOS`, `VATT`, `VSKN`/`VSKW`, `VUSR`, `VBND`) have the same element count: one for each vertex of the file. @@ -182,6 +184,35 @@ reads only `VPOS` (and `VBND` in merged primitives). weights in `VGWT`), `u32 × 2` the components of the group (first, count), `u32` 0. The vertex indices are those of the streams of the file (absolute). +## Geometry shared by a family + +The variants of a vehicle repeat the same parts byte for byte (the `include`s of their `.t3d`). Measured on the converted models +of the game, the folders of a family are 7% to 38% of their size with their shared parts kept once (EU07M, blocks of at least +4 KiB): `cd/181_v2` 60.8 MB → 4.0 MB, `pkp/11xa_v2/main` 69.3 MB → 5.8 MB, `pkp/elf_v1` 109.6 MB → 39.0 MB, `pkp/en57_v1` +104.1 MB → 39.3 MB. PR #521 showed the problem first, on E3D. + +- **Block.** The geometry of one primitive: a 16 B header (`u32` the vertex streams it has, as bits 0x1 `VPOS`, 0x2 `VATT`, 0x4 + `VSKN`, 0x8 `VSKW`, 0x10 `VUSR`, 0x20 `VBND`; `u32` vertex count; `u32` index count; `u32` index size 0, 2 or 4), then its vertices + in each of those streams in that order, then its indices. Its id is 128 bits: two FNV-1a 64 of its bytes, with the seeds + `0xcbf29ce484222325` and `0x84222325cbf29ce4`. A primitive can be kept in the store only when its vertex and index ranges are + its own. +- **The store** of the family is `geometry.eu07mpack` in the folder of the models: a 32 B header (magic `EU7P`, `u16` major 1, + `u16` minor 0, `u32` block count, `u32` flags, `u64` offset of the index, 8 B of zeroes), the blocks one after another, each + packed with zstd when it saves an eighth, and the index: entries of 40 B (`u64 × 2` id, `u64` offset, `u32` size in the file, + `u32` size unpacked, `u32` flags (0x1 zstd), `u32` 0), sorted by the id. +- **In a model file,** `GREF` names the primitives kept in the store. The writer leaves their vertex and index ranges out of the + streams of the file; the reader takes their blocks from the store, checks the id and the counts of each, and puts them back in + their places, so the model in memory always has its whole streams and nothing past the reader knows the difference. A model + with references and no store, or a block which isn't the one referred to, is refused with the reason in the log. `GREF` is a + required section, so a reader which doesn't know it refuses the file rather than reading short streams. +- **The game** opens the store of a folder once and keeps it, reading the blocks from it as the models ask for them. +- **The tools.** `eu07 -eu07m pack [minimum bytes]` moves every block of at least the minimum (4096 by default) which + occurs more than once in the models of the folder into its store, made anew from all of them, and writes the models again + referring to it; each model is read back and compared with what it was before it's replaced. `eu07 -eu07m unpack ` + writes the models whole again (the store is left to be deleted). `dump` and `validate` read the store of the folder. +- The renderer still makes the geometry of each model on its own; a part shared by the variants takes one range of the buffers + for each model that uses it. Sharing that range is the next step. + ## Components A record in `CMPT` (20 B): diff --git a/model/eu07m/eu07m_convert.cpp b/model/eu07m/eu07m_convert.cpp index b689eb9e2..05ccea067 100644 --- a/model/eu07m/eu07m_convert.cpp +++ b/model/eu07m/eu07m_convert.cpp @@ -14,6 +14,8 @@ http://mozilla.org/MPL/2.0/. #include "model/eu07m/eu07m_build.h" #include "model/eu07m/eu07m_dump.h" #include "model/eu07m/eu07m_io.h" +#include "model/eu07m/eu07m_pack.h" +#include "model/eu07m/eu07m_store.h" #include "model/Model3d.h" #include "rendering/renderer.h" #include "utilities/Globals.h" @@ -511,7 +513,9 @@ int command_read(int const Argc, char *Argv[], bool const Dump) { return 1; } model loaded; - auto const result{read(std::as_bytes(std::span{file.data.get(), file.size}), loaded, {true, true})}; + read_options options{true, true}; + options.blocks = store_source(family_store(Argv[3])); + auto const result{read(std::as_bytes(std::span{file.data.get(), file.size}), loaded, options)}; if (false == result.ok) { std::cerr << std::format("{}: {}\n", Argv[3], result.error); return 1; @@ -539,7 +543,14 @@ int run_command_line(int const Argc, char *Argv[]) { return command_read(Argc, Argv, false); if (command == "diff") return command_diff(Argc, Argv); - std::cerr << "usage: -eu07m convert|dump|validate|diff ...\n"; + if (command == "pack" && Argc >= 4) { + // the blocks of at least 4 KiB by default, smaller ones cost more in the index than they save + std::size_t const minimum{Argc >= 5 ? static_cast(std::stoul(Argv[4])) : std::size_t{4096}}; + return pack_folder(Argv[3], minimum, std::cout).ok ? 0 : 1; + } + if (command == "unpack" && Argc >= 4) + return unpack_folder(Argv[3], std::cout).ok ? 0 : 1; + std::cerr << "usage: -eu07m convert|dump|validate|diff ... | pack [minimum bytes] | unpack \n"; return 2; } diff --git a/model/eu07m/eu07m_dump.cpp b/model/eu07m/eu07m_dump.cpp index 874df85e2..c6a3bdcb6 100644 --- a/model/eu07m/eu07m_dump.cpp +++ b/model/eu07m/eu07m_dump.cpp @@ -53,6 +53,8 @@ void dump_counts(model const &Model, std::string &Output) { Model.indices32.size(), Model.weights.size(), Model.weights_wide.size(), Model.vertex_userdata.size(), Model.bindings.size()); Output += std::format("skins: {} ({} joints), vertex groups: {}, components: {} ({} bytes), bounds: {}, name index: {}\n", Model.skins.size(), Model.skin_joints.size(), Model.vertex_groups.size(), Model.components.size(), Model.component_data.size(), Model.bounds.size(), Model.name_index.size()); + if (false == Model.geometry_references.empty()) + Output += std::format("geometry in the store of the family: {} primitives\n", Model.geometry_references.size()); for (auto const §ion : Model.unknown) Output += std::format("unknown section {}: {} bytes\n", fourcc_name(section.id), section.data.size()); } diff --git a/model/eu07m/eu07m_format.h b/model/eu07m/eu07m_format.h index d99b58bfd..3cc4a4bf5 100644 --- a/model/eu07m/eu07m_format.h +++ b/model/eu07m/eu07m_format.h @@ -64,6 +64,7 @@ constexpr std::uint32_t clip_tracks{fourcc("ATRK")}; constexpr std::uint32_t key_times{fourcc("ATIM")}; constexpr std::uint32_t key_vectors{fourcc("AVEC")}; constexpr std::uint32_t key_rotations{fourcc("AROT")}; +constexpr std::uint32_t geometry_references{fourcc("GREF")}; } // namespace section // the components @@ -376,6 +377,18 @@ struct packed_rotation { }; static_assert(sizeof(packed_rotation) == 8); +// the geometry of a primitive kept in the geometry store of the family of the model (geometry.eu07mpack beside the file) instead of +// in the file: its vertices in every vertex stream of the file and its indices. the writer leaves its ranges out of the streams of the +// file, and the reader puts the block of the store back in their place, so the model in memory always has its whole streams +struct geometry_reference_record { + std::uint32_t primitive{0}; + std::uint32_t reserved{0}; + std::array hash{}; // of the block (eu07m::block_hash()) + std::uint32_t vertex_count{0}; // of the block, checked against the primitive and the block + std::uint32_t index_count{0}; +}; +static_assert(sizeof(geometry_reference_record) == 32); + struct bounds_record { std::array min{0.f, 0.f, 0.f}; std::array max{0.f, 0.f, 0.f}; diff --git a/model/eu07m/eu07m_io.cpp b/model/eu07m/eu07m_io.cpp index 7a8612a20..dabbb1eaa 100644 --- a/model/eu07m/eu07m_io.cpp +++ b/model/eu07m/eu07m_io.cpp @@ -577,6 +577,7 @@ bool file_reader::dispatch(section_entry const &Entry, section_bytes const &Sect case section::key_times: result = Section.stream(Model.key_times, error); break; case section::key_vectors: result = Section.stream(Model.key_vectors, error); break; case section::key_rotations: result = Section.stream(Model.key_rotations, error); break; + case section::geometry_references: result = Section.table(Model.geometry_references, error); break; default: known = false; break; } if (false == result) @@ -620,6 +621,11 @@ read_result file_reader::run(model &Model) { return {false, std::format("the model has no section {}", fourcc_name(required))}; } } + // the geometry kept in the store of the family goes back in its place in the streams + if (std::string error; false == insert_blocks(Model, m_options.blocks, error)) { + Model = model{}; + return {false, error}; + } if (auto const faults{validate(Model, 1)}; false == faults.empty()) { Model = model{}; return {false, faults.front()}; @@ -834,6 +840,7 @@ class validator { void component_ranges(std::uint32_t First, std::uint32_t Count, target_kind Kind, std::uint32_t Target, std::string_view Owner); void tables(); void clips(); + void geometry_references(); void track(std::uint32_t Index, track_record const &Track); void track_times(std::uint32_t Index, track_record const &Track); @@ -1146,6 +1153,22 @@ void validator::track_times(std::uint32_t const Index, track_record const &Track fault(std::format("track {} has times which aren't numbers from 0 up", Index)); } +// a primitive kept in the store has its vertex and index ranges to itself, and the counts of its reference +void validator::geometry_references() { + for (auto const &reference : m_model.geometry_references) { + if (reference.primitive >= m_model.primitives.size()) { + fault(std::format("a geometry reference names primitive {}, which the model hasn't", reference.primitive)); + continue; + } + auto const &primitive{m_model.primitives[reference.primitive]}; + auto const indices{(primitive.flags & primitive_flags::indexed) != 0 ? primitive.index_count : 0u}; + if (reference.vertex_count != primitive.vertex_count || reference.index_count != indices) + fault(std::format("the geometry reference of primitive {} has other counts than the primitive", reference.primitive)); + else if (false == shareable(m_model, reference.primitive)) + fault(std::format("primitive {} is in the geometry store, and shares its vertices or indices with another one", reference.primitive)); + } +} + std::vector validator::run() { nodes(); transforms(); @@ -1158,12 +1181,22 @@ std::vector validator::run() { components(); tables(); clips(); + geometry_references(); return m_faults; } } // namespace +// the file of the model as it is, its streams whole or already without the ranges of its references +std::vector write_model(model const &Model, write_options const &Options); + std::vector write(model const &Model, write_options const &Options) { + if (false == Model.geometry_references.empty()) + return write_model(remove_referenced(Model), Options); + return write_model(Model, Options); +} + +std::vector write_model(model const &Model, write_options const &Options) { file_builder builder; builder.add(section::strings, true, section_alignment, encode_strings(Model.strings)); builder.table(section::name_index, Model.name_index, false); @@ -1182,6 +1215,8 @@ 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); + // required: without the blocks of the store the streams are short + builder.table(section::geometry_references, Model.geometry_references, false == Model.geometry_references.empty()); builder.table(section::clips, Model.clips, false); builder.table(section::clip_tracks, Model.clip_tracks, false); builder.stream(section::key_times, Model.key_times, false); diff --git a/model/eu07m/eu07m_io.h b/model/eu07m/eu07m_io.h index 1296a1f53..b6c077ebc 100644 --- a/model/eu07m/eu07m_io.h +++ b/model/eu07m/eu07m_io.h @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. // writing, reading and checking of EU07M files #include "model/eu07m/eu07m_model.h" +#include "model/eu07m/eu07m_store.h" #include #include @@ -27,12 +28,16 @@ struct write_options { bool compress_streams{false}; }; -// the file of the model. the model is written as it is; validate() it first +// the file of the model. the model is written as it is, the ranges of the primitives it refers to in the geometry store (GREF) left out +// of its streams; validate() it first std::vector write(model const &Model, write_options const &Options = {}); struct read_options { bool verify_hash{false}; // the hash of the content, which costs a pass over the whole file bool keep_unknown{true}; // the sections the reader doesn't know, for the tools to write back + // the blocks of the geometry store a model refers to (GREF), put back in its streams; a model with references and no source + // is refused + block_source blocks; }; struct read_result { diff --git a/model/eu07m/eu07m_load.cpp b/model/eu07m/eu07m_load.cpp index 0400125a2..4f0d29026 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -471,8 +471,10 @@ bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) { return false; } eu07m::model model; - // the game has no use for the sections it doesn't know - if (auto const result{eu07m::read(std::as_bytes(std::span{file.data.get(), file.size}), model, {false, false})}; false == result.ok) { + // the game has no use for the sections it doesn't know; the geometry shared by the family comes from the store of the folder + eu07m::read_options options{false, false}; + options.blocks = eu07m::store_source(eu07m::family_store(FileName)); + if (auto const result{eu07m::read(std::as_bytes(std::span{file.data.get(), file.size}), model, options)}; false == result.ok) { ErrorLog("Bad model: \"" + FileName + "\" isn't a valid EU07M file: " + result.error, logtype::model); return false; } diff --git a/model/eu07m/eu07m_model.h b/model/eu07m/eu07m_model.h index f72cac374..ead4ef319 100644 --- a/model/eu07m/eu07m_model.h +++ b/model/eu07m/eu07m_model.h @@ -71,6 +71,7 @@ struct model { std::vector key_times; std::vector> key_vectors; std::vector key_rotations; + std::vector geometry_references; // the primitives whose geometry the store keeps std::vector unknown; // the id of the string, adding it when it isn't there yet diff --git a/model/eu07m/eu07m_pack.cpp b/model/eu07m/eu07m_pack.cpp new file mode 100644 index 000000000..c808c9f5d --- /dev/null +++ b/model/eu07m/eu07m_pack.cpp @@ -0,0 +1,230 @@ +/* +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/eu07m/eu07m_pack.h" + +#include "model/eu07m/eu07m_io.h" +#include "model/eu07m/eu07m_store.h" + +#include +#include +#include +#include +#include +#include + +namespace eu07m { + +namespace { + +struct folder_model { + std::filesystem::path path; + model loaded; +}; + +// a block met in the models: its bytes and the files which have it +struct candidate { + std::vector bytes; + std::size_t uses{0}; + bool collision{false}; // another block has the same hash +}; + +std::vector read_file(std::filesystem::path const &Path) { + std::ifstream file{Path, std::ios::binary | std::ios::ate}; + if (false == file.good()) + return {}; + std::vector data(static_cast(file.tellg())); + file.seekg(0); + file.read(reinterpret_cast(data.data()), static_cast(data.size())); + return file.good() ? data : std::vector{}; +} + +bool write_file(std::filesystem::path const &Path, std::span Data) { + // next to it first, so a failed write leaves the file as it was + auto const temporary{std::filesystem::path{Path}.concat(".tmp")}; + { + std::ofstream file{temporary, std::ios::binary}; + file.write(reinterpret_cast(Data.data()), static_cast(Data.size())); + if (false == file.good()) + return false; + } + std::error_code error; + std::filesystem::rename(temporary, Path, error); + return false == bool(error); +} + +bool is_model(std::filesystem::directory_entry const &Entry) { + auto extension{Entry.path().extension().string()}; + std::ranges::transform(extension, extension.begin(), [](unsigned char const Letter) { return static_cast(std::tolower(Letter)); }); + return Entry.is_regular_file() && extension == ".eu07m"; +} + +// the models of the folder read whole, with the store there is; false when one can't be read +bool read_models(std::filesystem::path const &Folder, std::vector &Models, std::uintmax_t &Bytes, std::ostream &Log) { + auto const storepath{Folder / store_file_name}; + auto store{std::make_shared()}; + std::error_code error; + if (std::string reason; std::filesystem::exists(storepath, error) && false == store->open(storepath, reason)) { + Log << std::format("{}: {}\n", storepath.string(), reason); + return false; + } + if (std::filesystem::exists(storepath, error)) + Bytes += std::filesystem::file_size(storepath, error); + read_options options; + options.blocks = store_source(store); + for (auto const &entry : std::filesystem::directory_iterator{Folder, error}) { + if (false == is_model(entry)) + continue; + auto const data{read_file(entry.path())}; + folder_model item{entry.path(), {}}; + if (auto const result{read(data, item.loaded, options)}; false == result.ok) { + Log << std::format("{}: {}\n", entry.path().string(), result.error); + return false; + } + Bytes += data.size(); + Models.push_back(std::move(item)); + } + std::ranges::sort(Models, {}, &folder_model::path); + return true; +} + +bool same_geometry(model const &A, model const &B) { + return A.positions.size() == B.positions.size() && std::ranges::equal(std::as_bytes(std::span{A.positions}), std::as_bytes(std::span{B.positions})) && + std::ranges::equal(std::as_bytes(std::span{A.vertex_attributes}), std::as_bytes(std::span{B.vertex_attributes})) && + std::ranges::equal(std::as_bytes(std::span{A.weights}), std::as_bytes(std::span{B.weights})) && + std::ranges::equal(std::as_bytes(std::span{A.weights_wide}), std::as_bytes(std::span{B.weights_wide})) && + std::ranges::equal(std::as_bytes(std::span{A.vertex_userdata}), std::as_bytes(std::span{B.vertex_userdata})) && + std::ranges::equal(std::as_bytes(std::span{A.bindings}), std::as_bytes(std::span{B.bindings})) && A.indices16 == B.indices16 && A.indices32 == B.indices32; +} + +// the blocks of the shareable primitives of at least MinBytes in all the models, with the files using each +std::map gather(std::vector const &Models, std::size_t const MinBytes) { + std::map candidates; + for (auto const &item : Models) { + for (std::uint32_t idx = 0; idx < item.loaded.primitives.size(); ++idx) { + if (false == shareable(item.loaded, idx)) + continue; + auto block{make_block(item.loaded, item.loaded.primitives[idx])}; + if (block.size() < MinBytes) + continue; + auto &found{candidates[block_hash(block)]}; + if (found.bytes.empty()) + found.bytes = std::move(block); + else if (found.bytes != block) + found.collision = true; + ++found.uses; + } + } + return candidates; +} + +// the references of the model to the blocks of the store +std::vector references(model const &Model, std::map const &Shared, std::size_t const MinBytes) { + std::vector result; + for (std::uint32_t idx = 0; idx < Model.primitives.size(); ++idx) { + if (false == shareable(Model, idx)) + continue; + auto const block{make_block(Model, Model.primitives[idx])}; + if (block.size() < MinBytes) + continue; + auto const hash{block_hash(block)}; + if (false == Shared.contains(hash)) + continue; + auto const &primitive{Model.primitives[idx]}; + geometry_reference_record reference; + reference.primitive = idx; + reference.hash = hash; + reference.vertex_count = primitive.vertex_count; + reference.index_count = (primitive.flags & primitive_flags::indexed) != 0 ? primitive.index_count : 0u; + result.push_back(reference); + } + return result; +} + +// the file of the model, read back with the store and compared with the model before it's written +bool write_checked(folder_model const &Item, model const &Packed, geometry_store const &Store, std::uintmax_t &Bytes, std::ostream &Log) { + auto const file{write(Packed)}; + model check; + read_options options; + options.blocks = [&Store](geometry_reference_record const &Reference, std::vector &Block) { return Store.block(Reference.hash, Block); }; + if (auto const result{read(file, check, options)}; false == result.ok || false == same_geometry(check, Item.loaded)) { + Log << std::format("{}: the model read back isn't the same, left as it was{}\n", Item.path.string(), result.ok ? "" : ": " + result.error); + return false; + } + if (false == write_file(Item.path, file)) { + Log << std::format("{}: can't write it\n", Item.path.string()); + return false; + } + Bytes += file.size(); + return true; +} + +} // namespace + +pack_result pack_folder(std::filesystem::path const &Folder, std::size_t const MinBytes, std::ostream &Log) { + pack_result result; + std::vector models; + if (false == read_models(Folder, models, result.bytes_before, Log)) + return result; + result.models = models.size(); + auto candidates{gather(models, MinBytes)}; + std::erase_if(candidates, [](auto const &Entry) { return Entry.second.uses < 2 || Entry.second.collision; }); + std::vector> blocks; + blocks.reserve(candidates.size()); + for (auto const &entry : candidates) + blocks.push_back(entry.second.bytes); + auto const storefile{write_store(blocks)}; + geometry_store store; + if (std::string reason; false == store.open(storefile, reason)) { + Log << std::format("the store made isn't valid: {}\n", reason); + return result; + } + // the models first, each checked against the store; the store replaces the old one once they all are written + for (auto const &item : models) { + auto packed{item.loaded}; + packed.geometry_references = references(packed, candidates, MinBytes); + result.references += packed.geometry_references.size(); + if (false == write_checked(item, packed, store, result.bytes_after, Log)) + return result; + } + if (false == write_file(Folder / store_file_name, storefile)) { + Log << "can't write the store\n"; + return result; + } + result.bytes_after += storefile.size(); + result.blocks = store.size(); + result.ok = true; + Log << std::format("{}: {} models, {} blocks in the store, {} references; {} bytes -> {} bytes\n", Folder.string(), result.models, result.blocks, result.references, result.bytes_before, + result.bytes_after); + return result; +} + +pack_result unpack_folder(std::filesystem::path const &Folder, std::ostream &Log) { + pack_result result; + std::vector models; + if (false == read_models(Folder, models, result.bytes_before, Log)) + return result; + result.models = models.size(); + for (auto &item : models) { + item.loaded.geometry_references.clear(); + auto const file{write(item.loaded)}; + if (false == write_file(item.path, file)) { + Log << std::format("{}: can't write it\n", item.path.string()); + return result; + } + result.bytes_after += file.size(); + } + result.ok = true; + Log << std::format("{}: {} models written whole, {} bytes; the store can be deleted\n", Folder.string(), result.models, result.bytes_after); + return result; +} + +} // namespace eu07m diff --git a/model/eu07m/eu07m_pack.h b/model/eu07m/eu07m_pack.h new file mode 100644 index 000000000..232372857 --- /dev/null +++ b/model/eu07m/eu07m_pack.h @@ -0,0 +1,37 @@ +/* +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/. +*/ + +#pragma once + +// the geometry store of a folder of EU07M models made and taken apart (-eu07m pack / unpack) + +#include +#include +#include +#include + +namespace eu07m { + +struct pack_result { + bool ok{false}; + std::size_t models{0}; + std::size_t blocks{0}; // in the store + std::size_t references{0}; // of all the models + std::uintmax_t bytes_before{0}; // the models and the store there was + std::uintmax_t bytes_after{0}; +}; + +// the geometry of the primitives of at least MinBytes which occur more than once in the models of the folder moved to its store +// (geometry.eu07mpack), made anew from all of them; the models are written again referring to it. every model is read back and +// compared with what it was before it's replaced. what was done goes to Log +pack_result pack_folder(std::filesystem::path const &Folder, std::size_t MinBytes, std::ostream &Log); +// the models of the folder written again with their whole geometry; the store is left for the user to delete +pack_result unpack_folder(std::filesystem::path const &Folder, std::ostream &Log); + +} // namespace eu07m diff --git a/model/eu07m/eu07m_store.cpp b/model/eu07m/eu07m_store.cpp new file mode 100644 index 000000000..f86871b44 --- /dev/null +++ b/model/eu07m/eu07m_store.cpp @@ -0,0 +1,473 @@ +/* +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/eu07m/eu07m_store.h" + +#include "zstd.h" + +#include +#include +#include +#include +#include +#include + +namespace eu07m { + +namespace { + +// the head of a store file +struct store_header { + std::array magic{'E', 'U', '7', 'P'}; + std::uint16_t major{1}; + std::uint16_t minor{0}; + std::uint32_t block_count{0}; + std::uint32_t flags{0}; + std::uint64_t index_offset{0}; + std::uint64_t reserved{0}; +}; +static_assert(sizeof(store_header) == 32); + +constexpr std::uint32_t entry_zstd{0x1}; +constexpr int store_level{9}; +constexpr std::uint64_t second_seed{0x84222325cbf29ce4ull}; + +// the vertex streams of the model, in the order of the bits of a block, each with its bit +template void each_stream(Model_ &Model, Visit_ &&Visit) { + Visit(block_streams::positions, Model.positions); + Visit(block_streams::attributes, Model.vertex_attributes); + Visit(block_streams::weights, Model.weights); + Visit(block_streams::weights_wide, Model.weights_wide); + Visit(block_streams::userdata, Model.vertex_userdata); + Visit(block_streams::bindings, Model.bindings); +} + +// the size of an element of the vertex stream of the bit +std::size_t element_size(std::uint32_t const Bit) { + switch (Bit) { + case block_streams::positions: return sizeof(position); + case block_streams::attributes: return sizeof(attributes); + case block_streams::weights: return sizeof(skin_weights); + case block_streams::weights_wide: return sizeof(skin_weights_wide); + case block_streams::userdata: return sizeof(userdata); + case block_streams::bindings: return sizeof(vertex_binding); + default: return 0; + } +} + +constexpr std::array stream_bits{block_streams::positions, block_streams::attributes, block_streams::weights, block_streams::weights_wide, block_streams::userdata, + block_streams::bindings}; + +// where the data of the stream of the bit starts in the block (the streams before it, then the indices for a bit past them all) +std::size_t stream_offset(block_header const &Header, std::uint32_t const Bit) { + std::size_t offset{sizeof(block_header)}; + for (auto const other : stream_bits) { + if (other < Bit && (Header.streams & other) != 0) + offset += std::size_t{Header.vertex_count} * element_size(other); + } + return offset; +} + +// whether the index of the store fits in a file of Size bytes and is sorted +bool valid_index(std::vector const &Index, std::uint64_t const Size) { + return std::ranges::all_of(Index, [Size](store_entry const &Entry) { return Entry.offset + Entry.stored_size <= Size; }) && std::ranges::is_sorted(Index, {}, &store_entry::hash); +} + +bool valid_header(store_header const &Header, std::uint64_t const Size) { + return Header.magic == store_header{}.magic && Header.major == 1 && Header.index_offset <= Size && (Size - Header.index_offset) / sizeof(store_entry) >= Header.block_count; +} + +bool indexed(primitive_record const &Primitive) { + return (Primitive.flags & primitive_flags::indexed) != 0; +} + +std::uint32_t index_size(primitive_record const &Primitive) { + if (false == indexed(Primitive)) + return 0; + return (Primitive.flags & primitive_flags::index32) != 0 ? 4u : 2u; +} + +bool overlap(std::uint64_t const First, std::uint64_t const Count, std::uint64_t const OtherFirst, std::uint64_t const OtherCount) { + return (Count > 0) && (OtherCount > 0) && (First < OtherFirst + OtherCount) && (OtherFirst < First + Count); +} + +template void append(std::vector &Output, std::span const Values) { + auto const bytes{std::as_bytes(Values)}; + Output.insert(Output.end(), bytes.begin(), bytes.end()); +} + +// a piece of a stream which the store keeps: where it goes in the whole stream and its bytes +struct piece { + std::size_t offset{0}; // in elements + std::span data; +}; + +// the whole stream from the part the file kept and the pieces of the store, put in at their places (sorted by them) +template bool rebuild(std::vector &Stream, std::vector const &Pieces, std::string_view const Name, std::string &Error) { + std::vector result; + std::size_t kept{0}; + for (auto const &part : Pieces) { + if (part.offset < result.size() || (part.data.size() % sizeof(Type_)) != 0 || kept + (part.offset - result.size()) > Stream.size()) { + Error = std::format("the pieces of the geometry store don't fit in stream {}", Name); + return false; + } + auto const gap{part.offset - result.size()}; + result.insert(result.end(), Stream.begin() + static_cast(kept), Stream.begin() + static_cast(kept + gap)); + kept += gap; + auto const count{part.data.size() / sizeof(Type_)}; + auto const first{result.size()}; + result.resize(first + count); + std::memcpy(static_cast(result.data() + first), part.data.data(), part.data.size()); + } + result.insert(result.end(), Stream.begin() + static_cast(kept), Stream.end()); + Stream = std::move(result); + return true; +} + +// the stream without the ranges (sorted, apart) +template void cut(std::vector &Stream, std::vector> const &Ranges) { + if (Stream.empty() || Ranges.empty()) + return; + std::vector result; + result.reserve(Stream.size()); + std::size_t next{0}; + for (auto const &[first, count] : Ranges) { + if (first > Stream.size()) + break; + result.insert(result.end(), Stream.begin() + static_cast(next), Stream.begin() + static_cast(first)); + next = std::min(first + count, Stream.size()); + } + result.insert(result.end(), Stream.begin() + static_cast(next), Stream.end()); + Stream = std::move(result); +} + +// a block of a reference read and checked against it and its primitive +struct block_view { + block_header header; + std::vector bytes; + primitive_record primitive; +}; + +bool read_block(model const &Model, geometry_reference_record const &Reference, block_source const &Source, block_view &View, std::string &Error) { + if (Reference.primitive >= Model.primitives.size()) { + Error = std::format("a geometry reference names primitive {}, which the model hasn't", Reference.primitive); + return false; + } + View.primitive = Model.primitives[Reference.primitive]; + if ((Source == nullptr) || false == Source(Reference, View.bytes)) { + Error = std::format("the geometry store hasn't the block of primitive {}", Reference.primitive); + return false; + } + if (View.bytes.size() < sizeof(block_header) || block_hash(View.bytes) != Reference.hash) { + Error = std::format("the block of primitive {} in the geometry store isn't the one the model refers to", Reference.primitive); + return false; + } + std::memcpy(&View.header, View.bytes.data(), sizeof(block_header)); + auto const &primitive{View.primitive}; + auto const indices{indexed(primitive) ? primitive.index_count : 0u}; + if (View.header.vertex_count != primitive.vertex_count || View.header.vertex_count != Reference.vertex_count || View.header.index_count != indices || + View.header.index_count != Reference.index_count || View.header.index_size != index_size(primitive)) { + Error = std::format("the block of primitive {} in the geometry store has other counts than the primitive", Reference.primitive); + return false; + } + return true; +} + +// the pieces of the blocks for one vertex stream; false when a block lacks a stream the model has +template +bool vertex_pieces(std::vector const &Blocks, std::uint32_t const Bit, bool const Present, std::vector &Pieces, std::string &Error) { + for (auto const &block : Blocks) { + if ((block.header.streams & Bit) == 0) { + if (Present) { + Error = "a block of the geometry store lacks a vertex stream the model has"; + return false; + } + continue; + } + auto const offset{stream_offset(block.header, Bit)}; + auto const size{std::size_t{block.header.vertex_count} * sizeof(Type_)}; + if (offset + size > block.bytes.size()) { + Error = "a block of the geometry store is cut short"; + return false; + } + Pieces.push_back({block.primitive.base_vertex, std::span{block.bytes}.subspan(offset, size)}); + } + return true; +} + +bool index_pieces(std::vector const &Blocks, std::uint32_t const Size, std::vector &Pieces, std::string &Error) { + for (auto const &block : Blocks) { + if (block.header.index_size != Size || block.header.index_count == 0) + continue; + auto const offset{stream_offset(block.header, 0x80000000u)}; + auto const size{std::size_t{block.header.index_count} * Size}; + if (offset + size > block.bytes.size()) { + Error = "a block of the geometry store is cut short"; + return false; + } + Pieces.push_back({block.primitive.first_index, std::span{block.bytes}.subspan(offset, size)}); + } + std::ranges::sort(Pieces, {}, &piece::offset); + return true; +} + +std::vector pack_block(std::span Block, std::uint32_t &Flags) { + std::vector packed(ZSTD_compressBound(Block.size())); + auto const size{ZSTD_compress(packed.data(), packed.size(), Block.data(), Block.size(), store_level)}; + if (ZSTD_isError(size) || size + size / 8 >= Block.size()) { + Flags = 0; + return {Block.begin(), Block.end()}; + } + packed.resize(size); + Flags = entry_zstd; + return packed; +} + +} // namespace + +bool shareable(model const &Model, std::uint32_t const Primitive) { + if (Primitive >= Model.primitives.size()) + return false; + auto const &primitive{Model.primitives[Primitive]}; + if (primitive.vertex_count == 0 || std::uint64_t{primitive.base_vertex} + primitive.vertex_count > Model.vertex_count()) + return false; + for (std::uint32_t idx = 0; idx < Model.primitives.size(); ++idx) { + if (idx == Primitive) + continue; + auto const &other{Model.primitives[idx]}; + if (overlap(primitive.base_vertex, primitive.vertex_count, other.base_vertex, other.vertex_count)) + return false; + if (indexed(primitive) && index_size(other) == index_size(primitive) && overlap(primitive.first_index, primitive.index_count, other.first_index, other.index_count)) + return false; + } + return true; +} + +std::vector make_block(model const &Model, primitive_record const &Primitive) { + block_header header; + header.vertex_count = Primitive.vertex_count; + header.index_count = indexed(Primitive) ? Primitive.index_count : 0u; + header.index_size = index_size(Primitive); + auto const vertices{Model.vertex_count()}; + each_stream(Model, [&header, vertices](std::uint32_t const Bit, auto const &Stream) { + if (false == Stream.empty() && Stream.size() == vertices) + header.streams |= Bit; + }); + std::vector block; + append(block, std::span{&header, 1}); + each_stream(Model, [&header, &block, &Primitive](std::uint32_t const Bit, auto const &Stream) { + if ((header.streams & Bit) != 0) + append(block, std::span{Stream}.subspan(Primitive.base_vertex, Primitive.vertex_count)); + }); + if (header.index_size == 2) + append(block, std::span{Model.indices16}.subspan(Primitive.first_index, Primitive.index_count)); + else if (header.index_size == 4) + append(block, std::span{Model.indices32}.subspan(Primitive.first_index, Primitive.index_count)); + return block; +} + +block_id block_hash(std::span const Block) { + return {hash_bytes(Block), hash_bytes(Block, second_seed)}; +} + +bool insert_blocks(model &Model, block_source const &Source, std::string &Error) { + if (Model.geometry_references.empty()) + return true; + std::vector blocks; + blocks.reserve(Model.geometry_references.size()); + for (auto const &reference : Model.geometry_references) { + if (false == read_block(Model, reference, Source, blocks.emplace_back(), Error)) + return false; + } + std::ranges::sort(blocks, {}, [](block_view const &Block) { return Block.primitive.base_vertex; }); + auto ok{true}; + each_stream(Model, [&blocks, &Error, &ok](std::uint32_t const Bit, auto &Stream) { + using element = typename std::remove_cvref_t::value_type; + auto const present{false == Stream.empty() || std::ranges::any_of(blocks, [Bit](block_view const &Block) { return (Block.header.streams & Bit) != 0; })}; + if (false == ok || false == present) + return; + std::vector pieces; + ok = vertex_pieces(blocks, Bit, present, pieces, Error) && rebuild(Stream, pieces, "of vertices", Error); + }); + if (false == ok) + return false; + std::vector narrow; + std::vector wide; + return index_pieces(blocks, 2, narrow, Error) && rebuild(Model.indices16, narrow, "IDX2", Error) && index_pieces(blocks, 4, wide, Error) && + rebuild(Model.indices32, wide, "IDX4", Error); +} + +model remove_referenced(model const &Model) { + model result{Model}; + std::vector> vertices; + std::vector> narrow; + std::vector> wide; + for (auto const &reference : Model.geometry_references) { + if (reference.primitive >= Model.primitives.size()) + continue; + auto const &primitive{Model.primitives[reference.primitive]}; + vertices.emplace_back(primitive.base_vertex, primitive.vertex_count); + if (index_size(primitive) == 2) + narrow.emplace_back(primitive.first_index, primitive.index_count); + else if (index_size(primitive) == 4) + wide.emplace_back(primitive.first_index, primitive.index_count); + } + std::ranges::sort(vertices); + std::ranges::sort(narrow); + std::ranges::sort(wide); + each_stream(result, [&vertices](std::uint32_t, auto &Stream) { cut(Stream, vertices); }); + cut(result.indices16, narrow); + cut(result.indices32, wide); + return result; +} + +std::vector write_store(std::vector> const &Blocks) { + std::map const *> unique; + for (auto const &block : Blocks) + unique.try_emplace(block_hash(block), &block); + std::vector file(sizeof(store_header)); + std::vector index; + index.reserve(unique.size()); + for (auto const &[hash, block] : unique) { + store_entry entry; + entry.hash = hash; + entry.offset = file.size(); + entry.size = static_cast(block->size()); + auto const packed{pack_block(*block, entry.flags)}; + entry.stored_size = static_cast(packed.size()); + file.insert(file.end(), packed.begin(), packed.end()); + index.push_back(entry); + } + store_header header; + header.block_count = static_cast(index.size()); + header.index_offset = file.size(); + append(file, std::span{index}); + std::memcpy(file.data(), &header, sizeof(header)); + return file; +} + +bool geometry_store::open(std::filesystem::path const &Path, std::string &Error) { + m_path = Path; + m_data.clear(); + m_index.clear(); + std::ifstream file{Path, std::ios::binary | std::ios::ate}; + if (false == file.good()) { + Error = "can't read the geometry store"; + return false; + } + auto const size{static_cast(file.tellg())}; + store_header header; + file.seekg(0); + if (size < sizeof(header) || false == bool(file.read(reinterpret_cast(&header), sizeof(header))) || false == valid_header(header, size)) { + Error = "the geometry store isn't one, or is of a later version"; + return false; + } + m_index.resize(header.block_count); + file.seekg(static_cast(header.index_offset)); + if (false == bool(file.read(reinterpret_cast(m_index.data()), static_cast(m_index.size() * sizeof(store_entry))))) { + m_index.clear(); + Error = "the index of the geometry store is cut short"; + return false; + } + if (false == valid_index(m_index, size)) { + m_index.clear(); + Error = "the index of the geometry store is out of order or out of the file"; + return false; + } + return true; +} + +bool geometry_store::open(std::vector Data, std::string &Error) { + m_path.clear(); + m_index.clear(); + m_data = std::move(Data); + store_header header; + if (m_data.size() < sizeof(header)) { + Error = "the geometry store is cut short"; + return false; + } + std::memcpy(&header, m_data.data(), sizeof(header)); + if (false == valid_header(header, m_data.size())) { + Error = "the geometry store isn't one, or is of a later version"; + return false; + } + m_index.resize(header.block_count); + std::memcpy(m_index.data(), m_data.data() + header.index_offset, m_index.size() * sizeof(store_entry)); + if (false == valid_index(m_index, m_data.size())) { + m_index.clear(); + Error = "the index of the geometry store is out of order or out of the file"; + return false; + } + return true; +} + +bool geometry_store::stored(store_entry const &Entry, std::vector &Bytes) const { + Bytes.resize(Entry.stored_size); + if (false == m_data.empty()) { + std::memcpy(Bytes.data(), m_data.data() + Entry.offset, Entry.stored_size); + return true; + } + std::ifstream file{m_path, std::ios::binary}; + file.seekg(static_cast(Entry.offset)); + return bool(file.read(reinterpret_cast(Bytes.data()), static_cast(Bytes.size()))); +} + +bool geometry_store::block(block_id const &Hash, std::vector &Block) const { + auto const found{std::ranges::lower_bound(m_index, Hash, {}, &store_entry::hash)}; + if (found == m_index.end() || found->hash != Hash) + return false; + std::vector bytes; + if (false == stored(*found, bytes)) + return false; + if ((found->flags & entry_zstd) == 0) { + Block = std::move(bytes); + return Block.size() == found->size; + } + Block.resize(found->size); + auto const size{ZSTD_decompress(Block.data(), Block.size(), bytes.data(), bytes.size())}; + return (false == ZSTD_isError(size)) && size == found->size; +} + +std::vector geometry_store::blocks() const { + std::vector result; + result.reserve(m_index.size()); + std::ranges::transform(m_index, std::back_inserter(result), &store_entry::hash); + return result; +} + +block_source store_source(std::shared_ptr Store) { + if (Store == nullptr) + return {}; + return [Store = std::move(Store)](geometry_reference_record const &Reference, std::vector &Block) { return Store->block(Reference.hash, Block); }; +} + +std::shared_ptr family_store(std::filesystem::path const &ModelFile) { + static std::mutex mutex; + static std::map> stores; + auto path{ModelFile.parent_path() / store_file_name}; + std::error_code error; + if (auto canonical{std::filesystem::weakly_canonical(path, error)}; false == bool(error)) + path = std::move(canonical); + std::scoped_lock lock{mutex}; + if (auto const found{stores.find(path)}; found != stores.end()) + return found->second; + std::shared_ptr result; + if (std::filesystem::exists(path, error)) { + auto store{std::make_shared()}; + std::string reason; + if (store->open(path, reason)) + result = std::move(store); + } + stores.emplace(path, result); + return result; +} + +} // namespace eu07m diff --git a/model/eu07m/eu07m_store.h b/model/eu07m/eu07m_store.h new file mode 100644 index 000000000..f346a3c71 --- /dev/null +++ b/model/eu07m/eu07m_store.h @@ -0,0 +1,105 @@ +/* +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/. +*/ + +#pragma once + +// the geometry shared by the models of a family (the variants of a vehicle): blocks of the geometry of primitives kept once in the +// store of the folder (geometry.eu07mpack) and referred to by the models (GREF) instead of being repeated in each of them + +#include "model/eu07m/eu07m_model.h" + +#include +#include +#include +#include +#include +#include + +namespace eu07m { + +using block_id = std::array; + +// the name of the store in the folder of the models +constexpr char const *store_file_name{"geometry.eu07mpack"}; + +// the streams a block carries, in this order after its header +namespace block_streams { +constexpr std::uint32_t positions{0x1}; +constexpr std::uint32_t attributes{0x2}; +constexpr std::uint32_t weights{0x4}; +constexpr std::uint32_t weights_wide{0x8}; +constexpr std::uint32_t userdata{0x10}; +constexpr std::uint32_t bindings{0x20}; +} // namespace block_streams + +// the head of a block: the streams it has, its vertices and indices, and the size of an index (0, 2 or 4) +struct block_header { + std::uint32_t streams{0}; + std::uint32_t vertex_count{0}; + std::uint32_t index_count{0}; + std::uint32_t index_size{0}; +}; +static_assert(sizeof(block_header) == 16); + +// whether the geometry of the primitive can go to the store: it has vertices, and its vertex and index ranges are its own +bool shareable(model const &Model, std::uint32_t Primitive); +// the block of the primitive: its vertices in every vertex stream the model has and its indices +std::vector make_block(model const &Model, primitive_record const &Primitive); +// 128 bits of the block: two FNV-1a 64 of its bytes with different seeds +block_id block_hash(std::span Block); + +// gives the block of a reference; false when there's none +using block_source = std::function &Block)>; +// the blocks of the references of the model put back in the places of their primitives in the streams, which the file has without +// them. false with the reason when a block is missing or doesn't fit +bool insert_blocks(model &Model, block_source const &Source, std::string &Error); +// the streams of the model without the ranges of the primitives it refers to, as the file keeps them +model remove_referenced(model const &Model); + +// the file of a store holding the blocks, each once (by its hash and its bytes), sorted by their hash +std::vector write_store(std::vector> const &Blocks); + +// an entry of the index of a store: the hash of the block, where it lies, its sizes in the file and unpacked +struct store_entry { + block_id hash{}; + std::uint64_t offset{0}; + std::uint32_t stored_size{0}; + std::uint32_t size{0}; + std::uint32_t flags{0}; // 0x1 zstd + std::uint32_t reserved{0}; +}; +static_assert(sizeof(store_entry) == 40); + +class geometry_store { + public: + // the index of a store file; the blocks are read from the file when asked for + bool open(std::filesystem::path const &Path, std::string &Error); + // a store held in memory + bool open(std::vector Data, std::string &Error); + // the block with the hash, unpacked; false when the store hasn't it + bool block(block_id const &Hash, std::vector &Block) const; + std::vector blocks() const; + std::size_t size() const { + return m_index.size(); + } + + private: + bool stored(store_entry const &Entry, std::vector &Bytes) const; + + std::filesystem::path m_path; + std::vector m_data; // a store in memory + std::vector m_index; +}; + +// the store of the folder of the model file, opened once in a process and kept; nullptr when the folder has none +std::shared_ptr family_store(std::filesystem::path const &ModelFile); +// the blocks of the store, for read_options::blocks; none without a store +block_source store_source(std::shared_ptr Store); + +} // namespace eu07m diff --git a/tests/unit/test_gref.cpp b/tests/unit/test_gref.cpp new file mode 100644 index 000000000..8020eb640 --- /dev/null +++ b/tests/unit/test_gref.cpp @@ -0,0 +1,213 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_io.h" +#include "model/eu07m/eu07m_pack.h" +#include "model/eu07m/eu07m_store.h" + +#include +#include +#include + +namespace { + +// a model of two meshes: a grid of Size x Size vertices, offset by Shift (the part the variants share when they have the same +// shift), and a small quad of its own +eu07m::model variant(int const Size, float const Shift, float const QuadHeight) { + eu07m::model model; + auto const node{[&model](std::string_view const Name, std::int32_t const Parent) { + eu07m::node_record record; + record.name = model.intern(Name); + record.parent = Parent; + model.nodes.push_back(record); + return static_cast(model.nodes.size() - 1); + }}; + auto const root{node("root", -1)}; + auto const body{node("body", static_cast(root))}; + auto const plate{node("plate", static_cast(root))}; + model.nodes[root].subtree_end = 3; + model.nodes[body].subtree_end = 2; + model.nodes[plate].subtree_end = 3; + model.materials.push_back({}); + auto const add_primitive = [&model](std::uint32_t const Node, std::uint32_t const First, std::uint32_t const Base, std::uint32_t const Vertices, std::uint32_t const Indices) { + eu07m::primitive_record primitive; + primitive.first_index = First; + primitive.index_count = Indices; + primitive.base_vertex = Base; + primitive.vertex_count = Vertices; + primitive.node = Node; + primitive.flags = static_cast(eu07m::topology::triangles) | eu07m::primitive_flags::indexed | eu07m::primitive_flags::opaque; + model.meshes.push_back({static_cast(model.primitives.size()), 1, -1, 0}); + model.nodes[Node].mesh = static_cast(model.meshes.size() - 1); + model.primitives.push_back(primitive); + }; + auto const vertex = [&model](float const X, float const Y, float const Z) { + model.positions.push_back({X, Y, Z}); + eu07m::attributes attribute; + attribute.qtangent = eu07m::encode_qtangent({{0.f, 0.f, 1.f}, {1.f, 0.f, 0.f}, 1.f}); + attribute.uv = {X, Y}; + model.vertex_attributes.push_back(attribute); + }; + for (int y = 0; y < Size; ++y) + for (int x = 0; x < Size; ++x) + vertex(static_cast(x) + Shift, static_cast(y), 0.f); + for (int y = 0; y + 1 < Size; ++y) { + for (int x = 0; x + 1 < Size; ++x) { + auto const a{static_cast(y * Size + x)}; + auto const b{static_cast(a + 1)}; + auto const c{static_cast(a + Size)}; + auto const d{static_cast(c + 1)}; + for (auto const index : {a, b, d, a, d, c}) + model.indices16.push_back(index); + } + } + add_primitive(body, 0, 0, static_cast(Size * Size), static_cast(model.indices16.size())); + auto const base{static_cast(model.positions.size())}; + auto const first{static_cast(model.indices16.size())}; + for (auto const &corner : std::array, 4>{{{0.f, 0.f}, {1.f, 0.f}, {1.f, 1.f}, {0.f, 1.f}}}) + vertex(corner[0], corner[1], QuadHeight); + model.indices16.insert(model.indices16.end(), {0, 1, 2, 0, 2, 3}); + add_primitive(plate, first, base, 4, 6); + eu07m::build_name_index(model); + eu07m::compute_bounds(model); + return model; +} + +eu07m::block_source memory_source(eu07m::geometry_store const &Store) { + return [&Store](eu07m::geometry_reference_record const &Reference, std::vector &Block) { return Store.block(Reference.hash, Block); }; +} + +bool same_streams(eu07m::model const &A, eu07m::model const &B) { + return std::ranges::equal(std::as_bytes(std::span{A.positions}), std::as_bytes(std::span{B.positions})) && + std::ranges::equal(std::as_bytes(std::span{A.vertex_attributes}), std::as_bytes(std::span{B.vertex_attributes})) && A.indices16 == B.indices16; +} + +void save(std::filesystem::path const &Path, std::span Data) { + std::ofstream file{Path, std::ios::binary}; + file.write(reinterpret_cast(Data.data()), static_cast(Data.size())); +} + +std::vector load(std::filesystem::path const &Path) { + std::ifstream file{Path, std::ios::binary | std::ios::ate}; + std::vector data(static_cast(file.tellg())); + file.seekg(0); + file.read(reinterpret_cast(data.data()), static_cast(data.size())); + return data; +} + +} // namespace + +TEST_CASE("gref: a primitive kept in the store comes back whole") { + auto model{variant(30, 0.f, 2.f)}; + REQUIRE(eu07m::shareable(model, 0)); + auto const block{eu07m::make_block(model, model.primitives[0])}; + eu07m::geometry_store store; + std::string error; + REQUIRE(store.open(eu07m::write_store({block}), error)); + CHECK(store.size() == 1); + + eu07m::geometry_reference_record reference; + reference.primitive = 0; + reference.hash = eu07m::block_hash(block); + reference.vertex_count = model.primitives[0].vertex_count; + reference.index_count = model.primitives[0].index_count; + model.geometry_references.push_back(reference); + CHECK(eu07m::validate(model, 16).empty()); + auto const whole{eu07m::write(variant(30, 0.f, 2.f))}; + auto const file{eu07m::write(model)}; + CHECK(file.size() < whole.size() / 2); + + eu07m::model read; + eu07m::read_options options; + options.blocks = memory_source(store); + REQUIRE(eu07m::read(file, read, options).ok); + CHECK(same_streams(read, model)); + CHECK(read.geometry_references.size() == 1); + // written again from what was read, the same file + CHECK(eu07m::write(read) == file); + + // without the store the file is refused + eu07m::model refused; + auto const result{eu07m::read(file, refused, {})}; + CHECK_FALSE(result.ok); + CHECK(result.error.find("geometry store") != std::string::npos); +} + +TEST_CASE("gref: a block which isn't the one referred to is refused") { + auto model{variant(30, 0.f, 2.f)}; + auto block{eu07m::make_block(model, model.primitives[0])}; + eu07m::geometry_reference_record reference; + reference.primitive = 0; + reference.hash = eu07m::block_hash(block); + reference.vertex_count = model.primitives[0].vertex_count; + reference.index_count = model.primitives[0].index_count; + model.geometry_references.push_back(reference); + auto const file{eu07m::write(model)}; + // a vertex of the block changed: the hash doesn't match + block[sizeof(eu07m::block_header) + 4] ^= std::byte{0x40}; + eu07m::geometry_store store; + std::string error; + REQUIRE(store.open(eu07m::write_store({block}), error)); + eu07m::model read; + eu07m::read_options options; + options.blocks = [&store, &block](eu07m::geometry_reference_record const &, std::vector &Out) { return store.block(eu07m::block_hash(block), Out); }; + CHECK_FALSE(eu07m::read(file, read, options).ok); +} + +TEST_CASE("gref: a primitive sharing its vertices can't be kept in the store") { + auto model{variant(10, 0.f, 2.f)}; + model.primitives[1].base_vertex = 0; // the quad on the vertices of the grid + CHECK_FALSE(eu07m::shareable(model, 0)); + eu07m::geometry_reference_record reference; + reference.primitive = 0; + reference.vertex_count = model.primitives[0].vertex_count; + reference.index_count = model.primitives[0].index_count; + model.geometry_references.push_back(reference); + CHECK_FALSE(eu07m::validate(model, 16).empty()); +} + +TEST_CASE("gref: a folder packed and unpacked") { + auto const folder{std::filesystem::path{EU07_UNIT_TESTS_SCRATCH} / "gref_family"}; + std::filesystem::remove_all(folder); + std::filesystem::create_directories(folder); + // two variants with the same grid, one with a grid of its own; the quads differ + auto const a{variant(40, 0.f, 1.f)}; + auto const b{variant(40, 0.f, 2.f)}; + auto const c{variant(40, 5.f, 3.f)}; + save(folder / "a.eu07m", eu07m::write(a)); + save(folder / "b.eu07m", eu07m::write(b)); + save(folder / "c.eu07m", eu07m::write(c)); + + std::ostringstream log; + auto const packed{eu07m::pack_folder(folder, 4096, log)}; + CAPTURE(log.str()); + REQUIRE(packed.ok); + CHECK(packed.models == 3); + CHECK(packed.blocks == 1); // the grid of a and b; the quads are too small, c's grid is its own + CHECK(packed.references == 2); + CHECK(packed.bytes_after < packed.bytes_before); + + eu07m::geometry_store store; + std::string error; + REQUIRE(store.open(folder / eu07m::store_file_name, error)); + eu07m::read_options options; + options.blocks = memory_source(store); + for (auto const &[name, original] : {std::pair{"a.eu07m", &a}, std::pair{"b.eu07m", &b}, std::pair{"c.eu07m", &c}}) { + eu07m::model read; + REQUIRE(eu07m::read(load(folder / name), read, options).ok); + CHECK(same_streams(read, *original)); + } + + // packed again, the same + std::ostringstream again; + CHECK(eu07m::pack_folder(folder, 4096, again).blocks == 1); + auto const unpacked{eu07m::unpack_folder(folder, log)}; + REQUIRE(unpacked.ok); + eu07m::model whole; + REQUIRE(eu07m::read(load(folder / "b.eu07m"), whole, {}).ok); + CHECK(whole.geometry_references.empty()); + CHECK(same_streams(whole, b)); + std::filesystem::remove_all(folder); +} From 1638fc919b0d0ff04cf4362d432a728ec95026e1 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:22:04 +0100 Subject: [PATCH 2/3] fix(model): EU07M review of #545: a pack failing half way leaves the folder loading, a store packed anew opened again - pack_folder() writes a store of the old blocks and the new ones together before the models, then the models, then the store of the new blocks alone: a failure on any model (a rename refused, the disk full) leaves models packed against either store, all of which load. Before, models 1..k referred to blocks no store on the disk had. - write_file() closes the stream before it checks it (what sat in its buffer is written by the close) and removes the .tmp of a failed write. - family_store() opens the store of a folder again when its size or time changed (packed anew while the game runs): its blocks are read from the file by the offsets of the index, which then belonged to another file. A store which can't be opened is told in the log once, with the reason, instead of every model of the folder reporting a missing block. - The game finds a block by its hash and checks its counts; the bytes are hashed again only with verify_hash, as the tools read (insert_blocks(..., Verify)), so a load no longer hashes every block twice. - The index of a store is checked without the offset and the size wrapping, and a block may unpack to 1 GiB at most. --- model/eu07m/eu07m_io.cpp | 2 +- model/eu07m/eu07m_pack.cpp | 44 ++++++++++++++++++++++++++--- model/eu07m/eu07m_store.cpp | 56 ++++++++++++++++++++++++++----------- model/eu07m/eu07m_store.h | 5 ++-- tests/unit/test_gref.cpp | 1 + 5 files changed, 84 insertions(+), 24 deletions(-) diff --git a/model/eu07m/eu07m_io.cpp b/model/eu07m/eu07m_io.cpp index 2a8c98bc5..a3c0edda9 100644 --- a/model/eu07m/eu07m_io.cpp +++ b/model/eu07m/eu07m_io.cpp @@ -665,7 +665,7 @@ read_result file_reader::run(model &Model) { } } // the geometry kept in the store of the family goes back in its place in the streams - if (std::string error; false == insert_blocks(Model, m_options.blocks, error)) { + if (std::string error; false == insert_blocks(Model, m_options.blocks, error, m_options.verify_hash)) { Model = model{}; return {false, error}; } diff --git a/model/eu07m/eu07m_pack.cpp b/model/eu07m/eu07m_pack.cpp index c808c9f5d..3e366e5c3 100644 --- a/model/eu07m/eu07m_pack.cpp +++ b/model/eu07m/eu07m_pack.cpp @@ -50,15 +50,24 @@ std::vector read_file(std::filesystem::path const &Path) { bool write_file(std::filesystem::path const &Path, std::span Data) { // next to it first, so a failed write leaves the file as it was auto const temporary{std::filesystem::path{Path}.concat(".tmp")}; + std::error_code error; { std::ofstream file{temporary, std::ios::binary}; file.write(reinterpret_cast(Data.data()), static_cast(Data.size())); - if (false == file.good()) + // closed before the check: what still sat in the buffer of the stream is written by the close + file.close(); + if (file.fail()) { + std::filesystem::remove(temporary, error); return false; + } } - std::error_code error; std::filesystem::rename(temporary, Path, error); - return false == bool(error); + if (error) { + std::error_code ignored; + std::filesystem::remove(temporary, ignored); + return false; + } + return true; } bool is_model(std::filesystem::directory_entry const &Entry) { @@ -167,6 +176,29 @@ bool write_checked(folder_model const &Item, model const &Packed, geometry_store return true; } +// the store of the folder made of the blocks it has (when it has one which can be read) and the new ones +bool write_bridge_store(std::filesystem::path const &Folder, std::vector> const &Blocks, std::ostream &Log) { + auto all{Blocks}; + std::error_code error; + if (auto const path{Folder / store_file_name}; std::filesystem::exists(path, error)) { + geometry_store old; + if (std::string reason; old.open(path, reason)) { + for (auto const &id : old.blocks()) { + if (std::vector block; old.block(id, block)) + all.push_back(std::move(block)); + } + } + else { + Log << std::format("the old store can't be read ({}), its blocks aren't kept\n", reason); + } + } + if (false == write_file(Folder / store_file_name, write_store(all))) { + Log << "can't write the store\n"; + return false; + } + return true; +} + } // namespace pack_result pack_folder(std::filesystem::path const &Folder, std::size_t const MinBytes, std::ostream &Log) { @@ -187,7 +219,11 @@ pack_result pack_folder(std::filesystem::path const &Folder, std::size_t const M Log << std::format("the store made isn't valid: {}\n", reason); return result; } - // the models first, each checked against the store; the store replaces the old one once they all are written + // first a store with the blocks of the old one and the new ones together: while the models are written one by one, the folder + // holds models packed against either, and a write failing half way leaves them all loading + if (false == write_bridge_store(Folder, blocks, Log)) + return result; + // then the models, each checked against the store; the store of the new blocks alone replaces the other once they all are for (auto const &item : models) { auto packed{item.loaded}; packed.geometry_references = references(packed, candidates, MinBytes); diff --git a/model/eu07m/eu07m_store.cpp b/model/eu07m/eu07m_store.cpp index f86871b44..a51bca2fd 100644 --- a/model/eu07m/eu07m_store.cpp +++ b/model/eu07m/eu07m_store.cpp @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "model/eu07m/eu07m_store.h" +#include "utilities/Logs.h" #include "zstd.h" #include @@ -76,9 +77,13 @@ std::size_t stream_offset(block_header const &Header, std::uint32_t const Bit) { return offset; } +// the largest block unpacked, so a broken index can't make the reader take all the memory +constexpr std::uint32_t block_size_limit{std::uint32_t{1} << 30}; + // whether the index of the store fits in a file of Size bytes and is sorted bool valid_index(std::vector const &Index, std::uint64_t const Size) { - return std::ranges::all_of(Index, [Size](store_entry const &Entry) { return Entry.offset + Entry.stored_size <= Size; }) && std::ranges::is_sorted(Index, {}, &store_entry::hash); + auto const fits{[Size](store_entry const &Entry) { return Entry.offset <= Size && Entry.stored_size <= Size - Entry.offset && Entry.size <= block_size_limit; }}; + return std::ranges::all_of(Index, fits) && std::ranges::is_sorted(Index, {}, &store_entry::hash); } bool valid_header(store_header const &Header, std::uint64_t const Size) { @@ -156,7 +161,7 @@ struct block_view { primitive_record primitive; }; -bool read_block(model const &Model, geometry_reference_record const &Reference, block_source const &Source, block_view &View, std::string &Error) { +bool read_block(model const &Model, geometry_reference_record const &Reference, block_source const &Source, bool const Verify, block_view &View, std::string &Error) { if (Reference.primitive >= Model.primitives.size()) { Error = std::format("a geometry reference names primitive {}, which the model hasn't", Reference.primitive); return false; @@ -166,7 +171,9 @@ bool read_block(model const &Model, geometry_reference_record const &Reference, Error = std::format("the geometry store hasn't the block of primitive {}", Reference.primitive); return false; } - if (View.bytes.size() < sizeof(block_header) || block_hash(View.bytes) != Reference.hash) { + // the block is found by its hash; its bytes are hashed again only when the content of the file is checked too (verify_hash), + // which the game doesn't do, as the store is read from the same disk as the model + if (View.bytes.size() < sizeof(block_header) || (Verify && block_hash(View.bytes) != Reference.hash)) { Error = std::format("the block of primitive {} in the geometry store isn't the one the model refers to", Reference.primitive); return false; } @@ -278,13 +285,13 @@ block_id block_hash(std::span const Block) { return {hash_bytes(Block), hash_bytes(Block, second_seed)}; } -bool insert_blocks(model &Model, block_source const &Source, std::string &Error) { +bool insert_blocks(model &Model, block_source const &Source, std::string &Error, bool const Verify) { if (Model.geometry_references.empty()) return true; std::vector blocks; blocks.reserve(Model.geometry_references.size()); for (auto const &reference : Model.geometry_references) { - if (false == read_block(Model, reference, Source, blocks.emplace_back(), Error)) + if (false == read_block(Model, reference, Source, Verify, blocks.emplace_back(), Error)) return false; } std::ranges::sort(blocks, {}, [](block_view const &Block) { return Block.primitive.base_vertex; }); @@ -450,24 +457,39 @@ block_source store_source(std::shared_ptr Store) { } std::shared_ptr family_store(std::filesystem::path const &ModelFile) { + // the store of a folder as it was opened: a file which changed since (packed anew while the game runs) is opened again, as + // its blocks are read from the file by the offsets of the index + struct cached { + std::shared_ptr store; + bool exists{false}; + std::uintmax_t size{0}; + std::filesystem::file_time_type time{}; + }; static std::mutex mutex; - static std::map> stores; + static std::map stores; auto path{ModelFile.parent_path() / store_file_name}; std::error_code error; if (auto canonical{std::filesystem::weakly_canonical(path, error)}; false == bool(error)) path = std::move(canonical); - std::scoped_lock lock{mutex}; - if (auto const found{stores.find(path)}; found != stores.end()) - return found->second; - std::shared_ptr result; - if (std::filesystem::exists(path, error)) { - auto store{std::make_shared()}; - std::string reason; - if (store->open(path, reason)) - result = std::move(store); + cached state; + state.exists = std::filesystem::exists(path, error); + if (state.exists) { + state.size = std::filesystem::file_size(path, error); + state.time = std::filesystem::last_write_time(path, error); } - stores.emplace(path, result); - return result; + std::scoped_lock lock{mutex}; + if (auto const found{stores.find(path)}; + found != stores.end() && found->second.exists == state.exists && found->second.size == state.size && found->second.time == state.time) + return found->second.store; + if (state.exists) { + auto store{std::make_shared()}; + if (std::string reason; store->open(path, reason)) + state.store = std::move(store); + else // once for the folder: its models which refer to the store then can't be read + ErrorLog("Bad model: the geometry store \"" + path.string() + "\" can't be used: " + reason, logtype::model); + } + stores.insert_or_assign(path, state); + return state.store; } } // namespace eu07m diff --git a/model/eu07m/eu07m_store.h b/model/eu07m/eu07m_store.h index f346a3c71..b094d090a 100644 --- a/model/eu07m/eu07m_store.h +++ b/model/eu07m/eu07m_store.h @@ -57,8 +57,9 @@ block_id block_hash(std::span Block); // gives the block of a reference; false when there's none using block_source = std::function &Block)>; // the blocks of the references of the model put back in the places of their primitives in the streams, which the file has without -// them. false with the reason when a block is missing or doesn't fit -bool insert_blocks(model &Model, block_source const &Source, std::string &Error); +// them. false with the reason when a block is missing or doesn't fit. Verify: the bytes of each block hashed again against the +// reference (the tools); the game finds the block by the hash and checks its counts only +bool insert_blocks(model &Model, block_source const &Source, std::string &Error, bool Verify = true); // the streams of the model without the ranges of the primitives it refers to, as the file keeps them model remove_referenced(model const &Model); diff --git a/tests/unit/test_gref.cpp b/tests/unit/test_gref.cpp index 8020eb640..f70fc3150 100644 --- a/tests/unit/test_gref.cpp +++ b/tests/unit/test_gref.cpp @@ -152,6 +152,7 @@ TEST_CASE("gref: a block which isn't the one referred to is refused") { REQUIRE(store.open(eu07m::write_store({block}), error)); eu07m::model read; eu07m::read_options options; + options.verify_hash = true; // the game finds a block by its hash and checks its counts, the tools hash its bytes again options.blocks = [&store, &block](eu07m::geometry_reference_record const &, std::vector &Out) { return store.block(eu07m::block_hash(block), Out); }; CHECK_FALSE(eu07m::read(file, read, options).ok); } From 7ab60800962c456d6407a55a70c847a9f390fe72 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:24:20 +0100 Subject: [PATCH 3/3] docs(eu07m): the store as the game reads it now, the id of a block hashed again only with verify_hash, the store opened again when its file changes; the id to settle before packing --- docs/eu07m-format.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index 8841f325f..82bea787c 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -201,11 +201,18 @@ of the game, the folders of a family are 7% to 38% of their size with their shar packed with zstd when it saves an eighth, and the index: entries of 40 B (`u64 × 2` id, `u64` offset, `u32` size in the file, `u32` size unpacked, `u32` flags (0x1 zstd), `u32` 0), sorted by the id. - **In a model file,** `GREF` names the primitives kept in the store. The writer leaves their vertex and index ranges out of the - streams of the file; the reader takes their blocks from the store, checks the id and the counts of each, and puts them back in - their places, so the model in memory always has its whole streams and nothing past the reader knows the difference. A model - with references and no store, or a block which isn't the one referred to, is refused with the reason in the log. `GREF` is a + streams of the file; the reader takes their blocks from the store by their ids, checks the counts of each, and puts them back + in their places, so the model in memory always has its whole streams and nothing past the reader knows the difference. The + bytes of a block are hashed again and compared with its id only when the content of the file is checked too (`verify_hash`, + the tools); the game goes by the id and the counts. A model with references and no store, or a block which isn't the one + referred to, is refused with the reason in the log. `GREF` is a required section, so a reader which doesn't know it refuses the file rather than reading short streams. -- **The game** opens the store of a folder once and keeps it, reading the blocks from it as the models ask for them. +- **The game** keeps the store of a folder open, with the size and the time of its file, and reads the blocks from it as the + models ask for them; a store whose file changed (packed again while the game runs) is opened again. A store which can't be + opened is logged once per folder, with the reason. +- **Settled before the data is packed:** the id of a block (two FNV-1a 64) is part of the format. A change of it is a new major + version and a repack of every store, so it is to be decided before the stores go into the SVN; the order of the blocks in a + store (now by id) and reading a model's blocks at once are free to change, as the index finds a block wherever it lies. - **The tools.** `eu07 -eu07m pack [minimum bytes]` moves every block of at least the minimum (4096 by default) which occurs more than once in the models of the folder into its store, made anew from all of them, and writes the models again referring to it; each model is read back and compared with what it was before it's replaced. `eu07 -eu07m unpack `