d3d12: expand the packed bottom-level structures a title ships #536

Merged
3kynox merged 2 commits from upstream-pr/536 into main 2026-12-01 15:21:27 +00:00
3kynox commented 2026-11-29 21:03:56 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by 3kynox on 2026-11-29T21:03:56Z.


Summary

For #382, the static bottom-level structures. A title streams them in a packed form and asks the console's builder library to expand each in place; the walks then read the expanded records. packed_structure::unpack does that expansion: it takes the packed bytes and the triangles the build names, and returns the structure the title's ray-walk shaders read.

Nothing calls it yet, so behaviour does not change. The buffer the structures go into and the wiring to the builds and dispatches follow in two more PRs; this one is the expansion and its tests alone, so it can be reviewed by itself.

Rebased onto 8ece312f as a fresh commit: formatted, and clean under the lints main now denies. Eight integer conversions were rewritten for that (a mask before each narrowing, cast_signed/cast_unsigned in the half-float rounding, one try_from on a masked offset); none changes a bit, and the comparison with the library below was run again on this code. The row this PR first added to docs/REFERENCES.md is gone with the table (9acdc888); the module comment now names the revision of the public source instead.

Where it comes from:

  • the packing is the one Leonida's docs/bvh.md describes (sections 3.1 and 4a), already cited in rehydrate.rs. Its repository is offline today; ProjectLeonida/mandy carries the document;
  • the expanded records (header and its flags, 64- and 128-byte box nodes, leaf) are those of the public console traversal source, as Dagor Engine publishes it at revision 9639942;
  • the slots the order byte of a two-triangle leaf selects: Leonida's document says the byte selects them without giving the rule. I read the rule in the rehydrator of the port-of-the-americas project (AGPL-3.0, revision 0f3be36, repository offline today), took no code from it, and then gave the library every order byte: all 36 orders come out the same. A comment in the code says so.

Where those are silent, what the library does was measured off the game: the title's own XboxBvhBuilder.dll has a rehydration entry that runs on the CPU and needs no device, so the same packed bytes and geometry can be given to it and to unpack under Wine, and every byte compared. That harness loads the title's library and stays on my machine. What it showed, and the code follows:

  • a leaf of one triangle keeps its corners in order, whatever its vertex-order byte says; the byte is still copied;
  • a 64-byte box node rounds its bounds outwards to halves as IEEE 754 directs, subnormal halves included; past the largest half the outward side is infinite;
  • a leaf at the root gets no entry in the parent table;
  • a geometry's own transform is joined to the leaf frame before a position goes through it, and each row adds its products in pairs. One after the other is off by an ulp or two on a turned geometry;
  • any frame word but 0x007f7f7f brings a negative zero out positive.

Review fix, 4631d10b. A child pointer and the root are now held to a box node of their own size at the place it begins: a 128-byte pointer to two 64-byte nodes, or a pointer into the middle of a 128-byte node, was expanded as if it named a node. The comparison below was run again on this commit: the 103 structures compared come out as before. The game has not run on this commit yet.

Results, on this code

  • 33 hand-built packed structures (one leaf to 20,000, pairs, stored bounds, both node sizes, scaled and moved frames): byte-identical to the library. Four more with a turned frame are refused, as before.
  • 70 structures captured from a game run with their geometry (2,626,240 bytes): byte-identical to the library. All have a scaled frame, 13 a moved one (on one or two axes), and 39 a geometry with its own transform.

In the game, called from a local build that reads the geometry on the CPU at the rehydration call:

  • on 1474b05e, before the review fix, with the two PRs that follow and #566 on top: in a 9-minute run, the structures the title rehydrated were all expanded and placed, 485 by the last count, none refused. That run ended on a GPU loss a minute into the world, in mesh-shader draws; a run without the switch that turns all this on went 25 minutes. I can't tell yet whether the two are related; more runs come before the wiring PR does;

  • before the rebase, with the code as it was but for the eight conversions:

    • an 8-minute run expanded and placed 904 structures by its last count, none refused;
    • a 15-minute run with an earlier revision, the same but for how a geometry's own transform is applied (the fourth point above, found from that run's captures), expanded all 1,340 the title rehydrated (1,376,703 leaves), none refused. All were version 6 with a 64-byte box at the root and a scaled frame; 136 were also moved.

Not handled:

  • a turned leaf frame (bits 24 to 29 of the frame word) is refused. None of the 1,340 structures has one, and I could not reproduce the library's rounding for it;
  • a leaf of two triangles whose order byte is not an order (a field of 3, or the same field twice for one triangle) is refused. The library writes something for some of those; the 1,120,912 leaves of two triangles in the run use nine order bytes, all of them orders;
  • compressed and updatable structures are refused; the title's archives hold none (Leonida, 3.1).

When the library expands a structure in place, as the title asks, the level table stays at the end of the structure. unpack leaves zeros there, as the library does when its destination is another buffer. No walk reads it.

Tested

Run the checks relevant to this change.

  • The checks relevant to this change passed: the code checks did, except one Python test of the launcher that fails the same way on main on this machine (below)
  • Changed or new behaviour is covered by a Lanes scenario, or the reason it cannot be is stated below
  • Where the table calls for AMD and NVIDIA, they passed on both. Otherwise, say which vendor still needs to run them: none of the GPU suites was run, on either vendor. Nothing calls the function and nothing in it runs on a GPU, so they have nothing of it to exercise.

