18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-03 12:25:27 +01:00
Files
maszyna/world/worldcache.cpp
maj00r 30f3d70da9 feat(world): the logic cache of a scenery, recorded on the first load and replayed while current (world.binary)
Step 2d of docs/world-format-eu07.md (#516). With world.binary 1 in eu07.ini (off by default; then nothing is
written and nothing changes) the loader looks for <scenery>.logic.eu07 in the folder of the sceneries:

- current: made by this build (GIT_HASH and SRC_DATE), from the files the tape names as they are now (names,
  sizes, times of the last change) and with the same load settings (traction loaded, the binary terrain file
  standing in for the terrain includes, the text put ahead of the scenery, the trainset overrides): the
  scenery is replayed from the tape through the same parsers, with no file opened and no include expanded;
- not there or not current: the scenery is read from its files as before, the parser records its tape, and
  the cache is written once the scenery is loaded, through a temporary file. The log says which of the two.

Never in the editor, which keeps track of the files of the nodes, nor for a Rainsted override ($.scn).

The cache file gains package blocks, data of the whole package rather than of a tile; the tape goes into them
in parts of at most 64 MB until the logic is split into regions (step 3). The SBT check moved ahead of the
parser, unchanged, as the cache depends on it.

Not checked yet in the game: that a run from the replayed scenery gives the same physicslog bit for bit.
Tests: the cache file name, FNV-1a, package blocks written and read back, and the logic cache read back while
current and refused for another build, other settings or a changed included file.
2026-12-02 22:20:40 +01:00

