From bbf9c4d0a8bab1cfa74c47060ef4ae555585f049 Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Sun, 22 Nov 2026 15:07:24 +0100 Subject: [PATCH] feat: VXLS sparse_tree file type --- crates/vxls-production/Cargo.toml | 2 + crates/vxls-production/src/io.rs | 211 +++++++ crates/vxls-production/src/io/chunk.rs | 195 +++++++ crates/vxls-production/src/io/error.rs | 449 ++++++++++++++ crates/vxls-production/src/io/format.rs | 353 +++++++++++ crates/vxls-production/src/io/read.rs | 636 ++++++++++++++++++++ crates/vxls-production/src/io/write.rs | 679 ++++++++++++++++++++++ crates/vxls-production/src/lib.rs | 2 + crates/vxls-production/src/main.rs | 31 + crates/vxls-production/src/sparse_tree.rs | 94 +++ crates/vxls-production/tests/io.rs | 675 +++++++++++++++++++++ 11 files changed, 3327 insertions(+) create mode 100644 crates/vxls-production/src/io.rs create mode 100644 crates/vxls-production/src/io/chunk.rs create mode 100644 crates/vxls-production/src/io/error.rs create mode 100644 crates/vxls-production/src/io/format.rs create mode 100644 crates/vxls-production/src/io/read.rs create mode 100644 crates/vxls-production/src/io/write.rs create mode 100644 crates/vxls-production/src/main.rs create mode 100644 crates/vxls-production/tests/io.rs diff --git a/crates/vxls-production/Cargo.toml b/crates/vxls-production/Cargo.toml index e5a5d92..b26650e 100644 --- a/crates/vxls-production/Cargo.toml +++ b/crates/vxls-production/Cargo.toml @@ -10,3 +10,5 @@ rayon.workspace = true wgpu.workspace = true vxls-attributes-derive = { path = "../vxls-attributes-derive" } vxls-voxel-cache = { path = "../vxls-voxel-cache" } +binrw = "0.15.2" +crc32fast = "1.5.1" diff --git a/crates/vxls-production/src/io.rs b/crates/vxls-production/src/io.rs new file mode 100644 index 0000000..c17dc06 --- /dev/null +++ b/crates/vxls-production/src/io.rs @@ -0,0 +1,211 @@ +//! +//! # VXLS sparse-tree file format +//! +//! Status: implemented by `io::read` and `io::write`; this module documents +//! the wire format they share. +//! +//! The layout mirrors `sparse_tree::NTree`: every node owns one attribute and +//! one `subdivided` flag. Subdividing a node creates all `N³` children at +//! once, so there is no per-child presence mask and no notion of a "missing" +//! child. A leaf's attribute applies to its whole subtree; an interior node's +//! attribute is the average of its children's, as `NTree` already maintains. +//! +//! The format records only tree structure, attribute word counts and labels. +//! What the words mean and how they map onto rendering is the loader's +//! business, not the file's. +//! +//! A file holds exactly one tree; there is no forest container. Compression is +//! deliberately out of scope for this version. The format is expected to +//! change, so when compression lands it can be a new chunk tag or a flag in an +//! offset-table entry rather than a compatibility problem. +//! +//! ## Conventions +//! +//! - Little-endian throughout, including raw attribute words. +//! - Structures are packed unless a `reserved` field is listed. Chunk bodies +//! are not padded internally; chunks are separated by zero padding so that +//! each chunk starts 8-byte aligned (see the chunk frame). +//! - Offsets are byte offsets from the start of the file. +//! - Sizes are in bytes unless the field name says otherwise. +//! - Strings are UTF-8: a `u32` byte count followed by that many bytes, no +//! terminator, no padding. +//! +//! ## Preamble (24 bytes) +//! +//! ```text +//! offset size field +//! 0 4 magic b"VXLS" +//! 4 4 file_type b"ST\0\0" (sparse tree) +//! 8 4 major_version incompatible changes +//! 12 4 minor_version compatible additions +//! 16 8 total_file_size exact on-disk length +//! ``` +//! +//! 24 bytes keeps the `u64` and everything after it naturally aligned. +//! +//! ## Header (at offset 24) +//! +//! ```text +//! u32 header_size size of the header in bytes, including this field (>= 12) +//! u32 tree_arity N, at least 2 +//! u32 tree_depth maximum depth, 0 = a single root node +//! ``` +//! +//! `tree_depth` is the capacity: nodes live at levels `0 ..= tree_depth`, and +//! `N^tree_depth` voxels span one axis. The tree may stop shallower than that +//! (see level chunks). +//! +//! Readers must skip `header_size - 12` unknown bytes instead of rejecting the +//! file; that is how later versions append fields. +//! +//! ## Offset table (at offset `24 + header_size`) +//! +//! ```text +//! u32 offset_table_size size of the entries in bytes, excluding this field; +//! must be a multiple of 24 +//! entry { // packed, 24 bytes each +//! u32 chunk_type_tag +//! u32 reserved // 0; future flags (e.g. compression) +//! u64 file_offset // always a multiple of 8 +//! u64 chunk_size // same value as the chunk frame's own size +//! } +//! ``` +//! +//! One entry per chunk, ordered by `file_offset`; chunks themselves may appear +//! in any order. The table is authoritative for seeking, and a reader checks +//! that the frame at `file_offset` still matches the entry. The first chunk +//! starts at the first 8-byte boundary at or after the end of this table, with +//! the same zero padding rule as between chunks. +//! +//! ## Chunk frame +//! +//! ```text +//! u32 chunk_type_tag +//! u64 chunk_size // 12 + body length; excludes the CRC word +//! [body: chunk_size - 12 bytes] +//! u32 chunk_crc32 // CRC-32/ISO-HDLC (zlib) over tag + size + body +//! ``` +//! +//! The CRC uses the reflected polynomial `0xEDB88320`, init `0xFFFFFFFF`, +//! final XOR `0xFFFFFFFF`. A mismatch is a hard error for required chunks. +//! +//! Chunk starts are 8-byte aligned: when a chunk's CRC ends at offset `e`, +//! the next chunk starts at `align_up(e, 8)`. The gap (0 to 7 bytes) is +//! zero-filled padding that belongs to no chunk, is not counted by any +//! `chunk_size` and is not covered by any CRC, so `chunk_size` remains exactly +//! `12 + body length`. There is no padding after the final chunk, and +//! `total_file_size` includes the inter-chunk padding. +//! +//! Only the chunk start is aligned: a body begins 12 bytes into an 8-byte +//! aligned chunk, so bodies are 4-byte aligned. That is enough to read `u32` +//! attribute words directly, but not `u64` values. +//! +//! ## Chunk tags +//! +//! | tag | meaning | +//! |------------------------|-------------------------------------------| +//! | `0x0000_0000` | invalid | +//! | `0x0000_0001` | attributes (required, exactly one) | +//! | `0x8000_0000 \| level` | nodes at `level`, 0 = root | +//! +//! Tags with the high bit clear are non-tree chunks; unknown ones are skipped. +//! +//! ## Attributes chunk (tag 1) +//! +//! Describes the payload in cache binding order: attribute 0 is the first +//! binding the shaders read, and that order is load-bearing. +//! +//! ```text +//! u32 attribute_count +//! attribute_count × { +//! u32 word_count // 32-bit words per voxel +//! u32 label_size +//! u8 label[label_size] +//! } +//! ``` +//! +//! Payload stride is `Σ word_count` words. The words are opaque: `word_count` +//! says how many, not what they mean, so a `u32` colour and an `[f32; 3]` +//! normal look identical. `label` is a human-readable hint; the format does +//! not interpret it. `word_count` must be at least 1, and `label` must be +//! valid UTF-8 (it may be empty). A single-attribute tree has +//! `attribute_count == 1`. +//! +//! ## Level chunks (tag `0x8000_0000 | level`) +//! +//! Structure-of-arrays, one chunk per level. Nodes are stored breadth-first: +//! the `N³` children of subdivided node `k` at level `L` (where `k` counts +//! only subdivided nodes, in order) are nodes `N³·k .. N³·(k+1)` at level +//! `L + 1`, in child order `c = x + N*y + N²*z` (x fastest, then y, then z) — +//! the order `TreeLocator::children` produces. +//! +//! ```text +//! u32 node_count +//! u32 subdivided[(node_count + 31) / 32] // 1 bit per node, LSB first +//! attr_0[node_count * word_count_0] +//! attr_1[node_count * word_count_1] +//! ... +//! ``` +//! +//! - Bit `i` of `subdivided` is node `i`'s `subdivided` flag; unused trailing +//! bits are zero. +//! - `node_count` at level 0 is 1, and the chunk then holds exactly the root's +//! flag word followed by its attributes. +//! - `node_count` at level `L + 1` is `N³ × popcount(subdivided at level L)`. +//! - Attribute arrays hold one payload per node in attribute order, raw +//! little-endian words, no padding between arrays. +//! - Level chunks are a contiguous prefix `0 ..= D`: level `L + 1` exists iff +//! level `L` has at least one bit set. `D` may be shallower than +//! `tree_depth`, in which case every node at `D` is a leaf whose attribute +//! covers its subtree. Every bit at `D` must be zero, so `D == tree_depth` +//! is valid only when the tree bottoms out exactly at its capacity. +//! +//! A constant tree is `tree_depth == 0`: one level-0 chunk with `node_count == 1`, +//! a zero flag word and one payload. +//! +//! ## Validation +//! +//! Check magic and type; `total_file_size` equals the real length; +//! `header_size >= 12` and inside the file; `tree_arity >= 2`; +//! `tree_depth <= TreeLocator::::max_depth()`; `offset_table_size` is a +//! multiple of 24; every `file_offset` is a multiple of 8 and every offset and +//! size lies inside the file; the gaps between chunks are shorter than 8 bytes +//! and zero-filled; chunk tags are unique; level chunks are the contiguous +//! prefix `0 ..= D` with `D <= tree_depth` and every flag at `D` clear; +//! level-0 `node_count == 1`; each level's `node_count` equals `N³ × popcount` +//! of the previous level's flags; each level's `chunk_size` equals +//! `12 + 4 + mask_words*4 + node_count × Σ word_count × 4`, where +//! `mask_words = ceil(node_count / 32)`; CRCs of required chunks. Same major is +//! required, a newer minor is accepted by skipping unknown tags. +//! +//! `total_file_size` is the offset just past the final chunk's CRC, including +//! inter-chunk padding and with no trailing padding. +//! +//! ## Implementation notes +//! +//! - `binrw` derives cover the fixed-shape sections; the attributes and level +//! bodies use manual `BinRead`/`BinWrite` impls because they are +//! structure-of-arrays with counts taken from the stream. +//! - CRC-32 comes from the `crc32fast` crate. +//! +//! ## Implementation map +//! +//! | module | contents | +//! |---|---| +//! | `io::format` | wire structs, tags, constants | +//! | `io::chunk` | frame read/write, 8-byte padding, CRC | +//! | `io::write` | [`write_tree`], [`write_tree_to_path`] | +//! | `io::read` | [`read_tree`], [`read_tree_from_path`], [`TreeFile`] | +//! | `io::error` | [`TreeFileError`] | + +mod chunk; +mod error; +mod format; +mod read; +mod write; + +pub use error::TreeFileError; +pub use format::FileAttribute; +pub use read::{FileLayout, TreeFile, read_tree, read_tree_from_path}; +pub use write::{write_tree, write_tree_to_path}; + diff --git a/crates/vxls-production/src/io/chunk.rs b/crates/vxls-production/src/io/chunk.rs new file mode 100644 index 0000000..ee4ced1 --- /dev/null +++ b/crates/vxls-production/src/io/chunk.rs @@ -0,0 +1,195 @@ +//! Chunk framing: 8-byte alignment, tag/size headers and CRC-32. + +use std::io::{Read, Seek, Write}; + +use binrw::{BinRead, BinWrite, Endian}; + +use super::error::TreeFileError; +use super::format::CHUNK_FRAME_SIZE; +use super::format::ChunkFrame; + +/// Alignment of a chunk start. +pub const CHUNK_ALIGNMENT: u64 = 8; + +const ZEROES: [u8; 8] = [0; 8]; + +/// A chunk read from a file, with its CRC already verified. +#[derive(Clone, Debug)] +pub struct Chunk +{ + pub tag: u32, + pub size: u64, + pub body: Vec, +} + +/// Rounds `value` up to the next multiple of `align`, which must be a power of two. +pub const fn align_up(value: u64, align: u64) -> u64 +{ + (value + align - 1) & !(align - 1) +} + +/// Writes zero padding until the writer is 8-byte aligned. +pub fn write_padding_to_alignment( + writer: &mut W, +) -> Result<(), TreeFileError> +{ + let position = writer.stream_position()?; + let target = align_up(position, CHUNK_ALIGNMENT); + let padding = (target - position) as usize; + + if padding > 0 + { + writer.write_all(&ZEROES[..padding])?; + } + + Ok(()) +} + +/// Writes a complete chunk at the current position, which must already be aligned. +pub fn write_chunk( + writer: &mut W, + tag: u32, + body: &[u8], +) -> Result<(), TreeFileError> +{ + let position = writer.stream_position()?; + + if position % CHUNK_ALIGNMENT != 0 + { + return Err(TreeFileError::MisalignedOffset { offset: position }); + } + + let chunk_size = CHUNK_FRAME_SIZE + body.len() as u64; + + ChunkFrame { + chunk_type_tag: tag, + chunk_size, + } + .write_options(writer, Endian::Little, ())?; + + writer.write_all(body)?; + + let mut hasher = crc32fast::Hasher::new(); + hasher.update(&tag.to_le_bytes()); + hasher.update(&chunk_size.to_le_bytes()); + hasher.update(body); + + writer.write_all(&hasher.finalize().to_le_bytes())?; + + Ok(()) +} + +/// Reads a chunk at the current position, verifying its frame and CRC. +/// +/// The reader is left just past the chunk's CRC word, before any padding. +pub fn read_chunk( + reader: &mut R, + file_len: u64, +) -> Result +{ + let offset = reader.stream_position()?; + + if offset % CHUNK_ALIGNMENT != 0 + { + return Err(TreeFileError::MisalignedOffset { offset }); + } + + let frame = ChunkFrame::read_options(reader, Endian::Little, ())?; + + if frame.chunk_size < CHUNK_FRAME_SIZE + { + return Err(TreeFileError::ChunkSizeTooSmall { + tag: frame.chunk_type_tag, + size: frame.chunk_size, + }); + } + + let end = offset + .checked_add(frame.chunk_size) + .and_then(|value| value.checked_add(4)) + .ok_or(TreeFileError::Overflow { what: "chunk end" })?; + + if end > file_len + { + return Err(TreeFileError::ChunkOutOfBounds { + tag: frame.chunk_type_tag, + offset, + size: frame.chunk_size, + }); + } + + let body_len = usize::try_from(frame.chunk_size - CHUNK_FRAME_SIZE) + .map_err(|_| TreeFileError::Overflow { what: "chunk body length" })?; + + let mut body = vec![0u8; body_len]; + reader.read_exact(&mut body)?; + + let mut crc_bytes = [0u8; 4]; + reader.read_exact(&mut crc_bytes)?; + let found = u32::from_le_bytes(crc_bytes); + + let mut hasher = crc32fast::Hasher::new(); + hasher.update(&frame.chunk_type_tag.to_le_bytes()); + hasher.update(&frame.chunk_size.to_le_bytes()); + hasher.update(&body); + let expected = hasher.finalize(); + + if expected != found + { + return Err(TreeFileError::CrcMismatch { + tag: frame.chunk_type_tag, + offset, + expected, + found, + }); + } + + Ok(Chunk { + tag: frame.chunk_type_tag, + size: frame.chunk_size, + body, + }) +} + +/// Reads the gap between `position` and `target`, requiring every byte to be zero. +/// +/// The caller guarantees `position <= target < position + 8`. +pub fn read_padding( + reader: &mut R, + target: u64, +) -> Result<(), TreeFileError> +{ + let position = reader.stream_position()?; + + if target < position + { + return Err(TreeFileError::ChunkOffsetMismatch { + tag: 0, + expected: target, + found: position, + }); + } + + let length = target - position; + + if length >= CHUNK_ALIGNMENT + { + return Err(TreeFileError::MisalignedOffset { offset: target }); + } + + let mut buffer = [0u8; 8]; + reader.read_exact(&mut buffer[..length as usize])?; + + for (index, byte) in buffer[..length as usize].iter().enumerate() + { + if *byte != 0 + { + return Err(TreeFileError::NonZeroPadding { + offset: position + index as u64, + value: *byte, + }); + } + } + + Ok(()) +} diff --git a/crates/vxls-production/src/io/error.rs b/crates/vxls-production/src/io/error.rs new file mode 100644 index 0000000..ddb82b8 --- /dev/null +++ b/crates/vxls-production/src/io/error.rs @@ -0,0 +1,449 @@ +//! Errors produced while reading or writing a VXLS sparse-tree file. + +use std::fmt; +use std::io; + +/// Anything that can go wrong reading or writing a sparse-tree file. +#[derive(Debug)] +pub enum TreeFileError +{ + /// An underlying I/O error. + Io(io::Error), + + /// A structural parse error reported by `binrw`. + Binrw(binrw::Error), + + /// The file does not start with `b"VXLS"`. + BadMagic + { + found: [u8; 4], + }, + + /// The file is not a sparse tree (`b"ST\0\0"`). + BadFileType + { + found: [u8; 4], + }, + + /// The file's version is not readable by this implementation. + UnsupportedVersion + { + major: u32, + minor: u32, + }, + + /// The file is shorter than a mandatory fixed-size section. + FileTooSmall + { + len: u64, + needed: u64, + }, + + /// The preamble's declared size does not match the real file length. + FileSizeMismatch + { + declared: u64, + actual: u64, + }, + + /// `header_size` is below the minimum. + HeaderTooSmall + { + header_size: u32, + }, + + /// The header extends past the end of the file. + HeaderOutOfBounds + { + header_size: u32, + file_len: u64, + }, + + /// `tree_arity` is below 2. + ArityTooSmall + { + arity: u32, + }, + + /// The file's arity does not match the requested `N`. + ArityMismatch + { + file: u32, + requested: u32, + }, + + /// `tree_depth` exceeds what `TreeLocator` can address for this arity. + DepthTooLarge + { + depth: u32, + max: u32, + }, + + /// The attribute layout has no attributes. + EmptyLayout, + + /// An attribute declares zero words per voxel. + InvalidWordCount + { + index: usize, + word_count: u32, + }, + + /// The layout's word count does not match `size_of::()`. + LayoutSizeMismatch + { + layout_words: u64, + payload_words: u64, + }, + + /// `size_of::()` is not a whole number of 32-bit words. + PayloadNotWordAligned + { + size: usize, + }, + + /// The file's attribute word counts differ from the expected layout. + LayoutMismatch + { + expected: Vec, + found: Vec, + }, + + /// The offset table size is not a multiple of the entry size. + OffsetTableNotAligned + { + size: u32, + }, + + /// The offset table extends past the end of the file. + OffsetTableOutOfBounds + { + end: u64, + file_len: u64, + }, + + /// Offset-table entries are not ordered by file offset. + OffsetTableNotSorted, + + /// A chunk offset is not 8-byte aligned. + MisalignedOffset + { + offset: u64, + }, + + /// A chunk does not start where the previous chunk and the alignment rule say. + ChunkOffsetMismatch + { + tag: u32, + expected: u64, + found: u64, + }, + + /// Padding between chunks contains a non-zero byte. + NonZeroPadding + { + offset: u64, + value: u8, + }, + + /// A chunk extends past the end of the file. + ChunkOutOfBounds + { + tag: u32, + offset: u64, + size: u64, + }, + + /// A chunk declares a size smaller than the 12-byte frame. + ChunkSizeTooSmall + { + tag: u32, + size: u64, + }, + + /// A chunk's declared size does not match the bytes its body consumed. + ChunkSizeMismatch + { + tag: u32, + declared: u64, + consumed: u64, + }, + + /// The size in the offset table differs from the size in the chunk frame. + EntrySizeMismatch + { + tag: u32, + entry: u64, + frame: u64, + }, + + /// The tag in the offset table differs from the tag in the chunk frame. + ChunkTagMismatch + { + entry: u32, + frame: u32, + }, + + /// The same chunk tag appears more than once. + DuplicateChunk + { + tag: u32, + }, + + /// The file contains an undefined tag. + UnexpectedTag + { + tag: u32, + }, + + /// The mandatory attributes chunk is missing. + MissingAttributesChunk, + + /// A tree level has no chunk. + MissingLevelChunk + { + level: u32, + }, + + /// A tree level chunk is beyond `tree_depth`. + LevelOutOfRange + { + level: u32, + tree_depth: u32, + }, + + /// A level declares a different number of nodes than its parents imply. + NodeCountMismatch + { + level: u32, + declared: u32, + expected: u64, + }, + + /// The unused bits of a level's subdivision flags are not zero. + TrailingFlagBits + { + level: u32, + }, + + /// The deepest level contains a subdivided node. + SubdividedAtDeepestLevel + { + level: u32, + }, + + /// The tree contains nodes that cannot be reached from the root, or vice versa. + UnreachableNodes + { + reachable: usize, + stored: usize, + }, + + /// The in-memory tree cannot be represented by the format. + InconsistentTree + { + reason: &'static str, + }, + + /// An arithmetic operation overflowed while sizing the file. + Overflow + { + what: &'static str, + }, + + /// A chunk's CRC does not match its contents. + CrcMismatch + { + tag: u32, + offset: u64, + expected: u32, + found: u32, + }, + + /// Bytes remain after the last chunk. + TrailingBytes + { + end: u64, + file_len: u64, + }, +} + +impl fmt::Display for TreeFileError +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result + { + match self + { + Self::Io(error) => write!(f, "I/O error: {error}"), + Self::Binrw(error) => write!(f, "parse error: {error}"), + Self::BadMagic { found } => { + write!(f, "bad magic {found:02X?}, expected b\"VXLS\"") + } + Self::BadFileType { found } => { + write!(f, "bad file type {found:02X?}, expected b\"ST\\0\\0\"") + } + Self::UnsupportedVersion { major, minor } => { + write!(f, "unsupported file version {major}.{minor}") + } + Self::FileTooSmall { len, needed } => { + write!(f, "file is {len} bytes, at least {needed} are needed") + } + Self::FileSizeMismatch { declared, actual } => { + write!(f, "file declares {declared} bytes but is {actual} bytes long") + } + Self::HeaderTooSmall { header_size } => { + write!(f, "header_size {header_size} is smaller than the 12-byte header") + } + Self::HeaderOutOfBounds { + header_size, + file_len, + } => write!( + f, + "header_size {header_size} extends past the {file_len}-byte file" + ), + Self::ArityTooSmall { arity } => write!(f, "tree_arity {arity} is below 2"), + Self::ArityMismatch { file, requested } => { + write!(f, "file arity {file} does not match requested arity {requested}") + } + Self::DepthTooLarge { depth, max } => { + write!(f, "tree_depth {depth} exceeds the maximum {max}") + } + Self::EmptyLayout => write!(f, "the attribute layout is empty"), + Self::InvalidWordCount { index, word_count } => write!( + f, + "attribute {index} has word_count {word_count}, expected at least 1" + ), + Self::LayoutSizeMismatch { + layout_words, + payload_words, + } => write!( + f, + "layout totals {layout_words} words but the payload is {payload_words} words" + ), + Self::PayloadNotWordAligned { size } => { + write!(f, "payload size {size} is not a multiple of 4 bytes") + } + Self::LayoutMismatch { expected, found } => { + write!(f, "attribute layout mismatch: expected {expected:?}, file has {found:?}") + } + Self::OffsetTableNotAligned { size } => { + write!(f, "offset table size {size} is not a multiple of 24") + } + Self::OffsetTableOutOfBounds { end, file_len } => { + write!(f, "offset table ends at {end}, past the {file_len}-byte file") + } + Self::OffsetTableNotSorted => { + write!(f, "offset table entries are not ordered by file_offset") + } + Self::MisalignedOffset { offset } => { + write!(f, "chunk offset {offset} is not 8-byte aligned") + } + Self::ChunkOffsetMismatch { + tag, + expected, + found, + } => write!( + f, + "chunk {tag:#010X} starts at {found}, expected {expected}" + ), + Self::NonZeroPadding { offset, value } => { + write!(f, "padding byte at {offset} is {value}, expected 0") + } + Self::ChunkOutOfBounds { tag, offset, size } => write!( + f, + "chunk {tag:#010X} at {offset} with size {size} extends past the file" + ), + Self::ChunkSizeTooSmall { tag, size } => { + write!(f, "chunk {tag:#010X} size {size} is smaller than 12") + } + Self::ChunkSizeMismatch { + tag, + declared, + consumed, + } => write!( + f, + "chunk {tag:#010X} declares {declared} body bytes but consumed {consumed}" + ), + Self::EntrySizeMismatch { tag, entry, frame } => write!( + f, + "chunk {tag:#010X} size {frame} in the frame differs from {entry} in the offset table" + ), + Self::ChunkTagMismatch { entry, frame } => write!( + f, + "chunk tag {frame:#010X} in the frame differs from {entry:#010X} in the offset table" + ), + Self::DuplicateChunk { tag } => write!(f, "chunk tag {tag:#010X} appears twice"), + Self::UnexpectedTag { tag } => write!(f, "undefined chunk tag {tag:#010X}"), + Self::MissingAttributesChunk => write!(f, "the attributes chunk is missing"), + Self::MissingLevelChunk { level } => { + write!(f, "the chunk for tree level {level} is missing") + } + Self::LevelOutOfRange { level, tree_depth } => write!( + f, + "level chunk {level} is beyond tree_depth {tree_depth}" + ), + Self::NodeCountMismatch { + level, + declared, + expected, + } => write!( + f, + "level {level} declares {declared} nodes but its parents imply {expected}" + ), + Self::TrailingFlagBits { level } => { + write!(f, "level {level} has non-zero unused subdivision bits") + } + Self::SubdividedAtDeepestLevel { level } => { + write!(f, "level {level} is the deepest level but has subdivided nodes") + } + Self::UnreachableNodes { reachable, stored } => write!( + f, + "{reachable} nodes are reachable from the root but the tree stores {stored}" + ), + Self::InconsistentTree { reason } => write!(f, "inconsistent tree: {reason}"), + Self::Overflow { what } => write!(f, "integer overflow while computing {what}"), + Self::CrcMismatch { + tag, + offset, + expected, + found, + } => write!( + f, + "chunk {tag:#010X} at {offset} has CRC {found:#010X}, expected {expected:#010X}" + ), + Self::TrailingBytes { end, file_len } => write!( + f, + "the last chunk ends at {end} but the file is {file_len} bytes long" + ), + } + } +} + +impl std::error::Error for TreeFileError +{ + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> + { + match self + { + Self::Io(error) => Some(error), + Self::Binrw(error) => Some(error), + _ => None, + } + } +} + +impl From for TreeFileError +{ + fn from(value: io::Error) -> Self + { + Self::Io(value) + } +} + +impl From for TreeFileError +{ + fn from(value: binrw::Error) -> Self + { + Self::Binrw(value) + } +} diff --git a/crates/vxls-production/src/io/format.rs b/crates/vxls-production/src/io/format.rs new file mode 100644 index 0000000..9b887bb --- /dev/null +++ b/crates/vxls-production/src/io/format.rs @@ -0,0 +1,353 @@ +//! On-disk wire types of the VXLS sparse-tree format. +//! +//! Fixed-shape sections derive [`BinRead`]/[`BinWrite`]. The two variable +//! sections (attributes and tree levels) are implemented by hand because they +//! are structure-of-arrays with counts taken from the stream and from the +//! attribute layout. + +use std::io::{Read, Seek, SeekFrom, Write}; + +use binrw::{BinRead, BinResult, BinWrite, Endian}; + +/// File magic. +pub const MAGIC: [u8; 4] = *b"VXLS"; + +/// File-type word for a sparse tree. +pub const FILE_TYPE_SPARSE_TREE: [u8; 4] = *b"ST\0\0"; + +/// Size of [`Preamble`] in bytes. +pub const PREAMBLE_SIZE: u64 = 24; + +/// Size of [`Header`] in bytes. +pub const HEADER_SIZE: u32 = 12; + +/// Size of the fixed part of a chunk frame (`tag` + `chunk_size`). +pub const CHUNK_FRAME_SIZE: u64 = 12; + +/// Size of one offset-table entry. +pub const OFFSET_ENTRY_SIZE: u64 = 24; + +/// Chunk tag of the attributes section. +pub const TAG_ATTRIBUTES: u32 = 1; + +/// High bit of a tree-level chunk tag. +pub const TAG_LEVEL_FLAG: u32 = 0x8000_0000; + +/// Version written by this implementation. +pub const CURRENT_MAJOR: u32 = 1; + +/// Minor version written by this implementation. +pub const CURRENT_MINOR: u32 = 0; + +/// Builds the chunk tag for a tree level, 0 being the root. +pub const fn level_tag(level: u32) -> u32 +{ + TAG_LEVEL_FLAG | level +} + +/// Extracts the level from a chunk tag, or `None` for a non-level chunk. +pub const fn level_of(tag: u32) -> Option +{ + if tag & TAG_LEVEL_FLAG != 0 + { + Some(tag & !TAG_LEVEL_FLAG) + } + else + { + None + } +} + +/// Number of `u32` words needed for `node_count` subdivision flags. +pub const fn mask_words(node_count: u32) -> usize +{ + (node_count as usize).div_ceil(32) +} +/// File preamble. +#[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)] +#[brw(little)] +pub struct Preamble +{ + pub magic: [u8; 4], + pub file_type: [u8; 4], + pub major_version: u32, + pub minor_version: u32, + pub total_file_size: u64, +} + +/// Fixed header following the preamble. +#[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)] +#[brw(little)] +pub struct Header +{ + pub header_size: u32, + pub tree_arity: u32, + pub tree_depth: u32, +} + +/// The fixed part of a chunk frame. +#[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)] +#[brw(little)] +pub struct ChunkFrame +{ + pub chunk_type_tag: u32, + pub chunk_size: u64, +} + +/// One entry of the offset table. +#[derive(BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq)] +#[brw(little)] +pub struct OffsetEntry +{ + pub chunk_type_tag: u32, + pub reserved: u32, + pub file_offset: u64, + pub chunk_size: u64, +} + +/// One attribute as recorded in the attributes chunk. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FileAttribute +{ + /// Human-readable name. The format does not interpret it. + pub label: String, + + /// Size of the attribute in 32-bit words. + pub word_count: u32, +} + +/// The attributes chunk body. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AttributesBody +{ + pub attributes: Vec, +} + +impl BinRead for AttributesBody +{ + type Args<'a> = (); + + fn read_options( + reader: &mut R, + endian: Endian, + _args: Self::Args<'_>, + ) -> BinResult + { + let start = reader.stream_position()?; + let remaining = remaining_bytes(reader)?; + let count = u32::read_options(reader, endian, ())?; + + // Every entry needs at least word_count + label_size. + if count as u64 > remaining / 8 + { + return Err(binrw::Error::AssertFail { + pos: start, + message: format!( + "attributes chunk declares {count} entries, which cannot fit in {remaining} bytes" + ), + }); + } + + let mut attributes = Vec::with_capacity(count as usize); + + for index in 0..count + { + let word_count = u32::read_options(reader, endian, ())?; + let label_size = u32::read_options(reader, endian, ())?; + let position = reader.stream_position()?; + + if label_size as u64 > remaining_bytes(reader)? + { + return Err(binrw::Error::AssertFail { + pos: position, + message: format!( + "attribute {index} label length {label_size} exceeds the chunk body" + ), + }); + } + + let mut bytes = vec![0u8; label_size as usize]; + reader.read_exact(&mut bytes)?; + + let label = String::from_utf8(bytes).map_err(|_| binrw::Error::AssertFail { + pos: position, + message: format!("attribute {index} label is not valid UTF-8"), + })?; + + attributes.push(FileAttribute { label, word_count }); + } + + Ok(Self { attributes }) + } +} + +impl BinWrite for AttributesBody +{ + type Args<'a> = (); + + fn write_options( + &self, + writer: &mut W, + endian: Endian, + _args: Self::Args<'_>, + ) -> BinResult<()> + { + let count = u32::try_from(self.attributes.len()).map_err(|_| { + binrw::Error::AssertFail { + pos: writer.stream_position().unwrap_or(0), + message: "attribute count does not fit in a u32".to_string(), + } + })?; + count.write_options(writer, endian, ())?; + + for attribute in &self.attributes + { + let label_size = u32::try_from(attribute.label.len()).map_err(|_| { + binrw::Error::AssertFail { + pos: writer.stream_position().unwrap_or(0), + message: "attribute label does not fit in a u32".to_string(), + } + })?; + + attribute.word_count.write_options(writer, endian, ())?; + label_size.write_options(writer, endian, ())?; + writer.write_all(attribute.label.as_bytes())?; + } + + Ok(()) + } +} + +/// One tree level, stored as a structure of arrays. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LevelBody +{ + /// Number of nodes at this level. + pub node_count: u32, + + /// One `subdivided` bit per node, packed least-significant bit first. + pub subdivided: Vec, + + /// One word array per attribute, `node_count * word_count` words each. + pub attributes: Vec>, +} + +/// Arguments of [`LevelBody::read_options`]. +pub struct LevelArgs<'a> +{ + /// Word count of every attribute, in binding order. + pub word_counts: &'a [u32], +} + +impl BinRead for LevelBody +{ + type Args<'a> = LevelArgs<'a>; + + fn read_options( + reader: &mut R, + endian: Endian, + args: Self::Args<'_>, + ) -> BinResult + { + let start = reader.stream_position()?; + let node_count = u32::read_options(reader, endian, ())?; + + let words = mask_words(node_count); + let mask_bytes = words as u64 * 4; + + if mask_bytes > remaining_bytes(reader)? + { + return Err(binrw::Error::AssertFail { + pos: start, + message: format!( + "level with {node_count} nodes needs {mask_bytes} mask bytes, more than the chunk holds" + ), + }); + } + + let mut subdivided = Vec::with_capacity(words); + + for _ in 0..words + { + subdivided.push(u32::read_options(reader, endian, ())?); + } + + let mut attributes = Vec::with_capacity(args.word_counts.len()); + + for (index, &word_count) in args.word_counts.iter().enumerate() + { + let count = (node_count as u64) + .checked_mul(word_count as u64) + .ok_or_else(|| binrw::Error::AssertFail { + pos: start, + message: format!( + "attribute {index} needs {node_count} * {word_count} words, which overflows" + ), + })?; + + if count.saturating_mul(4) > remaining_bytes(reader)? + { + return Err(binrw::Error::AssertFail { + pos: start, + message: format!( + "attribute {index} needs {count} words, more than the chunk holds" + ), + }); + } + + let count = count as usize; + let mut attribute = Vec::with_capacity(count); + + for _ in 0..count + { + attribute.push(u32::read_options(reader, endian, ())?); + } + + attributes.push(attribute); + } + + Ok(Self { + node_count, + subdivided, + attributes, + }) + } +} + +impl BinWrite for LevelBody +{ + type Args<'a> = (); + + fn write_options( + &self, + writer: &mut W, + endian: Endian, + _args: Self::Args<'_>, + ) -> BinResult<()> + { + self.node_count.write_options(writer, endian, ())?; + + for word in &self.subdivided + { + word.write_options(writer, endian, ())?; + } + + for attribute in &self.attributes + { + for word in attribute + { + word.write_options(writer, endian, ())?; + } + } + + Ok(()) + } +} + +fn remaining_bytes(reader: &mut R) -> BinResult +{ + let position = reader.stream_position()?; + let end = reader.seek(SeekFrom::End(0))?; + reader.seek(SeekFrom::Start(position))?; + Ok(end.saturating_sub(position)) +} diff --git a/crates/vxls-production/src/io/read.rs b/crates/vxls-production/src/io/read.rs new file mode 100644 index 0000000..c0e801e --- /dev/null +++ b/crates/vxls-production/src/io/read.rs @@ -0,0 +1,636 @@ +//! Reading and validating VXLS sparse-tree files. + +use std::collections::{HashMap, HashSet}; +use std::fs::File; +use std::io::{Cursor, Read, Seek, SeekFrom}; +use std::mem::size_of; +use std::path::Path; + +use binrw::{BinRead, Endian}; + +use super::chunk::{CHUNK_ALIGNMENT, Chunk, align_up, read_chunk, read_padding}; +use super::error::TreeFileError; +use super::format::{ + AttributesBody, CURRENT_MAJOR, CHUNK_FRAME_SIZE, FILE_TYPE_SPARSE_TREE, FileAttribute, + HEADER_SIZE, Header, LevelArgs, LevelBody, MAGIC, OFFSET_ENTRY_SIZE, OffsetEntry, PREAMBLE_SIZE, + Preamble, TAG_ATTRIBUTES, level_of, mask_words, +}; +use crate::attributes::{Attribute, AttributesLayout}; +use crate::sparse_tree::{NTree, NTreeNode}; +use crate::tree_locator::TreeLocator; + +/// The attribute layout read from a file. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct FileLayout +{ + pub attributes: Vec, +} + +impl FileLayout +{ + /// Total number of 32-bit words per voxel. + pub fn total_word_count(&self) -> u64 + { + self.attributes + .iter() + .map(|attribute| attribute.word_count as u64) + .sum() + } + + /// Index of the first attribute with this label. + pub fn by_label(&self, label: &str) -> Option + { + self.attributes + .iter() + .position(|attribute| attribute.label == label) + } +} + +/// A tree and its attribute layout, as read from a file. +pub struct TreeFile +{ + /// The parsed tree. + pub tree: NTree, + + /// The attribute split recorded in the file, in binding order. + pub layout: FileLayout, + + /// Major version of the file. + pub major_version: u32, + + /// Minor version of the file. + pub minor_version: u32, +} + +impl std::fmt::Debug for TreeFile +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result + { + f.debug_struct("TreeFile") + .field("depth", &self.tree.depth()) + .field("nodes", &self.tree.node_count()) + .field("layout", &self.layout) + .field("major_version", &self.major_version) + .field("minor_version", &self.minor_version) + .finish() + } +} + +/// Reads a sparse-tree file. +/// +/// When `expected` is `Some`, the file's attribute count and word counts must +/// match it exactly. Labels are treated as hints and are not compared. +pub fn read_tree( + reader: &mut R, + expected: Option, +) -> Result, TreeFileError> +where + R: Read + Seek, + T: Attribute, + [(); N * N * N]:, +{ + if N < 2 + { + return Err(TreeFileError::ArityTooSmall { arity: N as u32 }); + } + + let file_len = reader.seek(SeekFrom::End(0))?; + reader.seek(SeekFrom::Start(0))?; + + if file_len < PREAMBLE_SIZE + { + return Err(TreeFileError::FileTooSmall { + len: file_len, + needed: PREAMBLE_SIZE, + }); + } + + let preamble = Preamble::read_options(reader, Endian::Little, ())?; + + if preamble.magic != MAGIC + { + return Err(TreeFileError::BadMagic { + found: preamble.magic, + }); + } + + if preamble.file_type != FILE_TYPE_SPARSE_TREE + { + return Err(TreeFileError::BadFileType { + found: preamble.file_type, + }); + } + + if preamble.major_version != CURRENT_MAJOR + { + return Err(TreeFileError::UnsupportedVersion { + major: preamble.major_version, + minor: preamble.minor_version, + }); + } + + // A newer minor is accepted: unknown chunks are skipped while walking the + // offset table. + + if preamble.total_file_size != file_len + { + return Err(TreeFileError::FileSizeMismatch { + declared: preamble.total_file_size, + actual: file_len, + }); + } + + let minimum_header_end = PREAMBLE_SIZE + HEADER_SIZE as u64; + + if file_len < minimum_header_end + { + return Err(TreeFileError::FileTooSmall { + len: file_len, + needed: minimum_header_end, + }); + } + + let header = Header::read_options(reader, Endian::Little, ())?; + + if header.header_size < HEADER_SIZE + { + return Err(TreeFileError::HeaderTooSmall { + header_size: header.header_size, + }); + } + + let header_end = PREAMBLE_SIZE + header.header_size as u64; + + if header_end > file_len + { + return Err(TreeFileError::HeaderOutOfBounds { + header_size: header.header_size, + file_len, + }); + } + + reader.seek(SeekFrom::Start(header_end))?; + + if header.tree_arity < 2 + { + return Err(TreeFileError::ArityTooSmall { + arity: header.tree_arity, + }); + } + + if header.tree_arity != N as u32 + { + return Err(TreeFileError::ArityMismatch { + file: header.tree_arity, + requested: N as u32, + }); + } + + if header.tree_depth > TreeLocator::::max_depth() + { + return Err(TreeFileError::DepthTooLarge { + depth: header.tree_depth, + max: TreeLocator::::max_depth(), + }); + } + + let table_size = u32::read_options(reader, Endian::Little, ())?; + + if !(table_size as u64).is_multiple_of(OFFSET_ENTRY_SIZE) + { + return Err(TreeFileError::OffsetTableNotAligned { size: table_size }); + } + + let table_end = header_end + 4 + table_size as u64; + + if table_end > file_len + { + return Err(TreeFileError::OffsetTableOutOfBounds { + end: table_end, + file_len, + }); + } + + let entry_count = table_size as usize / OFFSET_ENTRY_SIZE as usize; + let mut entries = Vec::with_capacity(entry_count); + let mut tags = HashSet::with_capacity(entry_count); + let mut previous_offset = None; + + for _ in 0..entry_count + { + let entry = OffsetEntry::read_options(reader, Endian::Little, ())?; + + if !tags.insert(entry.chunk_type_tag) + { + return Err(TreeFileError::DuplicateChunk { + tag: entry.chunk_type_tag, + }); + } + + if entry.file_offset % CHUNK_ALIGNMENT != 0 + { + return Err(TreeFileError::MisalignedOffset { + offset: entry.file_offset, + }); + } + + if entry.chunk_size < CHUNK_FRAME_SIZE + { + return Err(TreeFileError::ChunkSizeTooSmall { + tag: entry.chunk_type_tag, + size: entry.chunk_size, + }); + } + + let end = entry + .file_offset + .checked_add(entry.chunk_size) + .and_then(|value| value.checked_add(4)) + .ok_or(TreeFileError::Overflow { what: "chunk end" })?; + + if end > file_len + { + return Err(TreeFileError::ChunkOutOfBounds { + tag: entry.chunk_type_tag, + offset: entry.file_offset, + size: entry.chunk_size, + }); + } + + if let Some(previous) = previous_offset + && entry.file_offset <= previous + { + return Err(TreeFileError::OffsetTableNotSorted); + } + + previous_offset = Some(entry.file_offset); + entries.push(entry); + } + + if entry_count == 0 + { + return Err(TreeFileError::MissingAttributesChunk); + } + + // The writer emits chunks back to back; the reader enforces that packing. + let mut previous_end = table_end; + + for entry in &entries + { + let expected = align_up(previous_end, CHUNK_ALIGNMENT); + + if entry.file_offset != expected + { + return Err(TreeFileError::ChunkOffsetMismatch { + tag: entry.chunk_type_tag, + expected, + found: entry.file_offset, + }); + } + + reader.seek(SeekFrom::Start(previous_end))?; + read_padding(reader, entry.file_offset)?; + + previous_end = entry.file_offset + entry.chunk_size + 4; + } + + if previous_end != file_len + { + return Err(TreeFileError::TrailingBytes { + end: previous_end, + file_len, + }); + } + + let mut attributes_entry = None; + let mut level_entries = HashMap::new(); + + for entry in &entries + { + if entry.chunk_type_tag == TAG_ATTRIBUTES + { + attributes_entry = Some(*entry); + } + else if let Some(level) = level_of(entry.chunk_type_tag) + { + if level > header.tree_depth + { + return Err(TreeFileError::LevelOutOfRange { + level, + tree_depth: header.tree_depth, + }); + } + + level_entries.insert(level, *entry); + } + else if entry.chunk_type_tag == 0 + { + return Err(TreeFileError::UnexpectedTag { + tag: entry.chunk_type_tag, + }); + } + // Unknown non-level chunks are skipped for minor-version compatibility. + } + + let attributes_entry = attributes_entry.ok_or(TreeFileError::MissingAttributesChunk)?; + + let level_count = level_entries.len(); + + if level_count == 0 + { + return Err(TreeFileError::MissingLevelChunk { level: 0 }); + } + + for level in 0..level_count as u32 + { + if !level_entries.contains_key(&level) + { + return Err(TreeFileError::MissingLevelChunk { level }); + } + } + + let deepest = level_count as u32 - 1; + + let layout = read_attributes(reader, &attributes_entry, file_len)?; + + if let Some(expected) = expected + { + let expected_words: Vec = expected + .attributes + .iter() + .map(|attribute| attribute.word_count) + .collect(); + let found_words: Vec = layout + .attributes + .iter() + .map(|attribute| attribute.word_count) + .collect(); + + if expected_words != found_words + { + return Err(TreeFileError::LayoutMismatch { + expected: expected_words, + found: found_words, + }); + } + } + + for (index, attribute) in layout.attributes.iter().enumerate() + { + if attribute.word_count == 0 + { + return Err(TreeFileError::InvalidWordCount { + index, + word_count: attribute.word_count, + }); + } + } + + if !size_of::().is_multiple_of(4) + { + return Err(TreeFileError::PayloadNotWordAligned { size: size_of::() }); + } + + let layout_words = layout.total_word_count(); + let payload_words = (size_of::() / 4) as u64; + + if layout_words != payload_words + { + return Err(TreeFileError::LayoutSizeMismatch { + layout_words, + payload_words, + }); + } + + let word_counts: Vec = layout + .attributes + .iter() + .map(|attribute| attribute.word_count) + .collect(); + + let tree = read_tree_body::( + reader, + file_len, + header.tree_depth, + deepest, + &level_entries, + &word_counts, + )?; + + Ok(TreeFile { + tree, + layout, + major_version: preamble.major_version, + minor_version: preamble.minor_version, + }) +} + +/// Reads `path` as a sparse-tree file. +pub fn read_tree_from_path( + path: P, + expected: Option, +) -> Result, TreeFileError> +where + P: AsRef, + T: Attribute, + [(); N * N * N]:, +{ + let mut file = File::open(path)?; + read_tree(&mut file, expected) +} + +fn read_attributes( + reader: &mut R, + entry: &OffsetEntry, + file_len: u64, +) -> Result +{ + let chunk = read_chunk_at(reader, entry, file_len)?; + + if chunk.tag != TAG_ATTRIBUTES + { + return Err(TreeFileError::ChunkTagMismatch { + entry: TAG_ATTRIBUTES, + frame: chunk.tag, + }); + } + + let mut cursor = Cursor::new(&chunk.body); + let body = AttributesBody::read_options(&mut cursor, Endian::Little, ())?; + + if cursor.position() != chunk.body.len() as u64 + { + return Err(TreeFileError::ChunkSizeMismatch { + tag: chunk.tag, + declared: chunk.body.len() as u64, + consumed: cursor.position(), + }); + } + + Ok(FileLayout { + attributes: body.attributes, + }) +} + +fn read_tree_body( + reader: &mut (impl Read + Seek), + file_len: u64, + tree_depth: u32, + deepest: u32, + level_entries: &HashMap, + word_counts: &[u32], +) -> Result, TreeFileError> +where + [(); N * N * N]:, +{ + let mut map: HashMap, NTreeNode> = HashMap::new(); + let mut parents = vec![TreeLocator::::root()]; + let mut scratch = vec![0u8; size_of::()]; + + for level in 0..=deepest + { + let entry = level_entries + .get(&level) + .ok_or(TreeFileError::MissingLevelChunk { level })?; + let chunk = read_chunk_at(reader, entry, file_len)?; + + if level_of(chunk.tag) != Some(level) + { + return Err(TreeFileError::ChunkTagMismatch { + entry: entry.chunk_type_tag, + frame: chunk.tag, + }); + } + + let mut cursor = Cursor::new(&chunk.body); + let body = LevelBody::read_options( + &mut cursor, + Endian::Little, + LevelArgs { word_counts }, + )?; + + if cursor.position() != chunk.body.len() as u64 + { + return Err(TreeFileError::ChunkSizeMismatch { + tag: chunk.tag, + declared: chunk.body.len() as u64, + consumed: cursor.position(), + }); + } + + let node_count = body.node_count as usize; + + if node_count as u64 != parents.len() as u64 + { + return Err(TreeFileError::NodeCountMismatch { + level, + declared: body.node_count, + expected: parents.len() as u64, + }); + } + + if body.subdivided.len() != mask_words(body.node_count) + { + return Err(TreeFileError::InconsistentTree { + reason: "level mask length does not match its node count", + }); + } + + if body.node_count % 32 != 0 + { + let used = body.node_count % 32; + let last = *body.subdivided.last().unwrap_or(&0); + + if last >> used != 0 + { + return Err(TreeFileError::TrailingFlagBits { level }); + } + } + + let mut next = Vec::new(); + + for (index, parent) in parents.iter().enumerate() + { + let subdivided = body.subdivided[index / 32] & (1 << (index % 32)) != 0; + + let mut byte_offset = 0usize; + + for (attribute_index, &word_count) in word_counts.iter().enumerate() + { + let word_count = word_count as usize; + let start = index * word_count; + let end = start + word_count; + let words = &body.attributes[attribute_index][start..end]; + + for word in words + { + scratch[byte_offset..byte_offset + 4] + .copy_from_slice(&word.to_ne_bytes()); + byte_offset += 4; + } + } + + let attribute = bytemuck::pod_read_unaligned::(&scratch); + + map.insert( + *parent, + NTreeNode { + attribute, + subdivided, + }, + ); + + if subdivided + { + next.extend(parent.children()); + } + } + + if level == deepest && !next.is_empty() + { + return Err(TreeFileError::SubdividedAtDeepestLevel { level }); + } + + parents = next; + } + + if !parents.is_empty() + { + return Err(TreeFileError::NodeCountMismatch { + level: deepest, + declared: 0, + expected: parents.len() as u64, + }); + } + + Ok(NTree::from_nodes(map, tree_depth as usize)) +} + +fn read_chunk_at( + reader: &mut R, + entry: &OffsetEntry, + file_len: u64, +) -> Result +{ + reader.seek(SeekFrom::Start(entry.file_offset))?; + let chunk = read_chunk(reader, file_len)?; + + if chunk.tag != entry.chunk_type_tag + { + return Err(TreeFileError::ChunkTagMismatch { + entry: entry.chunk_type_tag, + frame: chunk.tag, + }); + } + + if chunk.size != entry.chunk_size + { + return Err(TreeFileError::EntrySizeMismatch { + tag: chunk.tag, + entry: entry.chunk_size, + frame: chunk.size, + }); + } + + Ok(chunk) +} diff --git a/crates/vxls-production/src/io/write.rs b/crates/vxls-production/src/io/write.rs new file mode 100644 index 0000000..8f0f0e2 --- /dev/null +++ b/crates/vxls-production/src/io/write.rs @@ -0,0 +1,679 @@ +//! Writing VXLS sparse-tree files. + +use std::fs::File; +use std::io::{Cursor, Write}; +use std::mem::size_of; +use std::path::Path; + +use binrw::{BinWrite, Endian}; + +use super::chunk::{CHUNK_ALIGNMENT, align_up, write_chunk, write_padding_to_alignment}; +use super::error::TreeFileError; +use super::format::{ + AttributesBody, CURRENT_MAJOR, CURRENT_MINOR, FILE_TYPE_SPARSE_TREE, FileAttribute, + HEADER_SIZE, Header, LevelBody, MAGIC, OFFSET_ENTRY_SIZE, OffsetEntry, PREAMBLE_SIZE, Preamble, + TAG_ATTRIBUTES, level_tag, mask_words, +}; +use crate::attributes::{Attribute, AttributesLayout}; +use crate::sparse_tree::NTree; +use crate::tree_locator::TreeLocator; + +/// One level of the tree, as planned for writing. +struct LevelPlan +{ + locators: Vec>, + subdivided: Vec, +} + +impl LevelPlan +{ + fn node_count(&self) -> u64 + { + self.locators.len() as u64 + } + + fn body_len(&self, total_words: u64) -> u64 + { + let flags = mask_words(self.locators.len() as u32) as u64 * 4; + let attribute_bytes = self.node_count() * total_words * 4; + + 4 + flags + attribute_bytes + } +} + +struct ChunkPlan +{ + tag: u32, + offset: u64, + chunk_size: u64, +} + +/// Serialises `tree` with the attribute split described by `layout`. +/// +/// The layout must have at least one attribute, every `word_count` must be +/// non-zero, and `sum(word_count) * 4` must equal `size_of::()`. +pub fn write_tree( + writer: &mut W, + tree: &NTree, + layout: AttributesLayout, +) -> Result<(), TreeFileError> +where + W: Write + std::io::Seek, + T: Attribute, + [(); N * N * N]:, +{ + if N < 2 + { + return Err(TreeFileError::ArityTooSmall { arity: N as u32 }); + } + + let children_per_node = (N as u64) + .checked_mul(N as u64) + .and_then(|value| value.checked_mul(N as u64)) + .ok_or(TreeFileError::Overflow { what: "N^3" })?; + + if children_per_node > u32::MAX as u64 + { + return Err(TreeFileError::Overflow { + what: "N^3 does not fit in the u32 node count", + }); + } + + if !size_of::().is_multiple_of(4) + { + return Err(TreeFileError::PayloadNotWordAligned { size: size_of::() }); + } + + if layout.attributes.is_empty() + { + return Err(TreeFileError::EmptyLayout); + } + + let mut layout_words = 0u64; + + for (index, attribute) in layout.attributes.iter().enumerate() + { + if attribute.word_count == 0 + { + return Err(TreeFileError::InvalidWordCount { + index, + word_count: attribute.word_count, + }); + } + + layout_words = layout_words + .checked_add(attribute.word_count as u64) + .ok_or(TreeFileError::Overflow { + what: "attribute word count", + })?; + } + + let payload_words = (size_of::() / 4) as u64; + + if layout_words != payload_words + { + return Err(TreeFileError::LayoutSizeMismatch { + layout_words, + payload_words, + }); + } + + let tree_depth = u32::try_from(tree.depth()).map_err(|_| TreeFileError::DepthTooLarge { + depth: u32::MAX, + max: TreeLocator::::max_depth(), + })?; + + if tree_depth > TreeLocator::::max_depth() + { + return Err(TreeFileError::DepthTooLarge { + depth: tree_depth, + max: TreeLocator::::max_depth(), + }); + } + + let levels = plan_levels::(tree, tree_depth)?; + + // Reachability check: the file can only describe the part of the map that + // is reachable from the root. + let reachable = levels + .iter() + .map(|level| level.node_count()) + .sum::() + .try_into() + .unwrap_or(usize::MAX); + + if reachable != tree.node_count() + { + return Err(TreeFileError::UnreachableNodes { + reachable, + stored: tree.node_count(), + }); + } + + let word_offsets = attribute_word_offsets(layout); + + // Plan every chunk size and offset before writing anything. All sizes are + // derivable from the node counts and the layout, so no backpatching. + let attributes_body_len = attributes_body_len(layout)?; + + let mut plans: Vec = Vec::with_capacity(levels.len() + 1); + plans.push(ChunkPlan { + tag: TAG_ATTRIBUTES, + offset: 0, + chunk_size: chunk_size_for(attributes_body_len)?, + }); + + for (level, plan) in levels.iter().enumerate() + { + plans.push(ChunkPlan { + tag: level_tag(level as u32), + offset: 0, + chunk_size: chunk_size_for(plan.body_len(layout_words))?, + }); + } + + let header_end = PREAMBLE_SIZE + HEADER_SIZE as u64; + let table_size = (plans.len() as u64) + .checked_mul(OFFSET_ENTRY_SIZE) + .ok_or(TreeFileError::Overflow { + what: "offset table size", + })?; + let table_end = header_end + 4 + table_size; + + let mut cursor = align_up(table_end, CHUNK_ALIGNMENT); + + for plan in &mut plans + { + plan.offset = cursor; + cursor = align_up(cursor + plan.chunk_size + 4, CHUNK_ALIGNMENT); + } + + let last = plans + .last() + .ok_or(TreeFileError::InconsistentTree { + reason: "no chunks to write", + })?; + let total_file_size = last.offset + last.chunk_size + 4; + + Preamble { + magic: MAGIC, + file_type: FILE_TYPE_SPARSE_TREE, + major_version: CURRENT_MAJOR, + minor_version: CURRENT_MINOR, + total_file_size, + } + .write_options(writer, Endian::Little, ())?; + + Header { + header_size: HEADER_SIZE, + tree_arity: N as u32, + tree_depth, + } + .write_options(writer, Endian::Little, ())?; + + u32::try_from(table_size) + .map_err(|_| TreeFileError::Overflow { + what: "offset table size does not fit in a u32", + })? + .write_options(writer, Endian::Little, ())?; + + for plan in &plans + { + OffsetEntry { + chunk_type_tag: plan.tag, + reserved: 0, + file_offset: plan.offset, + chunk_size: plan.chunk_size, + } + .write_options(writer, Endian::Little, ())?; + } + + for (index, plan) in plans.iter().enumerate() + { + write_padding_to_alignment(writer)?; + + let position = writer.stream_position()?; + + if position != plan.offset + { + return Err(TreeFileError::ChunkOffsetMismatch { + tag: plan.tag, + expected: plan.offset, + found: position, + }); + } + + let body = if index == 0 + { + build_attributes_body(layout)? + } + else + { + build_level_body(tree, &levels[index - 1], layout, &word_offsets)? + }; + + write_chunk(writer, plan.tag, &body)?; + } + + let position = writer.stream_position()?; + + if position != total_file_size + { + return Err(TreeFileError::FileSizeMismatch { + declared: total_file_size, + actual: position, + }); + } + + Ok(()) +} + +/// Writes `tree` to a new file at `path`. +pub fn write_tree_to_path( + path: P, + tree: &NTree, + layout: AttributesLayout, +) -> Result<(), TreeFileError> +where + P: AsRef, + T: Attribute, + [(); N * N * N]:, +{ + let mut file = File::create(path)?; + write_tree(&mut file, tree, layout) +} + +fn plan_levels( + tree: &NTree, + capacity: u32, +) -> Result>, TreeFileError> +where + [(); N * N * N]:, +{ + let mut levels = Vec::new(); + let mut current = vec![TreeLocator::::root()]; + let mut level = 0u32; + + loop + { + let mut subdivided = Vec::with_capacity(current.len()); + + for locator in ¤t + { + let node = tree.get_by_loc(*locator).ok_or(TreeFileError::InconsistentTree { + reason: "a node reachable from the root is missing from the map", + })?; + subdivided.push(node.subdivided); + } + + let subdivided_count = subdivided.iter().filter(|flag| **flag).count(); + + if subdivided_count > 0 && level == capacity + { + return Err(TreeFileError::InconsistentTree { + reason: "a node at the maximum depth is subdivided", + }); + } + + let mut next = Vec::new(); + + if subdivided_count > 0 + { + let children = (N as u64) + .checked_mul(N as u64) + .and_then(|value| value.checked_mul(N as u64)) + .ok_or(TreeFileError::Overflow { what: "N^3" })?; + let reserve = (subdivided_count as u64) + .checked_mul(children) + .ok_or(TreeFileError::Overflow { + what: "next level node count", + })?; + let reserve = usize::try_from(reserve).map_err(|_| TreeFileError::Overflow { + what: "next level node count does not fit in usize", + })?; + next.reserve(reserve); + + for (locator, is_subdivided) in current.iter().zip(&subdivided) + { + if *is_subdivided + { + next.extend(locator.children()); + } + } + } + + let plan = LevelPlan { + locators: current, + subdivided, + }; + + if u32::try_from(plan.locators.len()).is_err() + { + return Err(TreeFileError::Overflow { + what: "level node count does not fit in a u32", + }); + } + + levels.push(plan); + + if next.is_empty() + { + break; + } + + current = next; + level += 1; + } + + Ok(levels) +} + +fn attribute_word_offsets(layout: AttributesLayout) -> Vec +{ + let mut offsets = Vec::with_capacity(layout.attributes.len()); + let mut offset = 0usize; + + for attribute in layout.attributes + { + offsets.push(offset); + offset += attribute.word_count as usize; + } + + offsets +} + +fn attributes_body_len(layout: AttributesLayout) -> Result +{ + let mut length = 4u64; + + for attribute in layout.attributes + { + length = length + .checked_add(8) + .and_then(|value| value.checked_add(attribute.label.len() as u64)) + .ok_or(TreeFileError::Overflow { + what: "attributes chunk length", + })?; + } + + Ok(length) +} + +fn build_attributes_body(layout: AttributesLayout) -> Result, TreeFileError> +{ + let body = AttributesBody { + attributes: layout + .attributes + .iter() + .map(|attribute| FileAttribute { + label: attribute.label.to_string(), + word_count: attribute.word_count, + }) + .collect(), + }; + + let mut cursor = Cursor::new(Vec::new()); + body.write_options(&mut cursor, Endian::Little, ())?; + Ok(cursor.into_inner()) +} + +fn build_level_body( + tree: &NTree, + plan: &LevelPlan, + layout: AttributesLayout, + word_offsets: &[usize], +) -> Result, TreeFileError> +where + [(); N * N * N]:, +{ + let node_count = u32::try_from(plan.locators.len()).map_err(|_| { + TreeFileError::Overflow { + what: "level node count does not fit in a u32", + } + })?; + + let mut flags = vec![0u32; mask_words(node_count)]; + + for (index, subdivided) in plan.subdivided.iter().enumerate() + { + if *subdivided + { + flags[index / 32] |= 1 << (index % 32); + } + } + + let mut attributes: Vec> = layout + .attributes + .iter() + .map(|attribute| { + Vec::with_capacity(node_count as usize * attribute.word_count as usize) + }) + .collect(); + + for locator in &plan.locators + { + let node = tree.get_by_loc(*locator).ok_or(TreeFileError::InconsistentTree { + reason: "a planned node disappeared from the map", + })?; + + let bytes = bytemuck::bytes_of(&node.attribute); + + for (index, attribute) in layout.attributes.iter().enumerate() + { + let start = word_offsets[index] * 4; + let end = start + attribute.word_count as usize * 4; + let slice = &bytes[start..end]; + + for word in slice.chunks_exact(4) + { + let value = u32::from_ne_bytes( + word.try_into().expect("chunks_exact yields 4-byte slices"), + ); + attributes[index].push(value); + } + } + } + + let body = LevelBody { + node_count, + subdivided: flags, + attributes, + }; + + let mut cursor = Cursor::new(Vec::new()); + body.write_options(&mut cursor, Endian::Little, ())?; + Ok(cursor.into_inner()) +} + +fn chunk_size_for(body_len: u64) -> Result +{ + super::format::CHUNK_FRAME_SIZE + .checked_add(body_len) + .ok_or(TreeFileError::Overflow { what: "chunk size" }) +} + +#[cfg(test)] +mod tests +{ + use std::io::Cursor; + use std::io::Seek; + use std::io::SeekFrom; + + use super::*; + use crate::io::chunk::read_chunk; + use crate::io::format::{ + AttributesBody, Header, LevelArgs, LevelBody, OffsetEntry, PREAMBLE_SIZE, level_of, + }; + use binrw::{BinRead, BinWrite}; + + const U32_LAYOUT: AttributesLayout = + AttributesLayout::new(&[crate::AttributeDescriptor::new("value", 1)]); + + fn write(tree: &NTree<2, u32>) -> Vec + { + let mut cursor = Cursor::new(Vec::new()); + write_tree(&mut cursor, tree, U32_LAYOUT).unwrap(); + cursor.into_inner() + } + + fn entries(bytes: &[u8]) -> Vec + { + let mut cursor = Cursor::new(bytes); + cursor.seek(SeekFrom::Start(PREAMBLE_SIZE)).unwrap(); + let header = Header::read_options(&mut cursor, Endian::Little, ()).unwrap(); + cursor + .seek(SeekFrom::Start( + PREAMBLE_SIZE + header.header_size as u64, + )) + .unwrap(); + let table_size = u32::read_options(&mut cursor, Endian::Little, ()).unwrap(); + + (0..table_size as usize / 24) + .map(|_| OffsetEntry::read_options(&mut cursor, Endian::Little, ()).unwrap()) + .collect() + } + + fn bodies(bytes: &[u8]) -> Vec<(u32, Vec)> + { + let mut cursor = Cursor::new(bytes); + entries(bytes) + .into_iter() + .map(|entry| { + cursor.seek(SeekFrom::Start(entry.file_offset)).unwrap(); + let chunk = read_chunk(&mut cursor, bytes.len() as u64).unwrap(); + assert_eq!(chunk.tag, entry.chunk_type_tag); + (chunk.tag, chunk.body) + }) + .collect() + } + + #[test] + fn child_order_is_x_fastest() + { + let mut tree = NTree::<2, u32>::constant(0, 1); + tree.set(1, 0, 0, 9); + + let bytes = write(&tree); + let chunks = bodies(&bytes); + + assert_eq!(chunks[0].0, TAG_ATTRIBUTES); + assert_eq!(level_of(chunks[1].0), Some(0)); + assert_eq!(level_of(chunks[2].0), Some(1)); + + let root = LevelBody::read_options( + &mut Cursor::new(&chunks[1].1), + Endian::Little, + LevelArgs { + word_counts: &[1], + }, + ) + .unwrap(); + assert_eq!(root.node_count, 1); + assert_eq!(root.subdivided, vec![1]); + assert_eq!(root.attributes[0], vec![9 / 8]); + + let level = LevelBody::read_options( + &mut Cursor::new(&chunks[2].1), + Endian::Little, + LevelArgs { + word_counts: &[1], + }, + ) + .unwrap(); + assert_eq!(level.node_count, 8); + assert_eq!(level.subdivided, vec![0]); + assert_eq!(level.attributes[0], vec![0, 9, 0, 0, 0, 0, 0, 0]); + } + + #[test] + fn chunks_are_aligned_and_packed() + { + let tree = NTree::<2, u32>::constant(3, 2); + let bytes = write(&tree); + let entries = entries(&bytes); + + let header_end = PREAMBLE_SIZE + 12; + let table_end = header_end + 4 + entries.len() as u64 * 24; + + let mut previous_end = table_end; + + for entry in &entries + { + let expected = crate::io::chunk::align_up(previous_end, 8); + assert_eq!(entry.file_offset, expected); + assert_eq!(entry.file_offset % 8, 0); + previous_end = entry.file_offset + entry.chunk_size + 4; + } + + assert_eq!(previous_end, bytes.len() as u64); + } + + #[test] + fn attributes_chunk_roundtrip() + { + let body = AttributesBody { + attributes: vec![ + FileAttribute { + label: "color".to_string(), + word_count: 1, + }, + FileAttribute { + label: "normal".to_string(), + word_count: 3, + }, + ], + }; + + let mut cursor = Cursor::new(Vec::new()); + body.write_options(&mut cursor, Endian::Little, ()).unwrap(); + + cursor.seek(SeekFrom::Start(0)).unwrap(); + let parsed = AttributesBody::read_options(&mut cursor, Endian::Little, ()).unwrap(); + + assert_eq!(parsed, body); + } + + #[test] + fn shallow_tree_keeps_capacity_in_the_header() + { + // A tree that bottoms out at level 1 while declaring a capacity of 4. + let mut map = std::collections::HashMap::new(); + map.insert( + TreeLocator::<2>::root(), + crate::sparse_tree::NTreeNode { + attribute: 1u32, + subdivided: true, + }, + ); + + for child in TreeLocator::<2>::root().children() + { + map.insert( + child, + crate::sparse_tree::NTreeNode { + attribute: 2u32, + subdivided: false, + }, + ); + } + + let tree = NTree::<2, u32>::from_nodes(map, 4); + let mut cursor = Cursor::new(Vec::new()); + write_tree(&mut cursor, &tree, U32_LAYOUT).unwrap(); + + let bytes = cursor.into_inner(); + let chunks = bodies(&bytes); + + // Attributes, level 0 and level 1 only. + assert_eq!(chunks.len(), 3); + + let mut cursor = Cursor::new(&bytes); + let file = + crate::io::read::read_tree::<_, 2, u32>(&mut cursor, Some(U32_LAYOUT)).unwrap(); + + assert_eq!(file.tree.depth(), 4); + assert_eq!(file.tree.node_count(), 9); + assert_eq!(file.tree.get(0, 0, 0), 2); + assert_eq!(file.tree.get(15, 15, 15), 2); + } +} diff --git a/crates/vxls-production/src/lib.rs b/crates/vxls-production/src/lib.rs index 2ac2c3d..b3187fd 100644 --- a/crates/vxls-production/src/lib.rs +++ b/crates/vxls-production/src/lib.rs @@ -46,3 +46,5 @@ pub mod request_queue; /// Routing voxel production to different producers pub mod production_router; + +pub mod io; diff --git a/crates/vxls-production/src/main.rs b/crates/vxls-production/src/main.rs new file mode 100644 index 0000000..3bfcd33 --- /dev/null +++ b/crates/vxls-production/src/main.rs @@ -0,0 +1,31 @@ +#![allow(incomplete_features)] +#![feature(generic_const_exprs)] +use std::fs::File; + +use vxls_production::AttributeDescriptor; +use vxls_production::AttributesLayout; +use vxls_production::io::write_tree; +use vxls_production::sparse_tree::Color; +use vxls_production::sparse_tree::NTree; +use vxls_production::sparse_tree::load_ply; + +fn main() +{ + let dragon: NTree<4, Color> = load_ply("../../dragon.txt"); + let mut file = File::create("../../dragon.vxls").unwrap(); + + let dragon_u32 = dragon.mapped(|v| v.as_color_byte()); + write_tree( + &mut file, + &dragon_u32, + AttributesLayout { + attributes: &[AttributeDescriptor { + label: "color", + word_count: 1, + semantic: None, + }], + }, + ) + .unwrap(); + println!("Wrote file") +} diff --git a/crates/vxls-production/src/sparse_tree.rs b/crates/vxls-production/src/sparse_tree.rs index d36dd84..d532dae 100644 --- a/crates/vxls-production/src/sparse_tree.rs +++ b/crates/vxls-production/src/sparse_tree.rs @@ -12,6 +12,10 @@ use crate::Attribute; #[repr(C)] pub struct Color(pub f32, pub f32, pub f32, pub f32); +#[derive(Debug, Clone, Copy, PartialEq, Default, Pod, Zeroable)] +#[repr(C)] +pub struct ColorByte(pub u32); + // `Attribute` requires `Eq`. `Color` is only ever constructed from finite, // non-NaN values in this crate, so equality is well-behaved here. impl Eq for Color {} @@ -43,6 +47,34 @@ impl Attribute for Color } } +impl Attribute for ColorByte +{ + fn average(attributes: &[Self]) -> Self + { + if attributes.is_empty() + { + return Self::default(); + } + + let mut c = Color::default(); + for color in attributes + { + let color = color.as_color(); + c.0 += color.0; + c.1 += color.1; + c.2 += color.2; + c.3 += color.3; + } + + let count = attributes.len() as f32; + c.0 /= count; + c.1 /= count; + c.2 /= count; + c.3 /= count; + ColorByte(c.as_packed_u32()) + } +} + impl Color { pub fn as_packed_u32(&self) -> u32 @@ -53,6 +85,23 @@ impl Color let mapped_a = (self.3 * 255.0).clamp(0., 255.0) as u32; mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24) } + + pub fn as_color_byte(&self) -> ColorByte + { + ColorByte(self.as_packed_u32()) + } +} + +impl ColorByte +{ + pub fn as_color(&self) -> Color + { + let r = (self.0 & 0xFF) as f32 / 255.0; + let g = ((self.0 >> 8) & 0xFF) as f32 / 255.0; + let b = ((self.0 >> 16) & 0xFF) as f32 / 255.0; + let a = ((self.0 >> 24) & 0xFF) as f32 / 255.0; + Color(r, g, b, a) + } } #[derive(Debug, Clone)] @@ -79,6 +128,21 @@ pub struct NTreeNode pub subdivided: bool, } +impl NTree +{ + /// Maximum voxel depth: the tree spans `N.pow(depth)` voxels per axis. + pub fn depth(&self) -> usize + { + self.depth + } + + /// Number of nodes currently stored, reachable from the root or not. + pub fn node_count(&self) -> usize + { + self.map.len() + } +} + impl NTree where [(); N * N * N]:, @@ -100,6 +164,26 @@ where self.set_at_depth(x, y, z, self.depth, value); } + pub fn mapped D>(&self, mut map: F) -> NTree + { + NTree:: { + map: self + .map + .iter() + .map(|(k, v)| { + ( + *k, + NTreeNode { + attribute: map(&v.attribute), + subdivided: v.subdivided, + }, + ) + }) + .collect(), + depth: self.depth, + } + } + pub fn get(&self, x: usize, y: usize, z: usize) -> T { assert!(x < N.pow(self.depth as u32)); @@ -375,6 +459,16 @@ where { self.map.get(&locator).copied() } + + /// Rebuilds a tree from raw nodes. + /// + /// Crate-private: the file reader is the only caller, and it is responsible + /// for maintaining the invariant that a subdivided node has all `N * N * N` + /// children. + pub(crate) fn from_nodes(map: HashMap, NTreeNode>, depth: usize) -> Self + { + Self { map, depth } + } } fn base_trailing_zeroes(mut number: usize) -> Option diff --git a/crates/vxls-production/tests/io.rs b/crates/vxls-production/tests/io.rs new file mode 100644 index 0000000..345b726 --- /dev/null +++ b/crates/vxls-production/tests/io.rs @@ -0,0 +1,675 @@ +//! End-to-end tests of the VXLS sparse-tree file format. + +#![feature(generic_const_exprs)] +#![allow(incomplete_features)] + +use std::io::Cursor; +use std::ops::Range; + +use bytemuck::{Pod, Zeroable}; +use vxls_production::Attribute; +use vxls_production::AttributeDescriptor; +use vxls_production::Attributes; +use vxls_production::AttributesLayout; +use vxls_production::io::TreeFileError; +use vxls_production::io::read_tree; +use vxls_production::io::write_tree; +use vxls_production::sparse_tree::NTree; + +const U32_LAYOUT: AttributesLayout = AttributesLayout::new(&[AttributeDescriptor::new("value", 1)]); +const PAIR_LAYOUT: AttributesLayout = AttributesLayout::new(&[AttributeDescriptor::new("pair", 2)]); +const WRONG_LAYOUT: AttributesLayout = + AttributesLayout::new(&[AttributeDescriptor::new("wrong", 2)]); + +fn encode(tree: &NTree, layout: AttributesLayout) -> Vec +where + [(); N * N * N]:, +{ + let mut cursor = Cursor::new(Vec::new()); + write_tree(&mut cursor, tree, layout).expect("write succeeds"); + cursor.into_inner() +} + +fn decode( + bytes: &[u8], + expected: Option, +) -> Result, TreeFileError> +where + [(); N * N * N]:, +{ + let mut cursor = Cursor::new(bytes); + read_tree::<_, N, T>(&mut cursor, expected).map(|file| file.tree) +} + +#[derive(Clone, Copy, Debug)] +struct Entry +{ + tag: u32, + offset: usize, + size: usize, + table_position: usize, +} + +impl Entry +{ + fn body(&self) -> Range + { + self.offset + 12..self.offset + self.size + } +} + +fn header_size(bytes: &[u8]) -> usize +{ + u32::from_le_bytes(bytes[24..28].try_into().unwrap()) as usize +} + +fn entries(bytes: &[u8]) -> Vec +{ + let header_size = header_size(bytes); + let table_position = 24 + header_size; + let table_size = + u32::from_le_bytes(bytes[table_position..table_position + 4].try_into().unwrap()) as usize; + let start = table_position + 4; + + (0..table_size / 24) + .map(|index| { + let base = start + index * 24; + Entry { + tag: u32::from_le_bytes(bytes[base..base + 4].try_into().unwrap()), + offset: u64::from_le_bytes(bytes[base + 8..base + 16].try_into().unwrap()) + as usize, + size: u64::from_le_bytes(bytes[base + 16..base + 24].try_into().unwrap()) as usize, + table_position: base, + } + }) + .collect() +} + +fn find_level(bytes: &[u8], level: u32) -> Entry +{ + entries(bytes) + .into_iter() + .find(|entry| entry.tag == 0x8000_0000 | level) + .expect("level chunk exists") +} + +fn patch_u32(bytes: &mut [u8], position: usize, value: u32) +{ + bytes[position..position + 4].copy_from_slice(&value.to_le_bytes()); +} + +fn recompute_crc(bytes: &mut [u8], entry: &Entry) +{ + let crc = crc32fast::hash(&bytes[entry.offset..entry.offset + entry.size]); + bytes[entry.offset + entry.size..entry.offset + entry.size + 4] + .copy_from_slice(&crc.to_le_bytes()); +} + +/// Renames a chunk in both the offset table and the frame, keeping the CRC valid. +fn rename_chunk(bytes: &mut [u8], entry: &Entry, tag: u32) +{ + patch_u32(bytes, entry.table_position, tag); + patch_u32(bytes, entry.offset, tag); + recompute_crc(bytes, &Entry { tag, ..*entry }); +} + +#[test] +fn constant_tree_roundtrip() +{ + let tree = NTree::<2, u32>::constant(7, 3); + let read = decode::<2, u32>(&encode(&tree, U32_LAYOUT), Some(U32_LAYOUT)).unwrap(); + + assert_eq!(read.depth(), 3); + assert_eq!(read.node_count(), 1); + assert_eq!(read.get(0, 0, 0), 7); + assert_eq!(read.get(7, 7, 7), 7); +} + +#[test] +fn one_voxel_roundtrip_matches_every_position() +{ + let mut tree = NTree::<2, u32>::constant(0, 1); + + for z in 0..2 + { + for y in 0..2 + { + for x in 0..2 + { + tree.set(x, y, z, 1 + (x + 2 * y + 4 * z) as u32); + } + } + } + + let read = decode::<2, u32>(&encode(&tree, U32_LAYOUT), Some(U32_LAYOUT)).unwrap(); + + for z in 0..2 + { + for y in 0..2 + { + for x in 0..2 + { + assert_eq!(read.get(x, y, z), tree.get(x, y, z), "voxel {x},{y},{z}"); + } + } + } +} + +#[test] +fn deep_tree_roundtrip() +{ + let mut tree = NTree::<2, u32>::constant(0, 4); + + for z in 0..16 + { + for y in 0..16 + { + for x in 0..16 + { + tree.set(x, y, z, (x * 31 + y * 17 + z * 7) as u32 % 23); + } + } + } + + let read = decode::<2, u32>(&encode(&tree, U32_LAYOUT), Some(U32_LAYOUT)).unwrap(); + + for z in 0..16 + { + for y in 0..16 + { + for x in 0..16 + { + assert_eq!(read.get(x, y, z), tree.get(x, y, z), "voxel {x},{y},{z}"); + } + } + } +} + +#[test] +fn arity_three_roundtrip() +{ + let mut tree = NTree::<3, u32>::constant(0, 2); + + for z in 0..9 + { + for y in 0..9 + { + for x in 0..9 + { + tree.set(x, y, z, ((x + y + z) % 5) as u32); + } + } + } + + let read = decode::<3, u32>(&encode(&tree, U32_LAYOUT), Some(U32_LAYOUT)).unwrap(); + + for z in 0..9 + { + for y in 0..9 + { + for x in 0..9 + { + assert_eq!(read.get(x, y, z), tree.get(x, y, z), "voxel {x},{y},{z}"); + } + } + } +} + +#[test] +fn shallow_tree_keeps_capacity_in_header() +{ + let tree = NTree::<2, u32>::constant(5, 4); + let read = decode::<2, u32>(&encode(&tree, U32_LAYOUT), None).unwrap(); + + assert_eq!(read.depth(), 4); + assert_eq!(read.node_count(), 1); + assert_eq!(read.get(15, 15, 15), 5); +} + +#[test] +fn from_array_roundtrip() +{ + let values: Vec = (0..64).map(|index| (index * 13 % 29) as u32).collect(); + let tree = NTree::<2, u32>::from_array(&values, 2); + let read = decode::<2, u32>(&encode(&tree, U32_LAYOUT), Some(U32_LAYOUT)).unwrap(); + + for z in 0..4 + { + for y in 0..4 + { + for x in 0..4 + { + assert_eq!(read.get(x, y, z), tree.get(x, y, z), "voxel {x},{y},{z}"); + } + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable, Attributes)] +#[repr(C)] +struct Payload +{ + #[attribute(label = "color", semantic = "color")] + color: u32, + + #[attribute(label = "normal", semantic = "normal")] + normal: [f32; 3], +} + +#[test] +fn multi_attribute_roundtrip() +{ + let mut tree = NTree::<2, Payload>::constant(Payload::default(), 2); + + for z in 0..4 + { + for y in 0..4 + { + for x in 0..4 + { + tree.set( + x, + y, + z, + Payload { + color: (x + 4 * y + 16 * z) as u32, + normal: [x as f32, y as f32, z as f32], + }, + ); + } + } + } + + let bytes = encode(&tree, Payload::LAYOUT); + let mut cursor = Cursor::new(&bytes); + let file = read_tree::<_, 2, Payload>(&mut cursor, Some(Payload::LAYOUT)).unwrap(); + + assert_eq!(file.layout.attributes.len(), 2); + assert_eq!(file.layout.attributes[0].label, "color"); + assert_eq!(file.layout.attributes[0].word_count, 1); + assert_eq!(file.layout.attributes[1].label, "normal"); + assert_eq!(file.layout.attributes[1].word_count, 3); + + for z in 0..4 + { + for y in 0..4 + { + for x in 0..4 + { + assert_eq!(file.tree.get(x, y, z), tree.get(x, y, z)); + } + } + } +} + +#[test] +fn write_rejects_layout_size_mismatch() +{ + let tree = NTree::<2, u32>::constant(0, 1); + let mut cursor = Cursor::new(Vec::new()); + + assert!(matches!( + write_tree(&mut cursor, &tree, PAIR_LAYOUT), + Err(TreeFileError::LayoutSizeMismatch { .. }) + )); +} + +#[test] +fn write_rejects_empty_layout() +{ + let tree = NTree::<2, u32>::constant(0, 1); + let mut cursor = Cursor::new(Vec::new()); + + assert!(matches!( + write_tree(&mut cursor, &tree, AttributesLayout::EMPTY), + Err(TreeFileError::EmptyLayout) + )); +} + +#[test] +fn write_rejects_zero_word_count() +{ + const ZERO: AttributesLayout = AttributesLayout::new(&[AttributeDescriptor::new("zero", 0)]); + + let tree = NTree::<2, u32>::constant(0, 1); + let mut cursor = Cursor::new(Vec::new()); + + assert!(matches!( + write_tree(&mut cursor, &tree, ZERO), + Err(TreeFileError::InvalidWordCount { index: 0, .. }) + )); +} + +#[test] +fn rejects_bad_magic() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + bytes[0] = b'X'; + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::BadMagic { .. }) + )); +} + +#[test] +fn rejects_bad_file_type() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + bytes[4] = b'X'; + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::BadFileType { .. }) + )); +} + +#[test] +fn rejects_unsupported_major_version() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + patch_u32(&mut bytes, 8, 99); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::UnsupportedVersion { major: 99, .. }) + )); +} + +#[test] +fn accepts_newer_minor_version() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(3, 1), U32_LAYOUT); + patch_u32(&mut bytes, 12, 7); + + let tree = decode::<2, u32>(&bytes, None).unwrap(); + assert_eq!(tree.get(0, 0, 0), 3); +} + +#[test] +fn rejects_file_size_mismatch() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + bytes.pop(); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::FileSizeMismatch { .. }) + )); +} + +#[test] +fn rejects_arity_mismatch() +{ + let bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + + assert!(matches!( + decode::<3, u32>(&bytes, None), + Err(TreeFileError::ArityMismatch { + file: 2, + requested: 3 + }) + )); +} + +#[test] +fn rejects_small_header() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + patch_u32(&mut bytes, 24, 4); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::HeaderTooSmall { header_size: 4 }) + )); +} + +#[test] +fn rejects_excessive_depth() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + patch_u32(&mut bytes, 32, 31); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::DepthTooLarge { depth: 31, .. }) + )); +} + +#[test] +fn rejects_misaligned_offset_table_entry() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + let entry = entries(&bytes)[0]; + patch_u32(&mut bytes, entry.table_position + 8, entry.offset as u32 + 1); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::MisalignedOffset { .. }) + )); +} + +#[test] +fn rejects_duplicate_chunk_tag() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + let first = entries(&bytes)[0]; + let second = entries(&bytes)[1]; + patch_u32(&mut bytes, second.table_position, first.tag); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::DuplicateChunk { .. }) + )); +} + +#[test] +fn rejects_non_zero_padding() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + let entries = entries(&bytes); + + let gap = entries + .windows(2) + .find_map(|pair| { + let end = pair[0].offset + pair[0].size + 4; + (end < pair[1].offset).then_some(end) + }) + .expect("the writer leaves at least one padding byte"); + + bytes[gap] = 1; + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::NonZeroPadding { .. }) + )); +} + +#[test] +fn rejects_wrong_frame_tag() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + let entry = entries(&bytes)[0]; + patch_u32(&mut bytes, entry.offset, entry.tag + 100); + recompute_crc(&mut bytes, &entry); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::ChunkTagMismatch { .. }) + )); +} + +#[test] +fn rejects_bad_crc() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + let entry = find_level(&bytes, 0); + let body = entry.body(); + bytes[body.start + 4] ^= 0xFF; + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::CrcMismatch { .. }) + )); +} + +#[test] +fn rejects_invalid_utf8_label() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + let entry = entries(&bytes)[0]; + let body = entry.body(); + // count, word_count, label_size, then the label bytes. + bytes[body.start + 12] = 0xFF; + recompute_crc(&mut bytes, &entry); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::Binrw(_)) + )); +} + +#[test] +fn rejects_layout_mismatch() +{ + let bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + + assert!(matches!( + decode::<2, u32>(&bytes, Some(WRONG_LAYOUT)), + Err(TreeFileError::LayoutMismatch { .. }) + )); +} + +#[test] +fn rejects_layout_size_mismatch() +{ + let tree = NTree::<2, [u32; 2]>::constant([1, 2], 1); + let bytes = encode(&tree, PAIR_LAYOUT); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::LayoutSizeMismatch { .. }) + )); +} + +#[test] +fn rejects_trailing_bytes() +{ + let mut bytes = encode(&NTree::<2, u32>::constant(0, 0), U32_LAYOUT); + bytes.push(0); + let length = bytes.len() as u64; + bytes[16..24].copy_from_slice(&length.to_le_bytes()); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::TrailingBytes { .. }) + )); +} + +#[test] +fn rejects_missing_level_chunk() +{ + let mut tree = NTree::<2, u32>::constant(0, 2); + tree.set(0, 0, 0, 1); + tree.set(2, 0, 0, 2); + + let mut bytes = encode(&tree, U32_LAYOUT); + + assert_eq!(find_level(&bytes, 2).tag, 0x8000_0002); + + let entry = find_level(&bytes, 1); + rename_chunk(&mut bytes, &entry, 2); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::MissingLevelChunk { level: 1 }) + )); +} + +#[test] +fn rejects_node_count_mismatch() +{ + let mut tree = NTree::<2, u32>::constant(0, 2); + tree.set(0, 0, 0, 1); + tree.set(2, 0, 0, 2); + + let mut bytes = encode(&tree, U32_LAYOUT); + let level_one = find_level(&bytes, 1); + let level_two = find_level(&bytes, 2); + + // Swap the two tags: level 1 now points at a body declaring 16 nodes while + // its parents imply only 8. + rename_chunk(&mut bytes, &level_one, 0x8000_0002); + rename_chunk(&mut bytes, &level_two, 0x8000_0001); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::NodeCountMismatch { level: 1, .. }) + )); +} + +#[test] +fn rejects_subdivision_at_deepest_level() +{ + let mut tree = NTree::<2, u32>::constant(0, 1); + tree.set(0, 0, 0, 1); + + let mut bytes = encode(&tree, U32_LAYOUT); + let entry = find_level(&bytes, 1); + let body = entry.body(); + + // First body word is node_count; the mask follows. + bytes[body.start + 4] |= 1; + recompute_crc(&mut bytes, &entry); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::SubdividedAtDeepestLevel { level: 1 }) + )); +} + +#[test] +fn rejects_non_zero_unused_flag_bits() +{ + let mut tree = NTree::<2, u32>::constant(0, 1); + tree.set(0, 0, 0, 1); + + let mut bytes = encode(&tree, U32_LAYOUT); + let entry = find_level(&bytes, 1); + let body = entry.body(); + + // 8 nodes use the low 8 bits; bit 9 is unused and must stay clear. + bytes[body.start + 5] |= 1 << 1; + recompute_crc(&mut bytes, &entry); + + assert!(matches!( + decode::<2, u32>(&bytes, None), + Err(TreeFileError::TrailingFlagBits { level: 1 }) + )); +} + +#[test] +fn file_path_helpers_roundtrip() +{ + let directory = std::env::temp_dir().join(format!( + "vxls-io-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&directory).unwrap(); + let path = directory.join("tree.vxls"); + + let mut tree = NTree::<2, u32>::constant(0, 2); + tree.set(1, 2, 3, 42); + + vxls_production::io::write_tree_to_path(&path, &tree, U32_LAYOUT).unwrap(); + let file = + vxls_production::io::read_tree_from_path::<_, 2, u32>(&path, Some(U32_LAYOUT)).unwrap(); + + assert_eq!(file.tree.get(1, 2, 3), 42); + + std::fs::remove_dir_all(&directory).unwrap(); +}