No Lanes scenario: the function is not called by the provider yet. It has twelve unit tests on packed structures built by hand in the test file (no title data). 77 errors planted in the expansion one at a time (a corner in the wrong slot, halves rounded inwards, the frame's move left out, a missing parent entry, a pointer of the other size accepted, products added one after the other and so on): 75 fail at least one test. The other two change nothing a caller could see: bounding the fourth corner of a one-triangle leaf (it is not a number, and a bound ignores those), and expanding a level's 64-byte nodes before its 128-byte ones (neither reads the other).

GPU, driver and backend: none needed for the checks below. The game runs above: GeForce RTX 4070 Ti SUPER, 620.73.04, GE-Proton11-14, Core i9-12900K, ProjectScarlett 1.0.2.1 offline.

The Evidence: line tuxbox.py check prints last, one per card (it names the commit it tested; run it on this pull request's head):

Evidence: TuxBox check of 4631d10be3b8, no uncommitted changes, no GPU checks: 12 passed, 1 failed, 0 not run

Everything below was run on the head commit, 4631d10b.

Commands run and their results:

python tuxbox.py check --no-gpu        (Rust 1.98.1: the nearest toolchain I have to CI's 1.95)
  passed   Build the shader compiler
  FAILED   Python tests: 759 ran, 1 failed, 10 skipped
           test_stage_baseline.GuestWatch.test_a_guest_that_died_stops_the_sandbox_instead_of_waiting_out_the_timeout
           It fails the same way on main (checked at e5d2e913) without this change on this machine (NixOS), as noted in #486.
  passed   Synthetic shaders through the runtime's DXC flags
  passed   Shader compiler tests
  passed   DXBC tests
  passed   XG layout tests
  passed   XG entry point tests
  passed   BVH layout tests
  passed   Storage codec tests
  passed   ACP HAL tests
  passed   Windows typecheck
  passed   Clippy
  passed   Formatting

RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --target x86_64-pc-windows-msvc -p tuxbox-d3d12 --document-private-items
  no warning

cargo test --target x86_64-pc-windows-msvc -p tuxbox-d3d12 --lib   (run under Wine)
  477 passed, 3 failed, 8 ignored
  The failures are scene_publication tests this PR does not touch; they ask for a hardware device my Wine prefix does not give them.

cargo +nightly-2026-11-03 miri test --locked --target x86_64-pc-windows-msvc --lib -p tuxbox-d3d12 -- packed_structure   (CI's MIRIFLAGS)
  12 passed, 0 failed, in 27 s. I ran Miri on this module's tests only, not on the whole crate.

Checks

CI runs the Python unit tests, the shader compiler, DXBC, and XG layout tests, a Windows typecheck of every crate, and clippy.

<!-- greyfinch-sync:brcly/TuxBox:issue:5555098201 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/536). Originally posted by [3kynox](https://github.com/3kynox) on 2026-11-29T21:03:56Z. --- ## Summary For #382, the static bottom-level structures. A title streams them in a packed form and asks the console's builder library to expand each in place; the walks then read the expanded records. `packed_structure::unpack` does that expansion: it takes the packed bytes and the triangles the build names, and returns the structure the title's ray-walk shaders read. **Nothing calls it yet, so behaviour does not change.** The buffer the structures go into and the wiring to the builds and dispatches follow in two more PRs; this one is the expansion and its tests alone, so it can be reviewed by itself. **Rebased onto 8ece312f** as a fresh commit: formatted, and clean under the lints `main` now denies. Eight integer conversions were rewritten for that (a mask before each narrowing, `cast_signed`/`cast_unsigned` in the half-float rounding, one `try_from` on a masked offset); none changes a bit, and the comparison with the library below was run again on this code. The row this PR first added to `docs/REFERENCES.md` is gone with the table (9acdc888); the module comment now names the revision of the public source instead. Where it comes from: - the packing is the one Leonida's `docs/bvh.md` describes (sections 3.1 and 4a), already cited in `rehydrate.rs`. Its repository is offline today; `ProjectLeonida/mandy` carries the document; - the expanded records (header and its flags, 64- and 128-byte box nodes, leaf) are those of the public console traversal source, as Dagor Engine publishes it at revision 9639942; - the slots the order byte of a two-triangle leaf selects: Leonida's document says the byte selects them without giving the rule. I read the rule in the rehydrator of the port-of-the-americas project (AGPL-3.0, revision 0f3be36, repository offline today), took no code from it, and then gave the library every order byte: all 36 orders come out the same. A comment in the code says so. Where those are silent, what the library does was measured off the game: the title's own `XboxBvhBuilder.dll` has a rehydration entry that runs on the CPU and needs no device, so the same packed bytes and geometry can be given to it and to `unpack` under Wine, and every byte compared. That harness loads the title's library and stays on my machine. What it showed, and the code follows: - a leaf of one triangle keeps its corners in order, whatever its vertex-order byte says; the byte is still copied; - a 64-byte box node rounds its bounds outwards to halves as IEEE 754 directs, subnormal halves included; past the largest half the outward side is infinite; - a leaf at the root gets no entry in the parent table; - a geometry's own transform is joined to the leaf frame before a position goes through it, and each row adds its products in pairs. One after the other is off by an ulp or two on a turned geometry; - any frame word but `0x007f7f7f` brings a negative zero out positive. **Review fix, 4631d10b.** A child pointer and the root are now held to a box node of their own size at the place it begins: a 128-byte pointer to two 64-byte nodes, or a pointer into the middle of a 128-byte node, was expanded as if it named a node. The comparison below was run again on this commit: the 103 structures compared come out as before. The game has not run on this commit yet. **Results, on this code** - 33 hand-built packed structures (one leaf to 20,000, pairs, stored bounds, both node sizes, scaled and moved frames): byte-identical to the library. Four more with a turned frame are refused, as before. - 70 structures captured from a game run with their geometry (2,626,240 bytes): byte-identical to the library. All have a scaled frame, 13 a moved one (on one or two axes), and 39 a geometry with its own transform. **In the game**, called from a local build that reads the geometry on the CPU at the rehydration call: - on 1474b05e, before the review fix, with the two PRs that follow and #566 on top: in a 9-minute run, the structures the title rehydrated were all expanded and placed, 485 by the last count, none refused. That run ended on a GPU loss a minute into the world, in mesh-shader draws; a run without the switch that turns all this on went 25 minutes. I can't tell yet whether the two are related; more runs come before the wiring PR does; - before the rebase, with the code as it was but for the eight conversions: - an 8-minute run expanded and placed 904 structures by its last count, none refused; - a 15-minute run with an earlier revision, the same but for how a geometry's own transform is applied (the fourth point above, found from that run's captures), expanded all 1,340 the title rehydrated (1,376,703 leaves), none refused. All were version 6 with a 64-byte box at the root and a scaled frame; 136 were also moved. **Not handled:** - a turned leaf frame (bits 24 to 29 of the frame word) is refused. None of the 1,340 structures has one, and I could not reproduce the library's rounding for it; - a leaf of two triangles whose order byte is not an order (a field of 3, or the same field twice for one triangle) is refused. The library writes something for some of those; the 1,120,912 leaves of two triangles in the run use nine order bytes, all of them orders; - compressed and updatable structures are refused; the title's archives hold none (Leonida, 3.1). When the library expands a structure in place, as the title asks, the level table stays at the end of the structure. `unpack` leaves zeros there, as the library does when its destination is another buffer. No walk reads it. ## Tested Run the [checks relevant to this change](../CONTRIBUTING.md#test-what-your-change-touches). - [ ] The checks relevant to this change passed: the code checks did, except one Python test of the launcher that fails the same way on `main` on this machine (below) - [x] Changed or new behaviour is covered by a Lanes scenario, or the reason it cannot be is stated below - [ ] Where the table calls for AMD and NVIDIA, they passed on both. Otherwise, say which vendor still needs to run them: none of the GPU suites was run, on either vendor. Nothing calls the function and nothing in it runs on a GPU, so they have nothing of it to exercise. No Lanes scenario: the function is not called by the provider yet. It has twelve unit tests on packed structures built by hand in the test file (no title data). 77 errors planted in the expansion one at a time (a corner in the wrong slot, halves rounded inwards, the frame's move left out, a missing parent entry, a pointer of the other size accepted, products added one after the other and so on): 75 fail at least one test. The other two change nothing a caller could see: bounding the fourth corner of a one-triangle leaf (it is not a number, and a bound ignores those), and expanding a level's 64-byte nodes before its 128-byte ones (neither reads the other). GPU, driver and backend: none needed for the checks below. The game runs above: GeForce RTX 4070 Ti SUPER, 620.73.04, GE-Proton11-14, Core i9-12900K, ProjectScarlett 1.0.2.1 offline. The `Evidence:` line `tuxbox.py check` prints last, one per card (it names the commit it tested; run it on this pull request's head): ```text Evidence: TuxBox check of 4631d10be3b8, no uncommitted changes, no GPU checks: 12 passed, 1 failed, 0 not run ``` Everything below was run on the head commit, 4631d10b. Commands run and their results: ```text python tuxbox.py check --no-gpu (Rust 1.98.1: the nearest toolchain I have to CI's 1.95) passed Build the shader compiler FAILED Python tests: 759 ran, 1 failed, 10 skipped test_stage_baseline.GuestWatch.test_a_guest_that_died_stops_the_sandbox_instead_of_waiting_out_the_timeout It fails the same way on main (checked at e5d2e913) without this change on this machine (NixOS), as noted in #486. passed Synthetic shaders through the runtime's DXC flags passed Shader compiler tests passed DXBC tests passed XG layout tests passed XG entry point tests passed BVH layout tests passed Storage codec tests passed ACP HAL tests passed Windows typecheck passed Clippy passed Formatting RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --target x86_64-pc-windows-msvc -p tuxbox-d3d12 --document-private-items no warning cargo test --target x86_64-pc-windows-msvc -p tuxbox-d3d12 --lib (run under Wine) 477 passed, 3 failed, 8 ignored The failures are scene_publication tests this PR does not touch; they ask for a hardware device my Wine prefix does not give them. cargo +nightly-2026-11-03 miri test --locked --target x86_64-pc-windows-msvc --lib -p tuxbox-d3d12 -- packed_structure (CI's MIRIFLAGS) 12 passed, 0 failed, in 27 s. I ran Miri on this module's tests only, not on the whole crate. ``` ## Checks CI runs the Python unit tests, the shader compiler, DXBC, and XG layout tests, a Windows typecheck of every crate, and clippy.
brcly commented 2026-11-30 04:12:17 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by brcly on 2026-11-30T04:12:17Z.


Heads-up: main just landed a large cleanup (up to e5d2e913), so this PR needs a rebase.

  • Formatting: the whole workspace is now formatted with rustfmt (see the new rustfmt.toml).
  • Lints: every crate denies unwrap(), lossy as casts and undocumented unsafe outside tests.
  • CI: it now also runs cargo fmt --check, rustdoc with warnings denied, and Miri on the providers' unit tests.

The least painful way is to format your branch first, so the rebase only shows real changes:

git fetch origin
git checkout origin/main -- rustfmt.toml
cargo fmt --all && git commit -am "rustfmt"
git rebase origin/main

Then run python tuxbox.py check --no-gpu, which now includes the format step.

If clippy flags something new:

  • A cast: use From for widening, TryFrom for narrowing, and a mask for bit fields.
  • An unwrap(): use ?, or expect with the reason it can't fail.
  • An unsafe block: it needs a // SAFETY: comment.

CONTRIBUTING's "Code checks" section lists the commands. Thanks!

<!-- greyfinch-sync:brcly/TuxBox:comment:7268561786 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/536#issuecomment-7268561786). Originally posted by [brcly](https://github.com/brcly) on 2026-11-30T04:12:17Z. --- Heads-up: main just landed a large cleanup (up to e5d2e913), so this PR needs a rebase. - **Formatting:** the whole workspace is now formatted with rustfmt (see the new `rustfmt.toml`). - **Lints:** every crate denies `unwrap()`, lossy `as` casts and undocumented `unsafe` outside tests. - **CI:** it now also runs `cargo fmt --check`, rustdoc with warnings denied, and Miri on the providers' unit tests. The least painful way is to format your branch first, so the rebase only shows real changes: ```sh git fetch origin git checkout origin/main -- rustfmt.toml cargo fmt --all && git commit -am "rustfmt" git rebase origin/main ``` Then run `python tuxbox.py check --no-gpu`, which now includes the format step. If clippy flags something new: - **A cast:** use `From` for widening, `TryFrom` for narrowing, and a mask for bit fields. - **An `unwrap()`:** use `?`, or `expect` with the reason it can't fail. - **An `unsafe` block:** it needs a `// SAFETY:` comment. CONTRIBUTING's "Code checks" section lists the commands. Thanks!
Copilot commented 2026-11-30 10:44:27 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by Copilot on 2026-11-30T10:44:27Z.

Code review location: runtime/d3d12/src/commands/build_raytracing/packed_structure.rs; line 447

@@ -0,0 +1,610 @@
+//! Console bottom-level structures in the packed form a title ships.
+//!
+//! A title streams its static bottom-level structures packed and has the
+//! console's builder library expand each one in place before a ray walks it.
+//! The packed form keeps the tree and leaves out what the geometry gives
+//! back: a leaf is 11 bytes naming its triangles, and a box node is its child
+//! pointers and the few bounds that cannot be recomputed. `unpack` writes the
+//! form the title's own ray-walk shaders read.
+//!
+//! The expanded records are those of the public traversal source
+//! (`XboxBvh4Header`, `Node16`, `Node32` and `Leaf` in
+//! `XDXRStandaloneTraverseShortStackCPU.hlsli`, as Dagor Engine publishes it
+//! at revision 9639942). The packing is the one
+//! Leonida's `docs/bvh.md` measured on the title's archives (sections 3.1 and
+//! 4a), where a model of it wrote the library's own bytes:
+//!
+//! - The 64-byte header stays, without its packed flag. A structure spans
+//!   `64 * (nodes + 1)` bytes: the header's node count leaves the header out.
+//! - Leaves start at the header's element offset and are 64 bytes each once
+//!   expanded. Packed, every run of 2,048 leaves begins with five arrays of
+//!   one entry per leaf: geometry index (3 bytes), flags (1), first primitive
+//!   (3), second primitive (3, `0xffffff` for none) and vertex order (1).
+//! - Box nodes start at the header's node offset, level by level from the
+//!   leaves up. The structure ends with a count of levels, preceded by one
+//!   pair per level: where its 128-byte nodes end and where its 64-byte nodes
+//!   end. Packed, every run of 64 nodes begins with one word per node (child
+//!   count in the top byte, then a 24-bit mask), then every child pointer,
+//!   then one stored bound per mask bit.
+//! - The parent table lies between the header and the leaves, one word per
+//!   64 bytes counted from the first leaf. It is empty when packed.
+//!
+//! A node pointer is its offset from the header in 8-byte steps, with the
+//! node's kind in the three low bits.
+//!
+//! Where those descriptions are silent, what the library does was measured
+//! off the game, by giving the title's own builder library and `unpack` the
+//! same packed bytes and the same geometry and comparing every byte:
+//!
+//! - a leaf of one triangle keeps its corners in order, whatever its vertex
+//!   order says;
+//! - a 64-byte box node rounds its bounds outwards to halves as IEEE 754
+//!   directs, subnormal halves included;
+//! - a leaf at the root gets no entry in the parent table;
+//! - a geometry's own transform is joined to the leaf frame before a
+//!   position goes through, and a row adds its products in pairs.
+// Not called outside the tests until the structures are placed for the walks.
+#![cfg_attr(not(test), allow(dead_code))]
+
+const UNIT: usize = 64;
+const WIDE: usize = 128;
+const LEAVES_IN_RUN: usize = 2048;
+const NODES_IN_RUN: usize = 64;
+/// Larger structures are refused rather than expanded.
+const LIMIT: usize = 256 << 20;
+
+const VERSION: u32 = 6;
+const BOTTOM_LEVEL: u32 = 0x8000_0000;
+const PACKED: u32 = 0x0100_0000;
+/// Forms no archive of the title holds: compressed, updatable, or with
+/// bounds of more than three axes.
+const UNSEEN: u32 = 0x00f5_0000;
+/// The leaf flag for a second triangle.
+const PAIR: u32 = 0x80;
+
+const TRIANGLE: u32 = 0;
+const BOX16: u32 = 4;
+const BOX32: u32 = 5;
+const NO_NODE: u32 = u32::MAX;
+const NO_PRIMITIVE: u32 = 0x00ff_ffff;
+
+/// A triangle's corners in the order its index buffer names them, as its
+/// geometry's buffers hold them: before the geometry's own transform.
+pub(super) type Triangle = [[f32; 3]; 3];
+/// A geometry's transform: three rows of four.
+pub(super) type Transform = [f32; 12];
+
+fn word(bytes: &[u8], at: usize) -> Option<u32> {
+    Some(u32::from_le_bytes(bytes.get(at..at.checked_add(4)?)?.try_into().ok()?))
+}
+
+/// A three-byte entry of a packed leaf array.
+fn triple(bytes: &[u8], at: usize) -> Option<u32> {
+    let entry = bytes.get(at..at.checked_add(3)?)?;
+    Some(u32::from(entry[0]) | u32::from(entry[1]) << 8 | u32::from(entry[2]) << 16)
+}
+
+fn put(out: &mut [u8], at: usize, bytes: &[u8]) -> Option<()> {
+    out.get_mut(at..at.checked_add(bytes.len())?)?.copy_from_slice(bytes);
+    Some(())
+}
+
+/// The low 32 bits of an offset. Offsets inside a structure fit, and the
+/// library counts in 32-bit words where one does not.
+fn low(offset: usize) -> u32 {
+    u32::try_from(offset & 0xffff_ffff).expect("masked to 32 bits")
+}
+
+fn pointer(at: usize, kind: u32) -> u32 {
+    low(at / 8) | kind
+}
+
+fn target(pointer: u32) -> usize {
+    (pointer >> 3) as usize * UNIT
+}
+
+struct Header {
+    flags: u32,
+    /// The whole structure, header included.
+    bytes: usize,
+    leaves: usize,
+    bounds: [f32; 6],
+    boxes_at: usize,
+    root: u32,
+    leaves_at: usize,
+    parents_at: u32,
+    frame: u32,
+}
+
+impl Header {
+    fn read(packed: &[u8]) -> Result<Self, &'static str> {
+        let field = |at| word(packed, at).ok_or("shorter than a header");
+        let flags = field(0)?;
+        if flags & 0xffff != VERSION || flags & BOTTOM_LEVEL == 0 {
+            return Err("not a bottom-level structure of the known version");
+        }
+        if flags & PACKED == 0 {
+            return Err("not packed");
+        }
+        // The word at 44 would lead to a table that renumbers the primitives.
+        if flags & UNSEEN != 0 || field(44)? != 0 {
+            return Err("a form no archive holds");
+        }
+        let bytes = (field(4)? as usize + 1)
+            .checked_mul(UNIT)
+            .filter(|&bytes| bytes <= packed.len().min(LIMIT))
+            .ok_or("larger than the bytes given")?;
+        let header = Self {
+            flags,
+            bytes,
+            leaves: field(12)? as usize,
+            bounds: core::array::from_fn(|index| f32::from_bits(word(packed, 16 + 4 * index).unwrap_or(0))),
+            boxes_at: field(40)? as usize,
+            root: field(48)?,
+            leaves_at: field(52)? as usize,
+            parents_at: field(56)?,
+            frame: field(60)?,
+        };
+        let leaves_end = header.leaves.checked_mul(UNIT).and_then(|span| span.checked_add(header.leaves_at));
+        if header.leaves == 0
+            || header.leaves_at < UNIT
+            || !header.leaves_at.is_multiple_of(UNIT)
+            || leaves_end.is_none_or(|end| end > bytes)
+        {
+            return Err("leaves outside the structure");
+        }
+        Ok(header)
+    }
+
+    /// Where the parent table holds the entry of the node at `at`, when it
+    /// holds one: the table ends where the leaves begin.
+    fn parent_entry(&self, at: usize) -> Option<usize> {
+        let unit = low(at).wrapping_sub(low(self.leaves_at)) >> 6;
+        let entry = self.parents_at.wrapping_add(unit.wrapping_mul(4)) as usize;
+        (entry >= UNIT && entry + 4 <= self.leaves_at).then_some(entry)
+    }
+}
+
+/// The space the leaves' corners are stored in, from the header's last word:
+/// `(v - middle) * scale`. Bit 31 scales each axis by a power of two, whose
+/// exponents are the three low bytes. Bit 30 moves the middle of the header's
+/// bounds to zero on each axis they do not straddle. Bits 24 to 29 would turn
+/// the positions. No structure seen so far sets them, and how the library
+/// rounds a turn is not established, so such a structure is refused.
+///
+/// The word `0x007f7f7f` alone leaves positions as they are. Any other goes
+/// through the arithmetic, which the library writes so that a negative zero
+/// comes out positive.
+struct Frame {
+    /// What is added to a position: minus the middle, or zero.
+    moved: [f32; 3],
+    scale: [f32; 3],
+    plain: bool,
+}
+
+impl Frame {
+    const PLAIN: u32 = 0x007f_7f7f;
+
+    fn new(word: u32, bounds: &[f32; 6]) -> Result<Self, &'static str> {
+        let (scaled, shifted, turned) = (word >> 31 != 0, word >> 30 & 1 != 0, word >> 24 & 0x3f != 0);
+        if turned {
+            return Err("a turned leaf frame, not seen so far");
+        }
+        Ok(Self {
+            moved: core::array::from_fn(|axis| {
+                let (low, high) = (bounds[axis], bounds[3 + axis]);
+                if shifted && (low > 0.0 || high < 0.0) { -((low + high) * 0.5) } else { 0.0 }
+            }),
+            scale: core::array::from_fn(
+                |axis| if scaled { f32::from_bits((word >> (8 * axis) & 0xff) << 23) } else { 1.0 },
+            ),
+            plain: word == Self::PLAIN,
+        })
+    }
+
+    fn place(&self, v: [f32; 3]) -> [f32; 3] {
+        if self.plain {
+            return v;
+        }
+        core::array::from_fn(|axis| (v[axis] + self.moved[axis]) * self.scale[axis])
+    }
+
+    /// The rows that take a position through a geometry's transform and then
+    /// into this frame. The library joins the two before it touches a
+    /// position, which rounds differently from one after the other.
+    fn after(&self, transform: &Transform) -> Transform {
+        core::array::from_fn(|at| {
+            let (axis, column) = (at / 4, at % 4);
+            if column == 3 {
+                (transform[at] + self.moved[axis]) * self.scale[axis]
+            } else {
+                transform[at] * self.scale[axis]
+            }
+        })
+    }
+}
+
+/// A position through rows: the first two products, then the third and the
+/// last column, then the two sums together, as the library adds them.
+fn through(rows: &Transform, [x, y, z]: [f32; 3]) -> [f32; 3] {
+    core::array::from_fn(|axis| {
+        let row = &rows[4 * axis..4 * axis + 4];
+        (row[0] * x + row[1] * y) + (row[2] * z + row[3])
+    })
+}
+
+/// The smaller of two bounds; one that is not a number gives way.
+fn lower(a: f32, b: f32) -> f32 {
+    if a.is_nan() {
+        b
+    } else if b.is_nan() || a <= b {
+        a
+    } else {
+        b
+    }
+}
+
+fn upper(a: f32, b: f32) -> f32 {
+    if a.is_nan() {
+        b
+    } else if b.is_nan() || a >= b {
+        a
+    } else {
+        b
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Bounds {
+    min: [f32; 3],
+    max: [f32; 3],
+}
+
+impl Bounds {
+    const NONE: Self = Self { min: [f32::INFINITY; 3], max: [f32::NEG_INFINITY; 3] };
+
+    fn add(&mut self, min: [f32; 3], max: [f32; 3]) {
+        for axis in 0..3 {
+            self.min[axis] = lower(self.min[axis], min[axis]);
+            self.max[axis] = upper(self.max[axis], max[axis]);
+        }
+    }
+}
+
+/// The half-precision value at or below `x`, or at or above it when `up`: a
+/// 64-byte box node keeps its bounds as halves, each rounded outwards.
+///
+/// This is the directed rounding of IEEE 754, subnormal halves included. Past
+/// the largest half, 65504, the outward side is infinite and the inward side
+/// stays at 65504. A value that rounds to zero keeps its sign.
+fn half(x: f32, up: bool) -> u16 {
+    let bits = x.to_bits();
+    let sign = (bits >> 16) as u16 & 0x8000;
+    let magnitude = bits & 0x7fff_ffff;
+    if magnitude > 0x7f80_0000 {
+        return sign | 0x7e00;
+    }
+    // Away from zero when the bound moves outwards on this side of zero.
+    let away = up == (sign == 0);
+    let exponent = (magnitude >> 23).cast_signed() - 127;
+    if exponent >= 16 {
+        return sign | if away || magnitude == 0x7f80_0000 { 0x7c00 } else { 0x7bff };
+    }
+    let (kept, inexact) = if exponent >= -14 {
+        // A half keeps 10 of the 23 fraction bits.
+        ((exponent + 15).cast_unsigned() << 10 | (magnitude >> 13 & 0x3ff), magnitude & 0x1fff != 0)
+    } else {
+        // Below the smallest normal half, 2^-14, halves count in steps of 2^-24.
+        let (significand, exponent) =
+            if exponent == -127 { (magnitude, -126) } else { (magnitude & 0x007f_ffff | 0x0080_0000, exponent) };
+        let drop = (-1 - exponent).cast_unsigned();
+        if drop >= 32 { (0, significand != 0) } else { (significand >> drop, significand & ((1 << drop) - 1) != 0) }
+    };
+    // A carry runs into the exponent, and from the largest half into infinity.
+    sign | ((kept + u32::from(away && inexact)) & 0xffff) as u16
+}
+
+fn single(half: u16) -> f32 {
+    let sign = u32::from(half & 0x8000) << 16;
+    let (exponent, fraction) = (u32::from(half >> 10 & 0x1f), u32::from(half & 0x3ff));
+    f32::from_bits(
+        sign | match (exponent, fraction) {
+            (0, 0) => 0,
+            (0, _) => {
+                let shift = fraction.leading_zeros() - 21;
+                (113 - shift) << 23 | (fraction << shift & 0x3ff) << 13
+            }
+            (31, 0) => 0x7f80_0000,
+            (31, _) => 0x7fc0_0000 | fraction << 13,
+            _ => (exponent + 112) << 23 | fraction << 13,
+        },
+    )
+}
+
+/// Leaf `index` of a run of `count` packed leaves at `base`: its geometry,
+/// flags, first and second primitive and vertex order.
+fn packed_leaf(packed: &[u8], base: usize, count: usize, index: usize) -> Option<(u32, u8, u32, u32, u8)> {
+    Some((
+        triple(packed, base + 3 * index)?,
+        *packed.get(base + 3 * count + index)?,
+        triple(packed, base + 4 * count + 3 * index)?,
+        triple(packed, base + 7 * count + 3 * index)?,
+        *packed.get(base + 10 * count + index)?,
+    ))
+}
+
+/// Writes the leaves: for each, the corners of its first triangle, and the
+/// corner a second triangle adds.
+///
+/// A triangle node reads slots 0, 1 and 2, and the node of a second triangle
+/// slots 1, 3 and 2. The order byte holds two fields of two bits for each
+/// triangle, and becomes the first two bytes of the leaf's last word, a
+/// nibble each. For a pair, the first triangle's corners go to the slots
+/// after the ones its fields name, counting round: the first corner after the
+/// first field, the second corner after the second field, the third corner in
+/// the slot left. The second triangle gives its first corner when its first
+/// field is 2, its second corner when its second field is 2, and its third
+/// corner otherwise. A triangle alone keeps its corners in order whatever its
+/// fields say.
+///
+/// The rule for a pair is the one the rehydrator of the port-of-the-americas
+/// project has (AGPL-3.0, revision 0f3be36; no code is taken from it). Every
+/// order byte was then given to the title's own library, alone and in a pair,
+/// and all 36 orders come out as here.
+fn leaves(
+    header: &Header,
+    packed: &[u8],
+    out: &mut [u8],
+    triangle: &dyn Fn(u32, u32) -> Option<Triangle>,
+    transform: &dyn Fn(u32) -> Option<Transform>,
+) -> Result<(), &'static str> {
+    let frame = Frame::new(header.frame, &header.bounds)?;
+    // The rows of the geometry last placed: leaves of one geometry come together.
+    let mut joined = None::<(u32, Option<Transform>)>;
+    let mut place = |geometry: u32, corner: [f32; 3]| {
+        if joined.is_none_or(|(of, _)| of != geometry) {
+            joined = Some((geometry, transform(geometry).map(|rows| frame.after(&rows))));
+        }
+        match &joined {
+            Some((_, Some(rows))) => through(rows, corner),
+            _ => frame.place(corner),
+        }
+    };
+    for first in (0..header.leaves).step_by(LEAVES_IN_RUN) {
+        let count = (header.leaves - first).min(LEAVES_IN_RUN);
+        let base = header.leaves_at + first * UNIT;
+        for index in 0..count {
+            let (geometry, flags, first_primitive, second_primitive, order) =
+                packed_leaf(packed, base, count, index).ok_or("leaf arrays outside the structure")?;
+            let corners =
+                triangle(geometry, first_primitive).ok_or("a leaf names a triangle the geometry does not have")?;
+            let mut slots = [[f32::NAN; 3]; 4];
+            if second_primitive == NO_PRIMITIVE {
+                for (slot, corner) in corners.iter().enumerate() {
+                    slots[slot] = place(geometry, *corner);
+                }
+            } else {
+                let fields: [usize; 4] = core::array::from_fn(|field| usize::from(order >> (2 * field) & 3));
+                if fields.iter().any(|&field| field > 2) || fields[0] == fields[1] || fields[2] == fields[3] {
+                    return Err("a leaf's vertex order is not an order");
+                }
+                slots[(fields[0] + 2) % 3] = place(geometry, corners[0]);
+                slots[(fields[1] + 2) % 3] = place(geometry, corners[1]);
+                slots[(5 - fields[0] - fields[1]) % 3] = place(geometry, corners[2]);
+                let corners =
+                    triangle(geometry, second_primitive).ok_or("a leaf names a triangle the geometry does not have")?;
+                let added = match (fields[2], fields[3]) {
+                    (2, _) => 0,
+                    (_, 2) => 1,
+                    _ => 2,
+                };
+                slots[3] = place(geometry, corners[added]);
+            }
+            let mut leaf = [0u8; UNIT];
+            for (slot, corner) in slots.iter().enumerate() {
+                for (axis, value) in corner.iter().enumerate() {
+                    leaf[12 * slot + 4 * axis..][..4].copy_from_slice(&value.to_bits().to_le_bytes());
+                }
+            }
+            let second_primitive = if second_primitive == NO_PRIMITIVE { NO_NODE } else { second_primitive };
+            let words = [
+                geometry << 8 | u32::from(flags),
+                first_primitive,
+                second_primitive,
+                u32::from(order & 0xf) | u32::from(order >> 4) << 8,
+            ];
+            for (index, word) in words.iter().enumerate() {
+                leaf[48 + 4 * index..][..4].copy_from_slice(&word.to_le_bytes());
+            }
+            put(out, base + index * UNIT, &leaf).ok_or("leaves outside the structure")?;
+        }
+    }
+    Ok(())
+}
+
+/// The box a parent holds for the child at `child`: the corners a leaf's
+/// node reads, or everything a box node's own slots hold. Box nodes at or
+/// past `below` are not expanded yet.
+fn seen(header: &Header, out: &[u8], child: u32, below: usize) -> Result<Bounds, &'static str> {
+    let at = target(child);
+    let read = |at| word(out, at).ok_or("a child outside the structure");
+    let mut bounds = Bounds::NONE;
+    match child & 7 {
+        TRIANGLE => {
+            if at < header.leaves_at || (at - header.leaves_at) / UNIT >= header.leaves {
+                return Err("a child that is not one of the leaves");
+            }
+            let corners = if read(at + 48)? & PAIR != 0 { 4 } else { 3 };
+            for slot in 0..corners {
+                let corner =
+                    [read(at + 12 * slot)?, read(at + 12 * slot + 4)?, read(at + 12 * slot + 8)?].map(f32::from_bits);
+                bounds.add(corner, corner);
+            }
+        }
+        kind @ (BOX16 | BOX32) => {
+            let size = if kind == BOX32 { WIDE } else { UNIT };
+            if at < header.boxes_at || at + size > below {
+                return Err("a child that is not a box node of a lower level");

This range check accepts malformed child pointers, such as a BOX32 pointer to two consecutive BOX16 records, and then reads half-float data as float bounds while preserving the invalid pointer in the output. The root check at lines 574–575 has the same issue: it accepts the wrong node kind or an address inside a wide record. Retain the level table's width-specific node ranges and validate both children and the root against actual record starts of the declared kind before accepting them.

<!-- greyfinch-sync:brcly/TuxBox:review-comment:4738031427 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/536#discussion_r4738031427). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-30T10:44:27Z. **Code review location:** `runtime/d3d12/src/commands/build_raytracing/packed_structure.rs`; line 447 ~~~~diff @@ -0,0 +1,610 @@ +//! Console bottom-level structures in the packed form a title ships. +//! +//! A title streams its static bottom-level structures packed and has the +//! console's builder library expand each one in place before a ray walks it. +//! The packed form keeps the tree and leaves out what the geometry gives +//! back: a leaf is 11 bytes naming its triangles, and a box node is its child +//! pointers and the few bounds that cannot be recomputed. `unpack` writes the +//! form the title's own ray-walk shaders read. +//! +//! The expanded records are those of the public traversal source +//! (`XboxBvh4Header`, `Node16`, `Node32` and `Leaf` in +//! `XDXRStandaloneTraverseShortStackCPU.hlsli`, as Dagor Engine publishes it +//! at revision 9639942). The packing is the one +//! Leonida's `docs/bvh.md` measured on the title's archives (sections 3.1 and +//! 4a), where a model of it wrote the library's own bytes: +//! +//! - The 64-byte header stays, without its packed flag. A structure spans +//! `64 * (nodes + 1)` bytes: the header's node count leaves the header out. +//! - Leaves start at the header's element offset and are 64 bytes each once +//! expanded. Packed, every run of 2,048 leaves begins with five arrays of +//! one entry per leaf: geometry index (3 bytes), flags (1), first primitive +//! (3), second primitive (3, `0xffffff` for none) and vertex order (1). +//! - Box nodes start at the header's node offset, level by level from the +//! leaves up. The structure ends with a count of levels, preceded by one +//! pair per level: where its 128-byte nodes end and where its 64-byte nodes +//! end. Packed, every run of 64 nodes begins with one word per node (child +//! count in the top byte, then a 24-bit mask), then every child pointer, +//! then one stored bound per mask bit. +//! - The parent table lies between the header and the leaves, one word per +//! 64 bytes counted from the first leaf. It is empty when packed. +//! +//! A node pointer is its offset from the header in 8-byte steps, with the +//! node's kind in the three low bits. +//! +//! Where those descriptions are silent, what the library does was measured +//! off the game, by giving the title's own builder library and `unpack` the +//! same packed bytes and the same geometry and comparing every byte: +//! +//! - a leaf of one triangle keeps its corners in order, whatever its vertex +//! order says; +//! - a 64-byte box node rounds its bounds outwards to halves as IEEE 754 +//! directs, subnormal halves included; +//! - a leaf at the root gets no entry in the parent table; +//! - a geometry's own transform is joined to the leaf frame before a +//! position goes through, and a row adds its products in pairs. +// Not called outside the tests until the structures are placed for the walks. +#![cfg_attr(not(test), allow(dead_code))] + +const UNIT: usize = 64; +const WIDE: usize = 128; +const LEAVES_IN_RUN: usize = 2048; +const NODES_IN_RUN: usize = 64; +/// Larger structures are refused rather than expanded. +const LIMIT: usize = 256 << 20; + +const VERSION: u32 = 6; +const BOTTOM_LEVEL: u32 = 0x8000_0000; +const PACKED: u32 = 0x0100_0000; +/// Forms no archive of the title holds: compressed, updatable, or with +/// bounds of more than three axes. +const UNSEEN: u32 = 0x00f5_0000; +/// The leaf flag for a second triangle. +const PAIR: u32 = 0x80; + +const TRIANGLE: u32 = 0; +const BOX16: u32 = 4; +const BOX32: u32 = 5; +const NO_NODE: u32 = u32::MAX; +const NO_PRIMITIVE: u32 = 0x00ff_ffff; + +/// A triangle's corners in the order its index buffer names them, as its +/// geometry's buffers hold them: before the geometry's own transform. +pub(super) type Triangle = [[f32; 3]; 3]; +/// A geometry's transform: three rows of four. +pub(super) type Transform = [f32; 12]; + +fn word(bytes: &[u8], at: usize) -> Option<u32> { + Some(u32::from_le_bytes(bytes.get(at..at.checked_add(4)?)?.try_into().ok()?)) +} + +/// A three-byte entry of a packed leaf array. +fn triple(bytes: &[u8], at: usize) -> Option<u32> { + let entry = bytes.get(at..at.checked_add(3)?)?; + Some(u32::from(entry[0]) | u32::from(entry[1]) << 8 | u32::from(entry[2]) << 16) +} + +fn put(out: &mut [u8], at: usize, bytes: &[u8]) -> Option<()> { + out.get_mut(at..at.checked_add(bytes.len())?)?.copy_from_slice(bytes); + Some(()) +} + +/// The low 32 bits of an offset. Offsets inside a structure fit, and the +/// library counts in 32-bit words where one does not. +fn low(offset: usize) -> u32 { + u32::try_from(offset & 0xffff_ffff).expect("masked to 32 bits") +} + +fn pointer(at: usize, kind: u32) -> u32 { + low(at / 8) | kind +} + +fn target(pointer: u32) -> usize { + (pointer >> 3) as usize * UNIT +} + +struct Header { + flags: u32, + /// The whole structure, header included. + bytes: usize, + leaves: usize, + bounds: [f32; 6], + boxes_at: usize, + root: u32, + leaves_at: usize, + parents_at: u32, + frame: u32, +} + +impl Header { + fn read(packed: &[u8]) -> Result<Self, &'static str> { + let field = |at| word(packed, at).ok_or("shorter than a header"); + let flags = field(0)?; + if flags & 0xffff != VERSION || flags & BOTTOM_LEVEL == 0 { + return Err("not a bottom-level structure of the known version"); + } + if flags & PACKED == 0 { + return Err("not packed"); + } + // The word at 44 would lead to a table that renumbers the primitives. + if flags & UNSEEN != 0 || field(44)? != 0 { + return Err("a form no archive holds"); + } + let bytes = (field(4)? as usize + 1) + .checked_mul(UNIT) + .filter(|&bytes| bytes <= packed.len().min(LIMIT)) + .ok_or("larger than the bytes given")?; + let header = Self { + flags, + bytes, + leaves: field(12)? as usize, + bounds: core::array::from_fn(|index| f32::from_bits(word(packed, 16 + 4 * index).unwrap_or(0))), + boxes_at: field(40)? as usize, + root: field(48)?, + leaves_at: field(52)? as usize, + parents_at: field(56)?, + frame: field(60)?, + }; + let leaves_end = header.leaves.checked_mul(UNIT).and_then(|span| span.checked_add(header.leaves_at)); + if header.leaves == 0 + || header.leaves_at < UNIT + || !header.leaves_at.is_multiple_of(UNIT) + || leaves_end.is_none_or(|end| end > bytes) + { + return Err("leaves outside the structure"); + } + Ok(header) + } + + /// Where the parent table holds the entry of the node at `at`, when it + /// holds one: the table ends where the leaves begin. + fn parent_entry(&self, at: usize) -> Option<usize> { + let unit = low(at).wrapping_sub(low(self.leaves_at)) >> 6; + let entry = self.parents_at.wrapping_add(unit.wrapping_mul(4)) as usize; + (entry >= UNIT && entry + 4 <= self.leaves_at).then_some(entry) + } +} + +/// The space the leaves' corners are stored in, from the header's last word: +/// `(v - middle) * scale`. Bit 31 scales each axis by a power of two, whose +/// exponents are the three low bytes. Bit 30 moves the middle of the header's +/// bounds to zero on each axis they do not straddle. Bits 24 to 29 would turn +/// the positions. No structure seen so far sets them, and how the library +/// rounds a turn is not established, so such a structure is refused. +/// +/// The word `0x007f7f7f` alone leaves positions as they are. Any other goes +/// through the arithmetic, which the library writes so that a negative zero +/// comes out positive. +struct Frame { + /// What is added to a position: minus the middle, or zero. + moved: [f32; 3], + scale: [f32; 3], + plain: bool, +} + +impl Frame { + const PLAIN: u32 = 0x007f_7f7f; + + fn new(word: u32, bounds: &[f32; 6]) -> Result<Self, &'static str> { + let (scaled, shifted, turned) = (word >> 31 != 0, word >> 30 & 1 != 0, word >> 24 & 0x3f != 0); + if turned { + return Err("a turned leaf frame, not seen so far"); + } + Ok(Self { + moved: core::array::from_fn(|axis| { + let (low, high) = (bounds[axis], bounds[3 + axis]); + if shifted && (low > 0.0 || high < 0.0) { -((low + high) * 0.5) } else { 0.0 } + }), + scale: core::array::from_fn( + |axis| if scaled { f32::from_bits((word >> (8 * axis) & 0xff) << 23) } else { 1.0 }, + ), + plain: word == Self::PLAIN, + }) + } + + fn place(&self, v: [f32; 3]) -> [f32; 3] { + if self.plain { + return v; + } + core::array::from_fn(|axis| (v[axis] + self.moved[axis]) * self.scale[axis]) + } + + /// The rows that take a position through a geometry's transform and then + /// into this frame. The library joins the two before it touches a + /// position, which rounds differently from one after the other. + fn after(&self, transform: &Transform) -> Transform { + core::array::from_fn(|at| { + let (axis, column) = (at / 4, at % 4); + if column == 3 { + (transform[at] + self.moved[axis]) * self.scale[axis] + } else { + transform[at] * self.scale[axis] + } + }) + } +} + +/// A position through rows: the first two products, then the third and the +/// last column, then the two sums together, as the library adds them. +fn through(rows: &Transform, [x, y, z]: [f32; 3]) -> [f32; 3] { + core::array::from_fn(|axis| { + let row = &rows[4 * axis..4 * axis + 4]; + (row[0] * x + row[1] * y) + (row[2] * z + row[3]) + }) +} + +/// The smaller of two bounds; one that is not a number gives way. +fn lower(a: f32, b: f32) -> f32 { + if a.is_nan() { + b + } else if b.is_nan() || a <= b { + a + } else { + b + } +} + +fn upper(a: f32, b: f32) -> f32 { + if a.is_nan() { + b + } else if b.is_nan() || a >= b { + a + } else { + b + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Bounds { + min: [f32; 3], + max: [f32; 3], +} + +impl Bounds { + const NONE: Self = Self { min: [f32::INFINITY; 3], max: [f32::NEG_INFINITY; 3] }; + + fn add(&mut self, min: [f32; 3], max: [f32; 3]) { + for axis in 0..3 { + self.min[axis] = lower(self.min[axis], min[axis]); + self.max[axis] = upper(self.max[axis], max[axis]); + } + } +} + +/// The half-precision value at or below `x`, or at or above it when `up`: a +/// 64-byte box node keeps its bounds as halves, each rounded outwards. +/// +/// This is the directed rounding of IEEE 754, subnormal halves included. Past +/// the largest half, 65504, the outward side is infinite and the inward side +/// stays at 65504. A value that rounds to zero keeps its sign. +fn half(x: f32, up: bool) -> u16 { + let bits = x.to_bits(); + let sign = (bits >> 16) as u16 & 0x8000; + let magnitude = bits & 0x7fff_ffff; + if magnitude > 0x7f80_0000 { + return sign | 0x7e00; + } + // Away from zero when the bound moves outwards on this side of zero. + let away = up == (sign == 0); + let exponent = (magnitude >> 23).cast_signed() - 127; + if exponent >= 16 { + return sign | if away || magnitude == 0x7f80_0000 { 0x7c00 } else { 0x7bff }; + } + let (kept, inexact) = if exponent >= -14 { + // A half keeps 10 of the 23 fraction bits. + ((exponent + 15).cast_unsigned() << 10 | (magnitude >> 13 & 0x3ff), magnitude & 0x1fff != 0) + } else { + // Below the smallest normal half, 2^-14, halves count in steps of 2^-24. + let (significand, exponent) = + if exponent == -127 { (magnitude, -126) } else { (magnitude & 0x007f_ffff | 0x0080_0000, exponent) }; + let drop = (-1 - exponent).cast_unsigned(); + if drop >= 32 { (0, significand != 0) } else { (significand >> drop, significand & ((1 << drop) - 1) != 0) } + }; + // A carry runs into the exponent, and from the largest half into infinity. + sign | ((kept + u32::from(away && inexact)) & 0xffff) as u16 +} + +fn single(half: u16) -> f32 { + let sign = u32::from(half & 0x8000) << 16; + let (exponent, fraction) = (u32::from(half >> 10 & 0x1f), u32::from(half & 0x3ff)); + f32::from_bits( + sign | match (exponent, fraction) { + (0, 0) => 0, + (0, _) => { + let shift = fraction.leading_zeros() - 21; + (113 - shift) << 23 | (fraction << shift & 0x3ff) << 13 + } + (31, 0) => 0x7f80_0000, + (31, _) => 0x7fc0_0000 | fraction << 13, + _ => (exponent + 112) << 23 | fraction << 13, + }, + ) +} + +/// Leaf `index` of a run of `count` packed leaves at `base`: its geometry, +/// flags, first and second primitive and vertex order. +fn packed_leaf(packed: &[u8], base: usize, count: usize, index: usize) -> Option<(u32, u8, u32, u32, u8)> { + Some(( + triple(packed, base + 3 * index)?, + *packed.get(base + 3 * count + index)?, + triple(packed, base + 4 * count + 3 * index)?, + triple(packed, base + 7 * count + 3 * index)?, + *packed.get(base + 10 * count + index)?, + )) +} + +/// Writes the leaves: for each, the corners of its first triangle, and the +/// corner a second triangle adds. +/// +/// A triangle node reads slots 0, 1 and 2, and the node of a second triangle +/// slots 1, 3 and 2. The order byte holds two fields of two bits for each +/// triangle, and becomes the first two bytes of the leaf's last word, a +/// nibble each. For a pair, the first triangle's corners go to the slots +/// after the ones its fields name, counting round: the first corner after the +/// first field, the second corner after the second field, the third corner in +/// the slot left. The second triangle gives its first corner when its first +/// field is 2, its second corner when its second field is 2, and its third +/// corner otherwise. A triangle alone keeps its corners in order whatever its +/// fields say. +/// +/// The rule for a pair is the one the rehydrator of the port-of-the-americas +/// project has (AGPL-3.0, revision 0f3be36; no code is taken from it). Every +/// order byte was then given to the title's own library, alone and in a pair, +/// and all 36 orders come out as here. +fn leaves( + header: &Header, + packed: &[u8], + out: &mut [u8], + triangle: &dyn Fn(u32, u32) -> Option<Triangle>, + transform: &dyn Fn(u32) -> Option<Transform>, +) -> Result<(), &'static str> { + let frame = Frame::new(header.frame, &header.bounds)?; + // The rows of the geometry last placed: leaves of one geometry come together. + let mut joined = None::<(u32, Option<Transform>)>; + let mut place = |geometry: u32, corner: [f32; 3]| { + if joined.is_none_or(|(of, _)| of != geometry) { + joined = Some((geometry, transform(geometry).map(|rows| frame.after(&rows)))); + } + match &joined { + Some((_, Some(rows))) => through(rows, corner), + _ => frame.place(corner), + } + }; + for first in (0..header.leaves).step_by(LEAVES_IN_RUN) { + let count = (header.leaves - first).min(LEAVES_IN_RUN); + let base = header.leaves_at + first * UNIT; + for index in 0..count { + let (geometry, flags, first_primitive, second_primitive, order) = + packed_leaf(packed, base, count, index).ok_or("leaf arrays outside the structure")?; + let corners = + triangle(geometry, first_primitive).ok_or("a leaf names a triangle the geometry does not have")?; + let mut slots = [[f32::NAN; 3]; 4]; + if second_primitive == NO_PRIMITIVE { + for (slot, corner) in corners.iter().enumerate() { + slots[slot] = place(geometry, *corner); + } + } else { + let fields: [usize; 4] = core::array::from_fn(|field| usize::from(order >> (2 * field) & 3)); + if fields.iter().any(|&field| field > 2) || fields[0] == fields[1] || fields[2] == fields[3] { + return Err("a leaf's vertex order is not an order"); + } + slots[(fields[0] + 2) % 3] = place(geometry, corners[0]); + slots[(fields[1] + 2) % 3] = place(geometry, corners[1]); + slots[(5 - fields[0] - fields[1]) % 3] = place(geometry, corners[2]); + let corners = + triangle(geometry, second_primitive).ok_or("a leaf names a triangle the geometry does not have")?; + let added = match (fields[2], fields[3]) { + (2, _) => 0, + (_, 2) => 1, + _ => 2, + }; + slots[3] = place(geometry, corners[added]); + } + let mut leaf = [0u8; UNIT]; + for (slot, corner) in slots.iter().enumerate() { + for (axis, value) in corner.iter().enumerate() { + leaf[12 * slot + 4 * axis..][..4].copy_from_slice(&value.to_bits().to_le_bytes()); + } + } + let second_primitive = if second_primitive == NO_PRIMITIVE { NO_NODE } else { second_primitive }; + let words = [ + geometry << 8 | u32::from(flags), + first_primitive, + second_primitive, + u32::from(order & 0xf) | u32::from(order >> 4) << 8, + ]; + for (index, word) in words.iter().enumerate() { + leaf[48 + 4 * index..][..4].copy_from_slice(&word.to_le_bytes()); + } + put(out, base + index * UNIT, &leaf).ok_or("leaves outside the structure")?; + } + } + Ok(()) +} + +/// The box a parent holds for the child at `child`: the corners a leaf's +/// node reads, or everything a box node's own slots hold. Box nodes at or +/// past `below` are not expanded yet. +fn seen(header: &Header, out: &[u8], child: u32, below: usize) -> Result<Bounds, &'static str> { + let at = target(child); + let read = |at| word(out, at).ok_or("a child outside the structure"); + let mut bounds = Bounds::NONE; + match child & 7 { + TRIANGLE => { + if at < header.leaves_at || (at - header.leaves_at) / UNIT >= header.leaves { + return Err("a child that is not one of the leaves"); + } + let corners = if read(at + 48)? & PAIR != 0 { 4 } else { 3 }; + for slot in 0..corners { + let corner = + [read(at + 12 * slot)?, read(at + 12 * slot + 4)?, read(at + 12 * slot + 8)?].map(f32::from_bits); + bounds.add(corner, corner); + } + } + kind @ (BOX16 | BOX32) => { + let size = if kind == BOX32 { WIDE } else { UNIT }; + if at < header.boxes_at || at + size > below { + return Err("a child that is not a box node of a lower level"); ~~~~ --- This range check accepts malformed child pointers, such as a BOX32 pointer to two consecutive BOX16 records, and then reads half-float data as float bounds while preserving the invalid pointer in the output. The root check at lines 574–575 has the same issue: it accepts the wrong node kind or an address inside a wide record. Retain the level table's width-specific node ranges and validate both children and the root against actual record starts of the declared kind before accepting them.
copilot-pull-request-reviewer[bot] commented 2026-11-30 10:44:27 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-30T10:44:27Z.

Review: COMMENTED


A critical pointer-validation flaw allows child and root pointers with the wrong node kind or misaligned record address, causing malformed bounds reads and preserving invalid pointers in the output.

1 open issue
What changed in this PR

Adds CPU-side expansion of packed bottom-level ray-tracing structures to TuxBox’s D3D12 provider, preparing for the ray walks tracked in #382. The function is not yet called outside tests, so runtime behavior remains unchanged.

Changes:

  • Expands packed leaves, both box-node sizes, transforms, bounds, and parent entries.
  • Rejects unsupported formats and adds eleven unit tests using hand-built structures.
  • Registers the module without wiring it into builds or dispatches.
File Description
runtime/​d3d12/​src/​tests/​commands/​packed_structure.rs Tests expansion, rounding, transforms, node relationships, and invalid inputs.
runtime/​d3d12/​src/​commands/​build_raytracing/​packed_structure.rs Implements packed-structure decoding and expansion.
runtime/​d3d12/​src/​commands/​build_raytracing.rs Registers the new module.

Review effort: Balanced

<!-- greyfinch-sync:brcly/TuxBox:review:6110725987 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/536#pullrequestreview-6110725987). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-30T10:44:27Z. **Review:** COMMENTED --- <!-- ccr-overview-v2 --> ### 🟡 Changes recommended A critical pointer-validation flaw allows child and root pointers with the wrong node kind or misaligned record address, causing malformed bounds reads and preserving invalid pointers in the output. <details open> <summary><strong>1 open issue</strong></summary> - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Validate child and root pointers against node kind and record starts](https://github.com/brcly/TuxBox/pull/536#discussion_r4738031427) · New </details> <details> <summary><strong>What changed in this PR</strong></summary> Adds CPU-side expansion of packed bottom-level ray-tracing structures to TuxBox’s D3D12 provider, preparing for the ray walks tracked in #382. The function is not yet called outside tests, so runtime behavior remains unchanged. **Changes:** - Expands packed leaves, both box-node sizes, transforms, bounds, and parent entries. - Rejects unsupported formats and adds eleven unit tests using hand-built structures. - Registers the module without wiring it into builds or dispatches. | File | Description | | ---- | ----------- | | `runtime/​d3d12/​src/​tests/​commands/​packed_structure.rs` | Tests expansion, rounding, transforms, node relationships, and invalid inputs. | | `runtime/​d3d12/​src/​commands/​build_raytracing/​packed_structure.rs` | Implements packed-structure decoding and expansion. | | `runtime/​d3d12/​src/​commands/​build_raytracing.rs` | Registers the new module. | </details> <sub>Review effort: Balanced</sub>
brcly commented 2026-11-30 11:45:59 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by brcly on 2026-11-30T11:45:59Z.


Thanks for the rebase and for the careful sourcing. The byte-for-byte comparison against the title's own rehydration entry is exactly the right standard, and so is keeping that harness off the repository.

As the description says, nothing calls this yet, and the same goes for #586. Our rule for this round is to merge when a change has an effect someone can see or measure. Your own runs on #382 also show that, with the console structures switched on, the walks currently end in GPU losses (three of three, Xid 13). So I'm holding #536 and #586 until the wiring PR is up. Then we'll review and merge the three together, once a run shows:

  • the walks reading the structures without device loss, over the same length of run as your #566 controls (20 to 25 min); and
  • some visible effect: shadows that the empty scenes leave out today.

Splitting the work into three PRs is still useful: it keeps each one reviewable. They just land together.

<!-- greyfinch-sync:brcly/TuxBox:comment:7277491446 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/536#issuecomment-7277491446). Originally posted by [brcly](https://github.com/brcly) on 2026-11-30T11:45:59Z. --- Thanks for the rebase and for the careful sourcing. The byte-for-byte comparison against the title's own rehydration entry is exactly the right standard, and so is keeping that harness off the repository. As the description says, nothing calls this yet, and the same goes for #586. Our rule for this round is to merge when a change has an effect someone can see or measure. Your own runs on #382 also show that, with the console structures switched on, the walks currently end in GPU losses (three of three, Xid 13). So I'm holding #536 and #586 until the wiring PR is up. Then we'll review and merge the three together, once a run shows: - the walks reading the structures without device loss, over the same length of run as your #566 controls (20 to 25 min); and - some visible effect: shadows that the empty scenes leave out today. Splitting the work into three PRs is still useful: it keeps each one reviewable. They just land together.
3kynox commented 2026-11-30 12:25:40 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by 3kynox on 2026-11-30T12:25:40Z.

Code review location: runtime/d3d12/src/commands/build_raytracing/packed_structure.rs; line 447

@@ -0,0 +1,610 @@
+//! Console bottom-level structures in the packed form a title ships.
+//!
+//! A title streams its static bottom-level structures packed and has the
+//! console's builder library expand each one in place before a ray walks it.
+//! The packed form keeps the tree and leaves out what the geometry gives
+//! back: a leaf is 11 bytes naming its triangles, and a box node is its child
+//! pointers and the few bounds that cannot be recomputed. `unpack` writes the
+//! form the title's own ray-walk shaders read.
+//!
+//! The expanded records are those of the public traversal source
+//! (`XboxBvh4Header`, `Node16`, `Node32` and `Leaf` in
+//! `XDXRStandaloneTraverseShortStackCPU.hlsli`, as Dagor Engine publishes it
+//! at revision 9639942). The packing is the one
+//! Leonida's `docs/bvh.md` measured on the title's archives (sections 3.1 and
+//! 4a), where a model of it wrote the library's own bytes:
+//!
+//! - The 64-byte header stays, without its packed flag. A structure spans
+//!   `64 * (nodes + 1)` bytes: the header's node count leaves the header out.
+//! - Leaves start at the header's element offset and are 64 bytes each once
+//!   expanded. Packed, every run of 2,048 leaves begins with five arrays of
+//!   one entry per leaf: geometry index (3 bytes), flags (1), first primitive
+//!   (3), second primitive (3, `0xffffff` for none) and vertex order (1).
+//! - Box nodes start at the header's node offset, level by level from the
+//!   leaves up. The structure ends with a count of levels, preceded by one
+//!   pair per level: where its 128-byte nodes end and where its 64-byte nodes
+//!   end. Packed, every run of 64 nodes begins with one word per node (child
+//!   count in the top byte, then a 24-bit mask), then every child pointer,
+//!   then one stored bound per mask bit.
+//! - The parent table lies between the header and the leaves, one word per
+//!   64 bytes counted from the first leaf. It is empty when packed.
+//!
+//! A node pointer is its offset from the header in 8-byte steps, with the
+//! node's kind in the three low bits.
+//!
+//! Where those descriptions are silent, what the library does was measured
+//! off the game, by giving the title's own builder library and `unpack` the
+//! same packed bytes and the same geometry and comparing every byte:
+//!
+//! - a leaf of one triangle keeps its corners in order, whatever its vertex
+//!   order says;
+//! - a 64-byte box node rounds its bounds outwards to halves as IEEE 754
+//!   directs, subnormal halves included;
+//! - a leaf at the root gets no entry in the parent table;
+//! - a geometry's own transform is joined to the leaf frame before a
+//!   position goes through, and a row adds its products in pairs.
+// Not called outside the tests until the structures are placed for the walks.
+#![cfg_attr(not(test), allow(dead_code))]
+
+const UNIT: usize = 64;
+const WIDE: usize = 128;
+const LEAVES_IN_RUN: usize = 2048;
+const NODES_IN_RUN: usize = 64;
+/// Larger structures are refused rather than expanded.
+const LIMIT: usize = 256 << 20;
+
+const VERSION: u32 = 6;
+const BOTTOM_LEVEL: u32 = 0x8000_0000;
+const PACKED: u32 = 0x0100_0000;
+/// Forms no archive of the title holds: compressed, updatable, or with
+/// bounds of more than three axes.
+const UNSEEN: u32 = 0x00f5_0000;
+/// The leaf flag for a second triangle.
+const PAIR: u32 = 0x80;
+
+const TRIANGLE: u32 = 0;
+const BOX16: u32 = 4;
+const BOX32: u32 = 5;
+const NO_NODE: u32 = u32::MAX;
+const NO_PRIMITIVE: u32 = 0x00ff_ffff;
+
+/// A triangle's corners in the order its index buffer names them, as its
+/// geometry's buffers hold them: before the geometry's own transform.
+pub(super) type Triangle = [[f32; 3]; 3];
+/// A geometry's transform: three rows of four.
+pub(super) type Transform = [f32; 12];
+
+fn word(bytes: &[u8], at: usize) -> Option<u32> {
+    Some(u32::from_le_bytes(bytes.get(at..at.checked_add(4)?)?.try_into().ok()?))
+}
+
+/// A three-byte entry of a packed leaf array.
+fn triple(bytes: &[u8], at: usize) -> Option<u32> {
+    let entry = bytes.get(at..at.checked_add(3)?)?;
+    Some(u32::from(entry[0]) | u32::from(entry[1]) << 8 | u32::from(entry[2]) << 16)
+}
+
+fn put(out: &mut [u8], at: usize, bytes: &[u8]) -> Option<()> {
+    out.get_mut(at..at.checked_add(bytes.len())?)?.copy_from_slice(bytes);
+    Some(())
+}
+
+/// The low 32 bits of an offset. Offsets inside a structure fit, and the
+/// library counts in 32-bit words where one does not.
+fn low(offset: usize) -> u32 {
+    u32::try_from(offset & 0xffff_ffff).expect("masked to 32 bits")
+}
+
+fn pointer(at: usize, kind: u32) -> u32 {
+    low(at / 8) | kind
+}
+
+fn target(pointer: u32) -> usize {
+    (pointer >> 3) as usize * UNIT
+}
+
+struct Header {
+    flags: u32,
+    /// The whole structure, header included.
+    bytes: usize,
+    leaves: usize,
+    bounds: [f32; 6],
+    boxes_at: usize,
+    root: u32,
+    leaves_at: usize,
+    parents_at: u32,
+    frame: u32,
+}
+
+impl Header {
+    fn read(packed: &[u8]) -> Result<Self, &'static str> {
+        let field = |at| word(packed, at).ok_or("shorter than a header");
+        let flags = field(0)?;
+        if flags & 0xffff != VERSION || flags & BOTTOM_LEVEL == 0 {
+            return Err("not a bottom-level structure of the known version");
+        }
+        if flags & PACKED == 0 {
+            return Err("not packed");
+        }
+        // The word at 44 would lead to a table that renumbers the primitives.
+        if flags & UNSEEN != 0 || field(44)? != 0 {
+            return Err("a form no archive holds");
+        }
+        let bytes = (field(4)? as usize + 1)
+            .checked_mul(UNIT)
+            .filter(|&bytes| bytes <= packed.len().min(LIMIT))
+            .ok_or("larger than the bytes given")?;
+        let header = Self {
+            flags,
+            bytes,
+            leaves: field(12)? as usize,
+            bounds: core::array::from_fn(|index| f32::from_bits(word(packed, 16 + 4 * index).unwrap_or(0))),
+            boxes_at: field(40)? as usize,
+            root: field(48)?,
+            leaves_at: field(52)? as usize,
+            parents_at: field(56)?,
+            frame: field(60)?,
+        };
+        let leaves_end = header.leaves.checked_mul(UNIT).and_then(|span| span.checked_add(header.leaves_at));
+        if header.leaves == 0
+            || header.leaves_at < UNIT
+            || !header.leaves_at.is_multiple_of(UNIT)
+            || leaves_end.is_none_or(|end| end > bytes)
+        {
+            return Err("leaves outside the structure");
+        }
+        Ok(header)
+    }
+
+    /// Where the parent table holds the entry of the node at `at`, when it
+    /// holds one: the table ends where the leaves begin.
+    fn parent_entry(&self, at: usize) -> Option<usize> {
+        let unit = low(at).wrapping_sub(low(self.leaves_at)) >> 6;
+        let entry = self.parents_at.wrapping_add(unit.wrapping_mul(4)) as usize;
+        (entry >= UNIT && entry + 4 <= self.leaves_at).then_some(entry)
+    }
+}
+
+/// The space the leaves' corners are stored in, from the header's last word:
+/// `(v - middle) * scale`. Bit 31 scales each axis by a power of two, whose
+/// exponents are the three low bytes. Bit 30 moves the middle of the header's
+/// bounds to zero on each axis they do not straddle. Bits 24 to 29 would turn
+/// the positions. No structure seen so far sets them, and how the library
+/// rounds a turn is not established, so such a structure is refused.
+///
+/// The word `0x007f7f7f` alone leaves positions as they are. Any other goes
+/// through the arithmetic, which the library writes so that a negative zero
+/// comes out positive.
+struct Frame {
+    /// What is added to a position: minus the middle, or zero.
+    moved: [f32; 3],
+    scale: [f32; 3],
+    plain: bool,
+}
+
+impl Frame {
+    const PLAIN: u32 = 0x007f_7f7f;
+
+    fn new(word: u32, bounds: &[f32; 6]) -> Result<Self, &'static str> {
+        let (scaled, shifted, turned) = (word >> 31 != 0, word >> 30 & 1 != 0, word >> 24 & 0x3f != 0);
+        if turned {
+            return Err("a turned leaf frame, not seen so far");
+        }
+        Ok(Self {
+            moved: core::array::from_fn(|axis| {
+                let (low, high) = (bounds[axis], bounds[3 + axis]);
+                if shifted && (low > 0.0 || high < 0.0) { -((low + high) * 0.5) } else { 0.0 }
+            }),
+            scale: core::array::from_fn(
+                |axis| if scaled { f32::from_bits((word >> (8 * axis) & 0xff) << 23) } else { 1.0 },
+            ),
+            plain: word == Self::PLAIN,
+        })
+    }
+
+    fn place(&self, v: [f32; 3]) -> [f32; 3] {
+        if self.plain {
+            return v;
+        }
+        core::array::from_fn(|axis| (v[axis] + self.moved[axis]) * self.scale[axis])
+    }
+
+    /// The rows that take a position through a geometry's transform and then
+    /// into this frame. The library joins the two before it touches a
+    /// position, which rounds differently from one after the other.
+    fn after(&self, transform: &Transform) -> Transform {
+        core::array::from_fn(|at| {
+            let (axis, column) = (at / 4, at % 4);
+            if column == 3 {
+                (transform[at] + self.moved[axis]) * self.scale[axis]
+            } else {
+                transform[at] * self.scale[axis]
+            }
+        })
+    }
+}
+
+/// A position through rows: the first two products, then the third and the
+/// last column, then the two sums together, as the library adds them.
+fn through(rows: &Transform, [x, y, z]: [f32; 3]) -> [f32; 3] {
+    core::array::from_fn(|axis| {
+        let row = &rows[4 * axis..4 * axis + 4];
+        (row[0] * x + row[1] * y) + (row[2] * z + row[3])
+    })
+}
+
+/// The smaller of two bounds; one that is not a number gives way.
+fn lower(a: f32, b: f32) -> f32 {
+    if a.is_nan() {
+        b
+    } else if b.is_nan() || a <= b {
+        a
+    } else {
+        b
+    }
+}
+
+fn upper(a: f32, b: f32) -> f32 {
+    if a.is_nan() {
+        b
+    } else if b.is_nan() || a >= b {
+        a
+    } else {
+        b
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Bounds {
+    min: [f32; 3],
+    max: [f32; 3],
+}
+
+impl Bounds {
+    const NONE: Self = Self { min: [f32::INFINITY; 3], max: [f32::NEG_INFINITY; 3] };
+
+    fn add(&mut self, min: [f32; 3], max: [f32; 3]) {
+        for axis in 0..3 {
+            self.min[axis] = lower(self.min[axis], min[axis]);
+            self.max[axis] = upper(self.max[axis], max[axis]);
+        }
+    }
+}
+
+/// The half-precision value at or below `x`, or at or above it when `up`: a
+/// 64-byte box node keeps its bounds as halves, each rounded outwards.
+///
+/// This is the directed rounding of IEEE 754, subnormal halves included. Past
+/// the largest half, 65504, the outward side is infinite and the inward side
+/// stays at 65504. A value that rounds to zero keeps its sign.
+fn half(x: f32, up: bool) -> u16 {
+    let bits = x.to_bits();
+    let sign = (bits >> 16) as u16 & 0x8000;
+    let magnitude = bits & 0x7fff_ffff;
+    if magnitude > 0x7f80_0000 {
+        return sign | 0x7e00;
+    }
+    // Away from zero when the bound moves outwards on this side of zero.
+    let away = up == (sign == 0);
+    let exponent = (magnitude >> 23).cast_signed() - 127;
+    if exponent >= 16 {
+        return sign | if away || magnitude == 0x7f80_0000 { 0x7c00 } else { 0x7bff };
+    }
+    let (kept, inexact) = if exponent >= -14 {
+        // A half keeps 10 of the 23 fraction bits.
+        ((exponent + 15).cast_unsigned() << 10 | (magnitude >> 13 & 0x3ff), magnitude & 0x1fff != 0)
+    } else {
+        // Below the smallest normal half, 2^-14, halves count in steps of 2^-24.
+        let (significand, exponent) =
+            if exponent == -127 { (magnitude, -126) } else { (magnitude & 0x007f_ffff | 0x0080_0000, exponent) };
+        let drop = (-1 - exponent).cast_unsigned();
+        if drop >= 32 { (0, significand != 0) } else { (significand >> drop, significand & ((1 << drop) - 1) != 0) }
+    };
+    // A carry runs into the exponent, and from the largest half into infinity.
+    sign | ((kept + u32::from(away && inexact)) & 0xffff) as u16
+}
+
+fn single(half: u16) -> f32 {
+    let sign = u32::from(half & 0x8000) << 16;
+    let (exponent, fraction) = (u32::from(half >> 10 & 0x1f), u32::from(half & 0x3ff));
+    f32::from_bits(
+        sign | match (exponent, fraction) {
+            (0, 0) => 0,
+            (0, _) => {
+                let shift = fraction.leading_zeros() - 21;
+                (113 - shift) << 23 | (fraction << shift & 0x3ff) << 13
+            }
+            (31, 0) => 0x7f80_0000,
+            (31, _) => 0x7fc0_0000 | fraction << 13,
+            _ => (exponent + 112) << 23 | fraction << 13,
+        },
+    )
+}
+
+/// Leaf `index` of a run of `count` packed leaves at `base`: its geometry,
+/// flags, first and second primitive and vertex order.
+fn packed_leaf(packed: &[u8], base: usize, count: usize, index: usize) -> Option<(u32, u8, u32, u32, u8)> {
+    Some((
+        triple(packed, base + 3 * index)?,
+        *packed.get(base + 3 * count + index)?,
+        triple(packed, base + 4 * count + 3 * index)?,
+        triple(packed, base + 7 * count + 3 * index)?,
+        *packed.get(base + 10 * count + index)?,
+    ))
+}
+
+/// Writes the leaves: for each, the corners of its first triangle, and the
+/// corner a second triangle adds.
+///
+/// A triangle node reads slots 0, 1 and 2, and the node of a second triangle
+/// slots 1, 3 and 2. The order byte holds two fields of two bits for each
+/// triangle, and becomes the first two bytes of the leaf's last word, a
+/// nibble each. For a pair, the first triangle's corners go to the slots
+/// after the ones its fields name, counting round: the first corner after the
+/// first field, the second corner after the second field, the third corner in
+/// the slot left. The second triangle gives its first corner when its first
+/// field is 2, its second corner when its second field is 2, and its third
+/// corner otherwise. A triangle alone keeps its corners in order whatever its
+/// fields say.
+///
+/// The rule for a pair is the one the rehydrator of the port-of-the-americas
+/// project has (AGPL-3.0, revision 0f3be36; no code is taken from it). Every
+/// order byte was then given to the title's own library, alone and in a pair,
+/// and all 36 orders come out as here.
+fn leaves(
+    header: &Header,
+    packed: &[u8],
+    out: &mut [u8],
+    triangle: &dyn Fn(u32, u32) -> Option<Triangle>,
+    transform: &dyn Fn(u32) -> Option<Transform>,
+) -> Result<(), &'static str> {
+    let frame = Frame::new(header.frame, &header.bounds)?;
+    // The rows of the geometry last placed: leaves of one geometry come together.
+    let mut joined = None::<(u32, Option<Transform>)>;
+    let mut place = |geometry: u32, corner: [f32; 3]| {
+        if joined.is_none_or(|(of, _)| of != geometry) {
+            joined = Some((geometry, transform(geometry).map(|rows| frame.after(&rows))));
+        }
+        match &joined {
+            Some((_, Some(rows))) => through(rows, corner),
+            _ => frame.place(corner),
+        }
+    };
+    for first in (0..header.leaves).step_by(LEAVES_IN_RUN) {
+        let count = (header.leaves - first).min(LEAVES_IN_RUN);
+        let base = header.leaves_at + first * UNIT;
+        for index in 0..count {
+            let (geometry, flags, first_primitive, second_primitive, order) =
+                packed_leaf(packed, base, count, index).ok_or("leaf arrays outside the structure")?;
+            let corners =
+                triangle(geometry, first_primitive).ok_or("a leaf names a triangle the geometry does not have")?;
+            let mut slots = [[f32::NAN; 3]; 4];
+            if second_primitive == NO_PRIMITIVE {
+                for (slot, corner) in corners.iter().enumerate() {
+                    slots[slot] = place(geometry, *corner);
+                }
+            } else {
+                let fields: [usize; 4] = core::array::from_fn(|field| usize::from(order >> (2 * field) & 3));
+                if fields.iter().any(|&field| field > 2) || fields[0] == fields[1] || fields[2] == fields[3] {
+                    return Err("a leaf's vertex order is not an order");
+                }
+                slots[(fields[0] + 2) % 3] = place(geometry, corners[0]);
+                slots[(fields[1] + 2) % 3] = place(geometry, corners[1]);
+                slots[(5 - fields[0] - fields[1]) % 3] = place(geometry, corners[2]);
+                let corners =
+                    triangle(geometry, second_primitive).ok_or("a leaf names a triangle the geometry does not have")?;
+                let added = match (fields[2], fields[3]) {
+                    (2, _) => 0,
+                    (_, 2) => 1,
+                    _ => 2,
+                };
+                slots[3] = place(geometry, corners[added]);
+            }
+            let mut leaf = [0u8; UNIT];
+            for (slot, corner) in slots.iter().enumerate() {
+                for (axis, value) in corner.iter().enumerate() {
+                    leaf[12 * slot + 4 * axis..][..4].copy_from_slice(&value.to_bits().to_le_bytes());
+                }
+            }
+            let second_primitive = if second_primitive == NO_PRIMITIVE { NO_NODE } else { second_primitive };
+            let words = [
+                geometry << 8 | u32::from(flags),
+                first_primitive,
+                second_primitive,
+                u32::from(order & 0xf) | u32::from(order >> 4) << 8,
+            ];
+            for (index, word) in words.iter().enumerate() {
+                leaf[48 + 4 * index..][..4].copy_from_slice(&word.to_le_bytes());
+            }
+            put(out, base + index * UNIT, &leaf).ok_or("leaves outside the structure")?;
+        }
+    }
+    Ok(())
+}
+
+/// The box a parent holds for the child at `child`: the corners a leaf's
+/// node reads, or everything a box node's own slots hold. Box nodes at or
+/// past `below` are not expanded yet.
+fn seen(header: &Header, out: &[u8], child: u32, below: usize) -> Result<Bounds, &'static str> {
+    let at = target(child);
+    let read = |at| word(out, at).ok_or("a child outside the structure");
+    let mut bounds = Bounds::NONE;
+    match child & 7 {
+        TRIANGLE => {
+            if at < header.leaves_at || (at - header.leaves_at) / UNIT >= header.leaves {
+                return Err("a child that is not one of the leaves");
+            }
+            let corners = if read(at + 48)? & PAIR != 0 { 4 } else { 3 };
+            for slot in 0..corners {
+                let corner =
+                    [read(at + 12 * slot)?, read(at + 12 * slot + 4)?, read(at + 12 * slot + 8)?].map(f32::from_bits);
+                bounds.add(corner, corner);
+            }
+        }
+        kind @ (BOX16 | BOX32) => {
+            let size = if kind == BOX32 { WIDE } else { UNIT };
+            if at < header.boxes_at || at + size > below {
+                return Err("a child that is not a box node of a lower level");

Right, and against what the file says of itself: what does not follow the packing is refused. Fixed in 4631d10b.

A child pointer and the root are now held to a box node of their own size, at the place it begins. boxes keeps the pairs of the level table it has checked, and Levels::begins finds the level a pointer falls in by a binary search over them, so nothing is allocated by a count the input gives. A structure whose box nodes are off the 64-byte steps a pointer counts in is refused by name.

One new test, which fails on 1474b05e: a 128-byte pointer to two 64-byte nodes, a 64-byte pointer to a 128-byte node and to its second half, a 128-byte pointer from the middle of one, a pointer to a node of the pointing node's own level, and the same for the root.

Run again on this commit:

  • the comparison with the title's library: the 33 hand-built structures and the 70 captured ones (2,626,240 bytes) are still byte-identical, and the four with a turned frame are still refused;
  • 77 errors planted one at a time, eight of them in the new check: 75 fail a test. The other two are the two the description already names, which change nothing a caller could see;
  • Miri on the module's twelve tests, check --no-gpu (12 steps passed, the Python test that fails on main here still fails), and the Wine suite (477 passed; the three failures are the scene_publication tests that ask for a hardware device).

The description is updated with these.

<!-- greyfinch-sync:brcly/TuxBox:review-comment:4739128509 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/536#discussion_r4739128509). Originally posted by [3kynox](https://github.com/3kynox) on 2026-11-30T12:25:40Z. **Code review location:** `runtime/d3d12/src/commands/build_raytracing/packed_structure.rs`; line 447 ~~~~diff @@ -0,0 +1,610 @@ +//! Console bottom-level structures in the packed form a title ships. +//! +//! A title streams its static bottom-level structures packed and has the +//! console's builder library expand each one in place before a ray walks it. +//! The packed form keeps the tree and leaves out what the geometry gives +//! back: a leaf is 11 bytes naming its triangles, and a box node is its child +//! pointers and the few bounds that cannot be recomputed. `unpack` writes the +//! form the title's own ray-walk shaders read. +//! +//! The expanded records are those of the public traversal source +//! (`XboxBvh4Header`, `Node16`, `Node32` and `Leaf` in +//! `XDXRStandaloneTraverseShortStackCPU.hlsli`, as Dagor Engine publishes it +//! at revision 9639942). The packing is the one +//! Leonida's `docs/bvh.md` measured on the title's archives (sections 3.1 and +//! 4a), where a model of it wrote the library's own bytes: +//! +//! - The 64-byte header stays, without its packed flag. A structure spans +//! `64 * (nodes + 1)` bytes: the header's node count leaves the header out. +//! - Leaves start at the header's element offset and are 64 bytes each once +//! expanded. Packed, every run of 2,048 leaves begins with five arrays of +//! one entry per leaf: geometry index (3 bytes), flags (1), first primitive +//! (3), second primitive (3, `0xffffff` for none) and vertex order (1). +//! - Box nodes start at the header's node offset, level by level from the +//! leaves up. The structure ends with a count of levels, preceded by one +//! pair per level: where its 128-byte nodes end and where its 64-byte nodes +//! end. Packed, every run of 64 nodes begins with one word per node (child +//! count in the top byte, then a 24-bit mask), then every child pointer, +//! then one stored bound per mask bit. +//! - The parent table lies between the header and the leaves, one word per +//! 64 bytes counted from the first leaf. It is empty when packed. +//! +//! A node pointer is its offset from the header in 8-byte steps, with the +//! node's kind in the three low bits. +//! +//! Where those descriptions are silent, what the library does was measured +//! off the game, by giving the title's own builder library and `unpack` the +//! same packed bytes and the same geometry and comparing every byte: +//! +//! - a leaf of one triangle keeps its corners in order, whatever its vertex +//! order says; +//! - a 64-byte box node rounds its bounds outwards to halves as IEEE 754 +//! directs, subnormal halves included; +//! - a leaf at the root gets no entry in the parent table; +//! - a geometry's own transform is joined to the leaf frame before a +//! position goes through, and a row adds its products in pairs. +// Not called outside the tests until the structures are placed for the walks. +#![cfg_attr(not(test), allow(dead_code))] + +const UNIT: usize = 64; +const WIDE: usize = 128; +const LEAVES_IN_RUN: usize = 2048; +const NODES_IN_RUN: usize = 64; +/// Larger structures are refused rather than expanded. +const LIMIT: usize = 256 << 20; + +const VERSION: u32 = 6; +const BOTTOM_LEVEL: u32 = 0x8000_0000; +const PACKED: u32 = 0x0100_0000; +/// Forms no archive of the title holds: compressed, updatable, or with +/// bounds of more than three axes. +const UNSEEN: u32 = 0x00f5_0000; +/// The leaf flag for a second triangle. +const PAIR: u32 = 0x80; + +const TRIANGLE: u32 = 0; +const BOX16: u32 = 4; +const BOX32: u32 = 5; +const NO_NODE: u32 = u32::MAX; +const NO_PRIMITIVE: u32 = 0x00ff_ffff; + +/// A triangle's corners in the order its index buffer names them, as its +/// geometry's buffers hold them: before the geometry's own transform. +pub(super) type Triangle = [[f32; 3]; 3]; +/// A geometry's transform: three rows of four. +pub(super) type Transform = [f32; 12]; + +fn word(bytes: &[u8], at: usize) -> Option<u32> { + Some(u32::from_le_bytes(bytes.get(at..at.checked_add(4)?)?.try_into().ok()?)) +} + +/// A three-byte entry of a packed leaf array. +fn triple(bytes: &[u8], at: usize) -> Option<u32> { + let entry = bytes.get(at..at.checked_add(3)?)?; + Some(u32::from(entry[0]) | u32::from(entry[1]) << 8 | u32::from(entry[2]) << 16) +} + +fn put(out: &mut [u8], at: usize, bytes: &[u8]) -> Option<()> { + out.get_mut(at..at.checked_add(bytes.len())?)?.copy_from_slice(bytes); + Some(()) +} + +/// The low 32 bits of an offset. Offsets inside a structure fit, and the +/// library counts in 32-bit words where one does not. +fn low(offset: usize) -> u32 { + u32::try_from(offset & 0xffff_ffff).expect("masked to 32 bits") +} + +fn pointer(at: usize, kind: u32) -> u32 { + low(at / 8) | kind +} + +fn target(pointer: u32) -> usize { + (pointer >> 3) as usize * UNIT +} + +struct Header { + flags: u32, + /// The whole structure, header included. + bytes: usize, + leaves: usize, + bounds: [f32; 6], + boxes_at: usize, + root: u32, + leaves_at: usize, + parents_at: u32, + frame: u32, +} + +impl Header { + fn read(packed: &[u8]) -> Result<Self, &'static str> { + let field = |at| word(packed, at).ok_or("shorter than a header"); + let flags = field(0)?; + if flags & 0xffff != VERSION || flags & BOTTOM_LEVEL == 0 { + return Err("not a bottom-level structure of the known version"); + } + if flags & PACKED == 0 { + return Err("not packed"); + } + // The word at 44 would lead to a table that renumbers the primitives. + if flags & UNSEEN != 0 || field(44)? != 0 { + return Err("a form no archive holds"); + } + let bytes = (field(4)? as usize + 1) + .checked_mul(UNIT) + .filter(|&bytes| bytes <= packed.len().min(LIMIT)) + .ok_or("larger than the bytes given")?; + let header = Self { + flags, + bytes, + leaves: field(12)? as usize, + bounds: core::array::from_fn(|index| f32::from_bits(word(packed, 16 + 4 * index).unwrap_or(0))), + boxes_at: field(40)? as usize, + root: field(48)?, + leaves_at: field(52)? as usize, + parents_at: field(56)?, + frame: field(60)?, + }; + let leaves_end = header.leaves.checked_mul(UNIT).and_then(|span| span.checked_add(header.leaves_at)); + if header.leaves == 0 + || header.leaves_at < UNIT + || !header.leaves_at.is_multiple_of(UNIT) + || leaves_end.is_none_or(|end| end > bytes) + { + return Err("leaves outside the structure"); + } + Ok(header) + } + + /// Where the parent table holds the entry of the node at `at`, when it + /// holds one: the table ends where the leaves begin. + fn parent_entry(&self, at: usize) -> Option<usize> { + let unit = low(at).wrapping_sub(low(self.leaves_at)) >> 6; + let entry = self.parents_at.wrapping_add(unit.wrapping_mul(4)) as usize; + (entry >= UNIT && entry + 4 <= self.leaves_at).then_some(entry) + } +} + +/// The space the leaves' corners are stored in, from the header's last word: +/// `(v - middle) * scale`. Bit 31 scales each axis by a power of two, whose +/// exponents are the three low bytes. Bit 30 moves the middle of the header's +/// bounds to zero on each axis they do not straddle. Bits 24 to 29 would turn +/// the positions. No structure seen so far sets them, and how the library +/// rounds a turn is not established, so such a structure is refused. +/// +/// The word `0x007f7f7f` alone leaves positions as they are. Any other goes +/// through the arithmetic, which the library writes so that a negative zero +/// comes out positive. +struct Frame { + /// What is added to a position: minus the middle, or zero. + moved: [f32; 3], + scale: [f32; 3], + plain: bool, +} + +impl Frame { + const PLAIN: u32 = 0x007f_7f7f; + + fn new(word: u32, bounds: &[f32; 6]) -> Result<Self, &'static str> { + let (scaled, shifted, turned) = (word >> 31 != 0, word >> 30 & 1 != 0, word >> 24 & 0x3f != 0); + if turned { + return Err("a turned leaf frame, not seen so far"); + } + Ok(Self { + moved: core::array::from_fn(|axis| { + let (low, high) = (bounds[axis], bounds[3 + axis]); + if shifted && (low > 0.0 || high < 0.0) { -((low + high) * 0.5) } else { 0.0 } + }), + scale: core::array::from_fn( + |axis| if scaled { f32::from_bits((word >> (8 * axis) & 0xff) << 23) } else { 1.0 }, + ), + plain: word == Self::PLAIN, + }) + } + + fn place(&self, v: [f32; 3]) -> [f32; 3] { + if self.plain { + return v; + } + core::array::from_fn(|axis| (v[axis] + self.moved[axis]) * self.scale[axis]) + } + + /// The rows that take a position through a geometry's transform and then + /// into this frame. The library joins the two before it touches a + /// position, which rounds differently from one after the other. + fn after(&self, transform: &Transform) -> Transform { + core::array::from_fn(|at| { + let (axis, column) = (at / 4, at % 4); + if column == 3 { + (transform[at] + self.moved[axis]) * self.scale[axis] + } else { + transform[at] * self.scale[axis] + } + }) + } +} + +/// A position through rows: the first two products, then the third and the +/// last column, then the two sums together, as the library adds them. +fn through(rows: &Transform, [x, y, z]: [f32; 3]) -> [f32; 3] { + core::array::from_fn(|axis| { + let row = &rows[4 * axis..4 * axis + 4]; + (row[0] * x + row[1] * y) + (row[2] * z + row[3]) + }) +} + +/// The smaller of two bounds; one that is not a number gives way. +fn lower(a: f32, b: f32) -> f32 { + if a.is_nan() { + b + } else if b.is_nan() || a <= b { + a + } else { + b + } +} + +fn upper(a: f32, b: f32) -> f32 { + if a.is_nan() { + b + } else if b.is_nan() || a >= b { + a + } else { + b + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Bounds { + min: [f32; 3], + max: [f32; 3], +} + +impl Bounds { + const NONE: Self = Self { min: [f32::INFINITY; 3], max: [f32::NEG_INFINITY; 3] }; + + fn add(&mut self, min: [f32; 3], max: [f32; 3]) { + for axis in 0..3 { + self.min[axis] = lower(self.min[axis], min[axis]); + self.max[axis] = upper(self.max[axis], max[axis]); + } + } +} + +/// The half-precision value at or below `x`, or at or above it when `up`: a +/// 64-byte box node keeps its bounds as halves, each rounded outwards. +/// +/// This is the directed rounding of IEEE 754, subnormal halves included. Past +/// the largest half, 65504, the outward side is infinite and the inward side +/// stays at 65504. A value that rounds to zero keeps its sign. +fn half(x: f32, up: bool) -> u16 { + let bits = x.to_bits(); + let sign = (bits >> 16) as u16 & 0x8000; + let magnitude = bits & 0x7fff_ffff; + if magnitude > 0x7f80_0000 { + return sign | 0x7e00; + } + // Away from zero when the bound moves outwards on this side of zero. + let away = up == (sign == 0); + let exponent = (magnitude >> 23).cast_signed() - 127; + if exponent >= 16 { + return sign | if away || magnitude == 0x7f80_0000 { 0x7c00 } else { 0x7bff }; + } + let (kept, inexact) = if exponent >= -14 { + // A half keeps 10 of the 23 fraction bits. + ((exponent + 15).cast_unsigned() << 10 | (magnitude >> 13 & 0x3ff), magnitude & 0x1fff != 0) + } else { + // Below the smallest normal half, 2^-14, halves count in steps of 2^-24. + let (significand, exponent) = + if exponent == -127 { (magnitude, -126) } else { (magnitude & 0x007f_ffff | 0x0080_0000, exponent) }; + let drop = (-1 - exponent).cast_unsigned(); + if drop >= 32 { (0, significand != 0) } else { (significand >> drop, significand & ((1 << drop) - 1) != 0) } + }; + // A carry runs into the exponent, and from the largest half into infinity. + sign | ((kept + u32::from(away && inexact)) & 0xffff) as u16 +} + +fn single(half: u16) -> f32 { + let sign = u32::from(half & 0x8000) << 16; + let (exponent, fraction) = (u32::from(half >> 10 & 0x1f), u32::from(half & 0x3ff)); + f32::from_bits( + sign | match (exponent, fraction) { + (0, 0) => 0, + (0, _) => { + let shift = fraction.leading_zeros() - 21; + (113 - shift) << 23 | (fraction << shift & 0x3ff) << 13 + } + (31, 0) => 0x7f80_0000, + (31, _) => 0x7fc0_0000 | fraction << 13, + _ => (exponent + 112) << 23 | fraction << 13, + }, + ) +} + +/// Leaf `index` of a run of `count` packed leaves at `base`: its geometry, +/// flags, first and second primitive and vertex order. +fn packed_leaf(packed: &[u8], base: usize, count: usize, index: usize) -> Option<(u32, u8, u32, u32, u8)> { + Some(( + triple(packed, base + 3 * index)?, + *packed.get(base + 3 * count + index)?, + triple(packed, base + 4 * count + 3 * index)?, + triple(packed, base + 7 * count + 3 * index)?, + *packed.get(base + 10 * count + index)?, + )) +} + +/// Writes the leaves: for each, the corners of its first triangle, and the +/// corner a second triangle adds. +/// +/// A triangle node reads slots 0, 1 and 2, and the node of a second triangle +/// slots 1, 3 and 2. The order byte holds two fields of two bits for each +/// triangle, and becomes the first two bytes of the leaf's last word, a +/// nibble each. For a pair, the first triangle's corners go to the slots +/// after the ones its fields name, counting round: the first corner after the +/// first field, the second corner after the second field, the third corner in +/// the slot left. The second triangle gives its first corner when its first +/// field is 2, its second corner when its second field is 2, and its third +/// corner otherwise. A triangle alone keeps its corners in order whatever its +/// fields say. +/// +/// The rule for a pair is the one the rehydrator of the port-of-the-americas +/// project has (AGPL-3.0, revision 0f3be36; no code is taken from it). Every +/// order byte was then given to the title's own library, alone and in a pair, +/// and all 36 orders come out as here. +fn leaves( + header: &Header, + packed: &[u8], + out: &mut [u8], + triangle: &dyn Fn(u32, u32) -> Option<Triangle>, + transform: &dyn Fn(u32) -> Option<Transform>, +) -> Result<(), &'static str> { + let frame = Frame::new(header.frame, &header.bounds)?; + // The rows of the geometry last placed: leaves of one geometry come together. + let mut joined = None::<(u32, Option<Transform>)>; + let mut place = |geometry: u32, corner: [f32; 3]| { + if joined.is_none_or(|(of, _)| of != geometry) { + joined = Some((geometry, transform(geometry).map(|rows| frame.after(&rows)))); + } + match &joined { + Some((_, Some(rows))) => through(rows, corner), + _ => frame.place(corner), + } + }; + for first in (0..header.leaves).step_by(LEAVES_IN_RUN) { + let count = (header.leaves - first).min(LEAVES_IN_RUN); + let base = header.leaves_at + first * UNIT; + for index in 0..count { + let (geometry, flags, first_primitive, second_primitive, order) = + packed_leaf(packed, base, count, index).ok_or("leaf arrays outside the structure")?; + let corners = + triangle(geometry, first_primitive).ok_or("a leaf names a triangle the geometry does not have")?; + let mut slots = [[f32::NAN; 3]; 4]; + if second_primitive == NO_PRIMITIVE { + for (slot, corner) in corners.iter().enumerate() { + slots[slot] = place(geometry, *corner); + } + } else { + let fields: [usize; 4] = core::array::from_fn(|field| usize::from(order >> (2 * field) & 3)); + if fields.iter().any(|&field| field > 2) || fields[0] == fields[1] || fields[2] == fields[3] { + return Err("a leaf's vertex order is not an order"); + } + slots[(fields[0] + 2) % 3] = place(geometry, corners[0]); + slots[(fields[1] + 2) % 3] = place(geometry, corners[1]); + slots[(5 - fields[0] - fields[1]) % 3] = place(geometry, corners[2]); + let corners = + triangle(geometry, second_primitive).ok_or("a leaf names a triangle the geometry does not have")?; + let added = match (fields[2], fields[3]) { + (2, _) => 0, + (_, 2) => 1, + _ => 2, + }; + slots[3] = place(geometry, corners[added]); + } + let mut leaf = [0u8; UNIT]; + for (slot, corner) in slots.iter().enumerate() { + for (axis, value) in corner.iter().enumerate() { + leaf[12 * slot + 4 * axis..][..4].copy_from_slice(&value.to_bits().to_le_bytes()); + } + } + let second_primitive = if second_primitive == NO_PRIMITIVE { NO_NODE } else { second_primitive }; + let words = [ + geometry << 8 | u32::from(flags), + first_primitive, + second_primitive, + u32::from(order & 0xf) | u32::from(order >> 4) << 8, + ]; + for (index, word) in words.iter().enumerate() { + leaf[48 + 4 * index..][..4].copy_from_slice(&word.to_le_bytes()); + } + put(out, base + index * UNIT, &leaf).ok_or("leaves outside the structure")?; + } + } + Ok(()) +} + +/// The box a parent holds for the child at `child`: the corners a leaf's +/// node reads, or everything a box node's own slots hold. Box nodes at or +/// past `below` are not expanded yet. +fn seen(header: &Header, out: &[u8], child: u32, below: usize) -> Result<Bounds, &'static str> { + let at = target(child); + let read = |at| word(out, at).ok_or("a child outside the structure"); + let mut bounds = Bounds::NONE; + match child & 7 { + TRIANGLE => { + if at < header.leaves_at || (at - header.leaves_at) / UNIT >= header.leaves { + return Err("a child that is not one of the leaves"); + } + let corners = if read(at + 48)? & PAIR != 0 { 4 } else { 3 }; + for slot in 0..corners { + let corner = + [read(at + 12 * slot)?, read(at + 12 * slot + 4)?, read(at + 12 * slot + 8)?].map(f32::from_bits); + bounds.add(corner, corner); + } + } + kind @ (BOX16 | BOX32) => { + let size = if kind == BOX32 { WIDE } else { UNIT }; + if at < header.boxes_at || at + size > below { + return Err("a child that is not a box node of a lower level"); ~~~~ --- Right, and against what the file says of itself: what does not follow the packing is refused. Fixed in 4631d10b. A child pointer and the root are now held to a box node of their own size, at the place it begins. `boxes` keeps the pairs of the level table it has checked, and `Levels::begins` finds the level a pointer falls in by a binary search over them, so nothing is allocated by a count the input gives. A structure whose box nodes are off the 64-byte steps a pointer counts in is refused by name. One new test, which fails on 1474b05e: a 128-byte pointer to two 64-byte nodes, a 64-byte pointer to a 128-byte node and to its second half, a 128-byte pointer from the middle of one, a pointer to a node of the pointing node's own level, and the same for the root. Run again on this commit: - the comparison with the title's library: the 33 hand-built structures and the 70 captured ones (2,626,240 bytes) are still byte-identical, and the four with a turned frame are still refused; - 77 errors planted one at a time, eight of them in the new check: 75 fail a test. The other two are the two the description already names, which change nothing a caller could see; - Miri on the module's twelve tests, `check --no-gpu` (12 steps passed, the Python test that fails on `main` here still fails), and the Wine suite (477 passed; the three failures are the `scene_publication` tests that ask for a hardware device). The description is updated with these.
3kynox commented 2026-12-01 11:58:16 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by 3kynox on 2026-12-01T11:58:16Z.


@brcly a data point for this PR by itself. Ahmet-Dedeler ported this decoder into another runtime and ran ProjectScarlett with it on an M5 Max (his comment on #596): 1,739 structures (179 MiB) expanded from the title's data, none refused, and the game's own indirect light in the picture, read by the title's walks from the expanded trees. Here the same code expands up to about 1,000 structures a run, none refused.

So its effect has been seen, on another host, though not yet in TuxBox. If that is enough for this PR alone, it could land apart from #586 and #596, which still wait on your two conditions; the runs on main are in #586. If you would rather keep the three together, that is fine too.

<!-- greyfinch-sync:brcly/TuxBox:comment:7310437342 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/536#issuecomment-7310437342). Originally posted by [3kynox](https://github.com/3kynox) on 2026-12-01T11:58:16Z. --- @brcly a data point for this PR by itself. Ahmet-Dedeler ported this decoder into another runtime and ran ProjectScarlett with it on an M5 Max ([his comment on #596](https://github.com/brcly/TuxBox/pull/596#issuecomment-7303540170)): 1,739 structures (179 MiB) expanded from the title's data, none refused, and the game's own indirect light in the picture, read by the title's walks from the expanded trees. Here the same code expands up to about 1,000 structures a run, none refused. So its effect has been seen, on another host, though not yet in TuxBox. If that is enough for this PR alone, it could land apart from #586 and #596, which still wait on your two conditions; the runs on main are in [#586](https://github.com/brcly/TuxBox/pull/586#issuecomment-7308751217). If you would rather keep the three together, that is fine too.
brcly commented 2026-12-01 15:21:47 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by brcly on 2026-12-01T15:21:47Z.


Merged on its own, thanks @3kynox. The decoder now has outside evidence (Ahmet-Dedeler's run with the title's indirect light, none of 1,739 structures refused), and on main it does nothing until something calls it, so it can go ahead of #586 and #596.

<!-- greyfinch-sync:brcly/TuxBox:comment:7315783510 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/536#issuecomment-7315783510). Originally posted by [brcly](https://github.com/brcly) on 2026-12-01T15:21:47Z. --- Merged on its own, thanks @3kynox. The decoder now has outside evidence (Ahmet-Dedeler's run with the title's indirect light, none of 1,739 structures refused), and on main it does nothing until something calls it, so it can go ahead of #586 and #596.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
brcly/TuxBox!536
No description provided.