536 lines
20 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 "world/worldcache.h"
#include <algorithm>
#include <array>
#include <format>
#include <istream>
#include <limits>
#include <ostream>
#include <tuple>
#include "scene/sn_utils.h"
#include "zstd.h"
namespace world_cache {
namespace {
// the sections of the file
enum class section_id : std::uint32_t {
names = 1,
directory = 2,
blocks = 3,
package = 4,
};
// the fixed part of the header, before the count of sections: magic, type, versions, flags, the body (17), package, layer, tile
// level, LOD count and the two hashes
constexpr std::size_t header_size{4 + 4 + 2 + 2 + 4 + 17 + 4 + 1 + 1 + 1 + 8 + 8};
// a section: its id, offset and size
constexpr std::size_t section_entry_size{4 + 8 + 8};
constexpr std::uint32_t section_limit{64};
// a chunk: its tag, flags and size, then its data padded to 4 bytes
constexpr std::size_t chunk_header_size{4 + 4 + 4};
// a package entry: its tag, offset, the stored and the raw size, and the CRC
constexpr std::size_t package_entry_size{4 + 8 + 4 + 4 + 4};
constexpr std::array<std::uint32_t, 256> crc_table() {
std::array<std::uint32_t, 256> table{};
for (std::uint32_t n = 0; n < 256; ++n) {
auto value{n};
for (int bit = 0; bit < 8; ++bit)
value = (value & 1u) != 0 ? 0xEDB8'8320u ^ (value >> 1) : value >> 1;
table[n] = value;
}
return table;
}
constexpr auto crc_lookup{crc_table()};
void put_bytes(std::ostream &Output, std::vector<std::byte> const &Bytes) {
Output.write(reinterpret_cast<char const *>(Bytes.data()), static_cast<std::streamsize>(Bytes.size()));
}
void put_zeros(std::ostream &Output, std::size_t Count) {
constexpr std::array<char, 256> zeros{};
while (Count > 0) {
auto const step{std::min(Count, zeros.size())};
Output.write(zeros.data(), static_cast<std::streamsize>(step));
Count -= step;
}
}
std::uint64_t aligned(std::uint64_t const Offset) {
return (Offset + block_alignment - 1) / block_alignment * block_alignment;
}
// the chunks of a block one after another, as the block unpacks to
std::vector<std::byte> raw_block(std::vector<chunk> const &Chunks) {
std::vector<std::byte> raw;
auto const put32{[&raw](std::uint32_t const Value) {
for (int shift = 0; shift < 32; shift += 8)
raw.push_back(static_cast<std::byte>((Value >> shift) & 0xFFu));
}};
for (auto const &piece : Chunks) {
put32(piece.tag);
put32(piece.flags);
put32(static_cast<std::uint32_t>(piece.data.size()));
raw.insert(raw.end(), piece.data.begin(), piece.data.end());
while (raw.size() % 4 != 0)
raw.push_back(std::byte{0});
}
return raw;
}
// the block packed with zstd, a frame per 64 KB, the frames one after another as zstd reads them
bool pack(std::vector<std::byte> const &Raw, std::vector<std::byte> &Packed) {
Packed.clear();
std::vector<std::byte> frame;
for (std::size_t start = 0; start < Raw.size(); start += frame_size) {
auto const length{std::min(frame_size, Raw.size() - start)};
frame.resize(ZSTD_compressBound(length));
auto const size{ZSTD_compress(frame.data(), frame.size(), Raw.data() + start, length, compression_level)};
if (ZSTD_isError(size))
return false;
Packed.insert(Packed.end(), frame.begin(), frame.begin() + static_cast<std::ptrdiff_t>(size));
}
return true;
}
struct stored_block {
directory_entry entry;
std::vector<std::byte> bytes;
};
struct stored_package_block {
package_entry entry;
std::vector<std::byte> bytes;
};
// the package blocks checked and packed, in the order given
std::string store_package(file_contents const &Contents, std::vector<stored_package_block> &Blocks) {
for (auto const &block : Contents.package) {
if (block.data.size() > block_size_limit)
return "a package block over the size limit";
stored_package_block stored;
stored.entry.tag = block.tag;
if (!pack(block.data, stored.bytes))
return "a package block couldn't be packed";
stored.entry.raw_size = static_cast<std::uint32_t>(block.data.size());
stored.entry.stored_size = static_cast<std::uint32_t>(stored.bytes.size());
stored.entry.crc = crc32(stored.bytes.data(), stored.bytes.size());
Blocks.push_back(std::move(stored));
}
return {};
}
// unpacks stored bytes checked by their CRC
std::string unpack(std::vector<std::byte> const &Stored, std::uint32_t const Crc, std::vector<std::byte> &Raw) {
if (crc32(Stored.data(), Stored.size()) != Crc)
return "the CRC of a block doesn't match";
if (!Raw.empty()) {
auto const size{ZSTD_decompress(Raw.data(), Raw.size(), Stored.data(), Stored.size())};
if (ZSTD_isError(size) || size != Raw.size())
return "a block doesn't unpack to its size";
}
return {};
}
// the tiles checked, packed and sorted by tile and level of detail
std::string store_blocks(file_contents const &Contents, std::vector<stored_block> &Blocks) {
for (auto const &tile : Contents.tiles) {
if (!tile.tile.valid())
return "a tile of the cache isn't a valid tile";
if (tile.lod >= Contents.header.lod_count)
return std::format("a level of detail {} beyond the count of {}", tile.lod, Contents.header.lod_count);
stored_block block;
block.entry.tile = tile.tile;
block.entry.lod = tile.lod;
block.entry.flags = tile.flags;
block.entry.y_min = tile.y_min;
block.entry.y_max = tile.y_max;
auto const empty{(tile.flags & entry_flags::empty) != 0};
if (empty && !tile.chunks.empty())
return "a tile marked empty has chunks";
if (!empty) {
auto const raw{raw_block(tile.chunks)};
if (raw.size() > block_size_limit)
return "a tile block over the size limit";
if (!pack(raw, block.bytes))
return "a tile block couldn't be packed";
block.entry.raw_size = static_cast<std::uint32_t>(raw.size());
block.entry.stored_size = static_cast<std::uint32_t>(block.bytes.size());
block.entry.crc = crc32(block.bytes.data(), block.bytes.size());
}
Blocks.push_back(std::move(block));
}
auto const key{[](stored_block const &Block) { return std::tuple{Block.entry.tile.raw(), Block.entry.lod}; }};
std::ranges::sort(Blocks, {}, key);
auto const repeated{std::ranges::adjacent_find(Blocks, {}, key)};
if (repeated != Blocks.end())
return "a tile repeated in the same level of detail";
return {};
}
void write_header(std::ostream &Output, file_header const &Header) {
sn_utils::ls_uint32(Output, file_magic);
sn_utils::ls_uint32(Output, file_type);
sn_utils::ls_uint16(Output, Header.major);
sn_utils::ls_uint16(Output, Header.minor);
sn_utils::ls_uint32(Output, Header.flags);
world_geometry::write(Output, Header.body);
sn_utils::ls_uint32(Output, Header.package);
sn_utils::s_uint8(Output, static_cast<std::uint8_t>(Header.layer));
sn_utils::s_uint8(Output, Header.tile_level);
sn_utils::s_uint8(Output, Header.lod_count);
sn_utils::ls_uint64(Output, Header.engine_hash);
sn_utils::ls_uint64(Output, Header.source_hash);
}
void write_entry(std::ostream &Output, directory_entry const &Entry) {
sn_utils::ls_uint64(Output, Entry.tile.raw());
sn_utils::s_uint8(Output, Entry.lod);
sn_utils::s_uint8(Output, Entry.flags);
sn_utils::ls_uint64(Output, Entry.offset);
sn_utils::ls_uint32(Output, Entry.stored_size);
sn_utils::ls_uint32(Output, Entry.raw_size);
sn_utils::ls_float32(Output, Entry.y_min);
sn_utils::ls_float32(Output, Entry.y_max);
sn_utils::ls_uint32(Output, Entry.crc);
sn_utils::ls_uint16(Output, 0);
}
directory_entry read_entry(std::istream &Input) {
directory_entry entry;
entry.tile = world_geometry::tile_id::from_raw(sn_utils::ld_uint64(Input));
entry.lod = sn_utils::d_uint8(Input);
entry.flags = sn_utils::d_uint8(Input);
entry.offset = sn_utils::ld_uint64(Input);
entry.stored_size = sn_utils::ld_uint32(Input);
entry.raw_size = sn_utils::ld_uint32(Input);
entry.y_min = sn_utils::ld_float32(Input);
entry.y_max = sn_utils::ld_float32(Input);
entry.crc = sn_utils::ld_uint32(Input);
sn_utils::ld_uint16(Input);
return entry;
}
std::uint32_t read_u32_le(std::byte const *Data) {
return static_cast<std::uint32_t>(Data[0]) | static_cast<std::uint32_t>(Data[1]) << 8 | static_cast<std::uint32_t>(Data[2]) << 16 |
static_cast<std::uint32_t>(Data[3]) << 24;
}
// the chunks of an unpacked block
std::string split_chunks(std::vector<std::byte> const &Raw, std::vector<chunk> &Chunks) {
std::size_t position{0};
while (position < Raw.size()) {
if (Raw.size() - position < chunk_header_size)
return "a chunk cut short";
chunk piece;
piece.tag = read_u32_le(Raw.data() + position);
piece.flags = read_u32_le(Raw.data() + position + 4);
auto const size{read_u32_le(Raw.data() + position + 8)};
position += chunk_header_size;
if (size > Raw.size() - position)
return "a chunk longer than its block";
piece.data.assign(Raw.begin() + static_cast<std::ptrdiff_t>(position), Raw.begin() + static_cast<std::ptrdiff_t>(position + size));
position += (static_cast<std::size_t>(size) + 3) / 4 * 4;
Chunks.push_back(std::move(piece));
}
return {};
}
} // namespace
std::uint32_t crc32(std::byte const *Data, std::size_t const Size) {
std::uint32_t crc{0xFFFF'FFFFu};
for (std::size_t k = 0; k < Size; ++k)
crc = crc_lookup[(crc ^ static_cast<std::uint32_t>(Data[k])) & 0xFFu] ^ (crc >> 8);
return crc ^ 0xFFFF'FFFFu;
}
std::string write(std::ostream &Output, file_contents const &Contents) {
std::vector<stored_block> blocks;
if (auto const error{store_blocks(Contents, blocks)}; !error.empty())
return error;
std::vector<stored_package_block> package;
if (auto const error{store_package(Contents, package)}; !error.empty())
return error;
// the layout: the header, the sections, the names, the directory, the table of package blocks, then the blocks from the first
// multiple of 4 KB, the tiles' first
constexpr std::uint32_t section_count{4};
std::uint64_t names_size{4};
for (auto const &name : Contents.names)
names_size += 4 + name.size();
auto const names_offset{static_cast<std::uint64_t>(header_size + 4 + section_count * section_entry_size)};
auto const directory_offset{names_offset + names_size};
auto const directory_size{4 + blocks.size() * directory_entry_size};
auto const package_offset{directory_offset + directory_size};
auto const package_size{4 + package.size() * package_entry_size};
auto const blocks_offset{aligned(package_offset + package_size)};
auto offset{blocks_offset};
for (auto &block : blocks) {
if (block.bytes.empty())
continue;
block.entry.offset = offset;
offset = aligned(offset + block.bytes.size());
}
for (auto &block : package) {
block.entry.offset = offset;
offset = aligned(offset + block.bytes.size());
}
write_header(Output, Contents.header);
sn_utils::ls_uint32(Output, section_count);
auto const section{[&Output](section_id const Id, std::uint64_t const Offset, std::uint64_t const Size) {
sn_utils::ls_uint32(Output, static_cast<std::uint32_t>(Id));
sn_utils::ls_uint64(Output, Offset);
sn_utils::ls_uint64(Output, Size);
}};
section(section_id::names, names_offset, names_size);
section(section_id::directory, directory_offset, directory_size);
section(section_id::package, package_offset, package_size);
section(section_id::blocks, blocks_offset, offset - blocks_offset);
sn_utils::ls_uint32(Output, static_cast<std::uint32_t>(Contents.names.size()));
for (auto const &name : Contents.names) {
sn_utils::ls_uint32(Output, static_cast<std::uint32_t>(name.size()));
Output.write(name.data(), static_cast<std::streamsize>(name.size()));
}
sn_utils::ls_uint32(Output, static_cast<std::uint32_t>(blocks.size()));
for (auto const &block : blocks)
write_entry(Output, block.entry);
sn_utils::ls_uint32(Output, static_cast<std::uint32_t>(package.size()));
for (auto const &block : package) {
sn_utils::ls_uint32(Output, block.entry.tag);
sn_utils::ls_uint64(Output, block.entry.offset);
sn_utils::ls_uint32(Output, block.entry.stored_size);
sn_utils::ls_uint32(Output, block.entry.raw_size);
sn_utils::ls_uint32(Output, block.entry.crc);
}
auto written{package_offset + package_size};
auto const put_block{[&Output, &written](std::uint64_t const Offset, std::vector<std::byte> const &Bytes) {
put_zeros(Output, Offset - written);
put_bytes(Output, Bytes);
written = Offset + Bytes.size();
}};
for (auto const &block : blocks) {
if (!block.bytes.empty())
put_block(block.entry.offset, block.bytes);
}
for (auto const &block : package)
put_block(block.entry.offset, block.bytes);
put_zeros(Output, offset - written);
if (!Output)
return "the cache file couldn't be written";
return {};
}
namespace {
struct reader_limits {
std::uint8_t lod_count{1};
std::uint64_t file_size{0};
};
std::string read_header(std::istream &Input, file_header &Header) {
auto const magic{sn_utils::ld_uint32(Input)};
auto const type{sn_utils::ld_uint32(Input)};
if (!Input || magic != file_magic || type != file_type)
return "not a cache file of the world format";
Header.major = sn_utils::ld_uint16(Input);
Header.minor = sn_utils::ld_uint16(Input);
if (!Input || Header.major != version_major)
return std::format("a cache file of version {}, this game reads version {}", Header.major, version_major);
Header.flags = sn_utils::ld_uint32(Input);
if (!world_geometry::read(Input, Header.body))
return "the body of the cache file isn't valid";
Header.package = sn_utils::ld_uint32(Input);
auto const layer{sn_utils::d_uint8(Input)};
Header.tile_level = sn_utils::d_uint8(Input);
Header.lod_count = sn_utils::d_uint8(Input);
Header.engine_hash = sn_utils::ld_uint64(Input);
Header.source_hash = sn_utils::ld_uint64(Input);
if (!Input)
return "the header of the cache file is cut short";
if (layer > static_cast<std::uint8_t>(layer_kind::logic))
return std::format("an unknown layer {}", layer);
if (Header.tile_level > world_geometry::max_tile_level || Header.lod_count == 0)
return "the tile level or the count of levels of detail isn't valid";
Header.layer = static_cast<layer_kind>(layer);
return {};
}
struct section_entry {
std::uint64_t offset{0};
std::uint64_t size{0};
bool present{false};
};
struct sections {
section_entry names;
section_entry directory;
section_entry package;
};
std::string read_sections(std::istream &Input, std::uint64_t const Filesize, sections &Sections) {
auto const count{sn_utils::ld_uint32(Input)};
if (!Input || count > section_limit)
return "the table of sections isn't valid";
for (std::uint32_t k = 0; k < count; ++k) {
auto const id{sn_utils::ld_uint32(Input)};
section_entry entry;
entry.offset = sn_utils::ld_uint64(Input);
entry.size = sn_utils::ld_uint64(Input);
entry.present = true;
if (!Input || entry.offset > Filesize || entry.size > Filesize - entry.offset)
return "a section lies beyond the end of the cache file";
// a section of a newer minor version is skipped
if (id == static_cast<std::uint32_t>(section_id::names))
Sections.names = entry;
else if (id == static_cast<std::uint32_t>(section_id::directory))
Sections.directory = entry;
else if (id == static_cast<std::uint32_t>(section_id::package))
Sections.package = entry;
}
if (!Sections.names.present || !Sections.directory.present)
return "the cache file has no name table or no directory";
return {};
}
std::string read_names(std::istream &Input, section_entry const &Section, std::vector<std::string> &Names) {
Input.seekg(static_cast<std::streamoff>(Section.offset));
auto const count{sn_utils::ld_uint32(Input)};
if (!Input || count > Section.size / 4)
return "the name table isn't valid";
std::uint64_t used{4};
for (std::uint32_t k = 0; k < count; ++k) {
auto const length{sn_utils::ld_uint32(Input)};
used += 4;
if (!Input || used > Section.size || length > Section.size - used)
return "a name runs beyond the name table";
std::string name(length, '\0');
Input.read(name.data(), static_cast<std::streamsize>(length));
used += length;
Names.push_back(std::move(name));
}
return {};
}
// whether the entry stays within the file: an empty one stores nothing
bool entry_in_file(directory_entry const &Entry, std::uint64_t const Filesize) {
if ((Entry.flags & entry_flags::empty) != 0)
return Entry.stored_size == 0 && Entry.raw_size == 0;
return Entry.offset <= Filesize && Entry.stored_size <= Filesize - Entry.offset && Entry.raw_size <= block_size_limit;
}
std::string read_directory(std::istream &Input, section_entry const &Section, reader_limits const &Limits, std::vector<directory_entry> &Directory) {
Input.seekg(static_cast<std::streamoff>(Section.offset));
auto const count{sn_utils::ld_uint32(Input)};
if (!Input || Section.size < 4 || count > (Section.size - 4) / directory_entry_size)
return "the directory isn't valid";
Directory.reserve(count);
for (std::uint32_t k = 0; k < count; ++k) {
auto const entry{read_entry(Input)};
if (!Input || !entry.tile.valid() || entry.lod >= Limits.lod_count)
return "an entry of the directory isn't valid";
if (!entry_in_file(entry, Limits.file_size))
return "an entry of the directory points beyond the file";
if (!Directory.empty() && std::tuple{Directory.back().tile.raw(), Directory.back().lod} >= std::tuple{entry.tile.raw(), entry.lod})
return "the directory isn't sorted";
Directory.push_back(entry);
}
return {};
}
// the table of package blocks; a file without one has none
std::string read_package(std::istream &Input, section_entry const &Section, std::uint64_t const Filesize, std::vector<package_entry> &Package) {
if (!Section.present)
return {};
Input.seekg(static_cast<std::streamoff>(Section.offset));
auto const count{sn_utils::ld_uint32(Input)};
if (!Input || Section.size < 4 || count > (Section.size - 4) / package_entry_size)
return "the table of package blocks isn't valid";
for (std::uint32_t k = 0; k < count; ++k) {
package_entry entry;
entry.tag = sn_utils::ld_uint32(Input);
entry.offset = sn_utils::ld_uint64(Input);
entry.stored_size = sn_utils::ld_uint32(Input);
entry.raw_size = sn_utils::ld_uint32(Input);
entry.crc = sn_utils::ld_uint32(Input);
if (!Input || entry.offset > Filesize || entry.stored_size > Filesize - entry.offset || entry.raw_size > block_size_limit)
return "a package block points beyond the file";
Package.push_back(entry);
}
return {};
}
} // namespace
std::string reader::open(std::istream &Input) {
m_names.clear();
m_directory.clear();
m_package.clear();
Input.seekg(0, std::ios::end);
auto const end{Input.tellg()};
Input.seekg(0, std::ios::beg);
if (!Input || end < 0)
return "the cache file can't be read";
m_size = static_cast<std::uint64_t>(end);
if (auto const error{read_header(Input, m_header)}; !error.empty())
return error;
sections found;
if (auto const error{read_sections(Input, m_size, found)}; !error.empty())
return error;
if (auto const error{read_names(Input, found.names, m_names)}; !error.empty())
return error;
if (auto const error{read_directory(Input, found.directory, {m_header.lod_count, m_size}, m_directory)}; !error.empty())
return error;
return read_package(Input, found.package, m_size, m_package);
}
std::optional<directory_entry> reader::find(world_geometry::tile_id const Tile, std::uint8_t const Lod) const {
auto const key{std::tuple{Tile.raw(), Lod}};
auto const found{std::ranges::lower_bound(m_directory, key, {}, [](directory_entry const &Entry) { return std::tuple{Entry.tile.raw(), Entry.lod}; })};
if (found == m_directory.end() || found->tile != Tile || found->lod != Lod)
return std::nullopt;
return *found;
}
std::string reader::read_block(std::istream &Input, directory_entry const &Entry, std::vector<chunk> &Chunks) const {
Chunks.clear();
if ((Entry.flags & entry_flags::empty) != 0)
return {};
std::vector<std::byte> stored(Entry.stored_size);
Input.clear();
Input.seekg(static_cast<std::streamoff>(Entry.offset));
Input.read(reinterpret_cast<char *>(stored.data()), static_cast<std::streamsize>(stored.size()));
if (!Input)
return "a tile block couldn't be read";
std::vector<std::byte> raw(Entry.raw_size);
if (auto const error{unpack(stored, Entry.crc, raw)}; !error.empty())
return error;
return split_chunks(raw, Chunks);
}
std::string reader::read_package_block(std::istream &Input, package_entry const &Entry, std::vector<std::byte> &Data) const {
std::vector<std::byte> stored(Entry.stored_size);
Input.clear();
Input.seekg(static_cast<std::streamoff>(Entry.offset));
Input.read(reinterpret_cast<char *>(stored.data()), static_cast<std::streamsize>(stored.size()));
if (!Input)
return "a package block couldn't be read";
Data.assign(Entry.raw_size, std::byte{0});
return unpack(stored, Entry.crc, Data);
}
} // namespace world_cache