18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-02 07:22:42 +01:00
Files
maszyna/model/eu07m/eu07m_pack.cpp
T
maj00r d930b6519d 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 <folder> [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 <folder>" 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.
2026-11-29 04:03:49 +01:00

231 lines
8.9 KiB
C++

/*
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 <algorithm>
#include <cctype>
#include <format>
#include <fstream>
#include <map>
#include <string>
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<std::byte> bytes;
std::size_t uses{0};
bool collision{false}; // another block has the same hash
};
std::vector<std::byte> read_file(std::filesystem::path const &Path) {
std::ifstream file{Path, std::ios::binary | std::ios::ate};
if (false == file.good())
return {};
std::vector<std::byte> data(static_cast<std::size_t>(file.tellg()));
file.seekg(0);
file.read(reinterpret_cast<char *>(data.data()), static_cast<std::streamsize>(data.size()));
return file.good() ? data : std::vector<std::byte>{};
}
bool write_file(std::filesystem::path const &Path, std::span<std::byte const> 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<char const *>(Data.data()), static_cast<std::streamsize>(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<char>(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<folder_model> &Models, std::uintmax_t &Bytes, std::ostream &Log) {
auto const storepath{Folder / store_file_name};
auto store{std::make_shared<geometry_store>()};
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<block_id, candidate> gather(std::vector<folder_model> const &Models, std::size_t const MinBytes) {
std::map<block_id, candidate> 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<geometry_reference_record> references(model const &Model, std::map<block_id, candidate> const &Shared, std::size_t const MinBytes) {
std::vector<geometry_reference_record> 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<std::byte> &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<folder_model> 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<std::vector<std::byte>> 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<folder_model> 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