/* 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 #include #include #include #include #include #include #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 crc_table() { std::array 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 const &Bytes) { Output.write(reinterpret_cast(Bytes.data()), static_cast(Bytes.size())); } void put_zeros(std::ostream &Output, std::size_t Count) { constexpr std::array zeros{}; while (Count > 0) { auto const step{std::min(Count, zeros.size())}; Output.write(zeros.data(), static_cast(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 raw_block(std::vector const &Chunks) { std::vector raw; auto const put32{[&raw](std::uint32_t const Value) { for (int shift = 0; shift < 32; shift += 8) raw.push_back(static_cast((Value >> shift) & 0xFFu)); }}; for (auto const &piece : Chunks) { put32(piece.tag); put32(piece.flags); put32(static_cast(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 const &Raw, std::vector &Packed) { Packed.clear(); std::vector 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(size)); } return true; } struct stored_block { directory_entry entry; std::vector bytes; }; struct stored_package_block { package_entry entry; std::vector bytes; }; // the package blocks checked and packed, in the order given std::string store_package(file_contents const &Contents, std::vector &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(block.data.size()); stored.entry.stored_size = static_cast(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 const &Stored, std::uint32_t const Crc, std::vector &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 &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(raw.size()); block.entry.stored_size = static_cast(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(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(Data[0]) | static_cast(Data[1]) << 8 | static_cast(Data[2]) << 16 | static_cast(Data[3]) << 24; } // the chunks of an unpacked block std::string split_chunks(std::vector const &Raw, std::vector &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(position), Raw.begin() + static_cast(position + size)); position += (static_cast(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(Data[k])) & 0xFFu] ^ (crc >> 8); return crc ^ 0xFFFF'FFFFu; } std::string write(std::ostream &Output, file_contents const &Contents) { std::vector blocks; if (auto const error{store_blocks(Contents, blocks)}; !error.empty()) return error; std::vector 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(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(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(Contents.names.size())); for (auto const &name : Contents.names) { sn_utils::ls_uint32(Output, static_cast(name.size())); Output.write(name.data(), static_cast(name.size())); } sn_utils::ls_uint32(Output, static_cast(blocks.size())); for (auto const &block : blocks) write_entry(Output, block.entry); sn_utils::ls_uint32(Output, static_cast(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 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(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); 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(section_id::names)) Sections.names = entry; else if (id == static_cast(section_id::directory)) Sections.directory = entry; else if (id == static_cast(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 &Names) { Input.seekg(static_cast(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(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) { Input.seekg(static_cast(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) { if (!Section.present) return {}; Input.seekg(static_cast(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(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 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 &Chunks) const { Chunks.clear(); if ((Entry.flags & entry_flags::empty) != 0) return {}; std::vector stored(Entry.stored_size); Input.clear(); Input.seekg(static_cast(Entry.offset)); Input.read(reinterpret_cast(stored.data()), static_cast(stored.size())); if (!Input) return "a tile block couldn't be read"; std::vector 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 &Data) const { std::vector stored(Entry.stored_size); Input.clear(); Input.seekg(static_cast(Entry.offset)); Input.read(reinterpret_cast(stored.data()), static_cast(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