d3d12: write the structures a title builds for the ray walks #623

Merged
3kynox merged 1 commit from upstream-pr/623 into main 2026-12-01 22:41:10 +00:00
3kynox commented 2026-12-01 15:04:00 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by 3kynox on 2026-12-01T15:04:00Z.


Summary

On main, now that #536, #586 and #596 are merged. Part of #382: the row "dynamic bottom-level structures".

A title builds most of its bottom-level structures while it runs. Main leaves their instances out of the scenes (#596). This writes them, behind the same TUXBOX_CONSOLE_STRUCTURES=1.

  • The writer (console_structure.rs, box_tree.rs). A structure in the console's form from the triangles a build names: one triangle to a leaf, 128-byte box nodes, the parent table. The tree is its own; a walk only needs boxes that hold what is below them. The tests walk it with a CPU port of the traversal (console_walk.rs) and compare with brute force.
  • Which builds (TUXBOX_CONSOLE_BUILT). By default only those in packed positions, whose geometry is final in title memory when the build is called. A build in float positions is mostly a mesh the GPU writes after the call, so it is left out. late writes those too, at the call and once more when the GPU is past that frame; that only helps on a host whose GPU works in the title's own memory (section-import=aliased). 0 and all are for comparing pictures.
  • Bounding the buffer. Nothing tells the provider that the title dropped a structure. A structure named inside the bytes a later one is sure to cover, or whose own bytes reach a later one's address, is now given up.

What it does not do: build from what the GPU wrote on a host that substitutes the import, and pair triangles in a leaf as the console's builder does.

Tested

  • The checks relevant to this change passed
  • 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: AMD has not run it.

No Lanes scenario: Lanes builds no console-format structure and has no walk that reads one. The writer, the choice of builds and the overlap rule are covered by unit tests.

GPU, driver and backend: RTX 4070 Ti SUPER 16 GB, 620.73.04, GE-Proton11-14, vkd3d-proton.

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 ba24f252a976, no uncommitted changes, no GPU checks: 12 passed, 1 failed, 0 not run

The one failure is test_stage_baseline.GuestWatch, which fails on this machine on main too.

Commands run and their results:

cargo fmt --all --check                      clean
cargo clippy ... -p tuxbox-d3d12 -- -D warnings   clean (Rust 1.98.1)
tuxbox-d3d12 unit tests under Wine           596 passed, 3 failed, 8 ignored
                                             (the 3 are scene_publication, which need a hardware device)
python -m unittest tests.test_repository_hygiene   OK
cargo miri test ... -- console_heap console::tests console_structure box_tree   pass

In ProjectScarlett, one run each.

  • On 717a74c4, before this rebase: with packed positions only the main scene holds 765 to 779 of about 2,700 instances; with late, 2,550 to 2,590 of about 3,250 (of 8,192 builds in float positions read again, 5,777 were written at the second reading and 946 could not be read).
  • On 5523fc01 with this change and late, before the last rebase: 349 s of the world, then the title's own access violation, which the run without the switch ends on too (#625). The main scene holds 2,109 of 2,818 instances at the end; 4,096 structures written, 53 left out, 1,001 given up under later structures; of 2,048 builds read again, 128 were written at the second reading.

About the buffer in late: in that run it doubled up to its 1,024 MiB limit, with 594 MiB held when the title stopped. That is what the structures in it take, not places left behind: 4,096 built structures were written and 1,001 given up under later ones, beside about 900 rehydrated ones, so some 4,000 structures at about 150 KiB each, in a form that spends about 110 bytes a triangle (a 64-byte leaf, its share of the 128-byte box nodes and its parent entry). A scene that needs more than TUXBOX_CONSOLE_HEAP_MB loses the structures that find no room, and the log says so.

Still open: the structures written at the second reading have not been checked against a reference; the tests check the writer itself against brute force. There is no visible effect to show: see #586 for why. Under Miri the two tests that walk large structures use small ones.

Checks

CI runs the code checks. No evidence JSON changes.

<!-- greyfinch-sync:brcly/TuxBox:issue:5588399932 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/623). Originally posted by [3kynox](https://github.com/3kynox) on 2026-12-01T15:04:00Z. --- ## Summary On main, now that #536, #586 and #596 are merged. Part of #382: the row "dynamic bottom-level structures". A title builds most of its bottom-level structures while it runs. Main leaves their instances out of the scenes (#596). This writes them, behind the same `TUXBOX_CONSOLE_STRUCTURES=1`. - **The writer** (`console_structure.rs`, `box_tree.rs`). A structure in the console's form from the triangles a build names: one triangle to a leaf, 128-byte box nodes, the parent table. The tree is its own; a walk only needs boxes that hold what is below them. The tests walk it with a CPU port of the traversal (`console_walk.rs`) and compare with brute force. - **Which builds** (`TUXBOX_CONSOLE_BUILT`). By default only those in packed positions, whose geometry is final in title memory when the build is called. A build in float positions is mostly a mesh the GPU writes after the call, so it is left out. `late` writes those too, at the call and once more when the GPU is past that frame; that only helps on a host whose GPU works in the title's own memory (`section-import=aliased`). `0` and `all` are for comparing pictures. - **Bounding the buffer.** Nothing tells the provider that the title dropped a structure. A structure named inside the bytes a later one is sure to cover, or whose own bytes reach a later one's address, is now given up. What it does not do: build from what the GPU wrote on a host that substitutes the import, and pair triangles in a leaf as the console's builder does. ## Tested - [x] The checks relevant to this change passed - [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: AMD has not run it. No Lanes scenario: Lanes builds no console-format structure and has no walk that reads one. The writer, the choice of builds and the overlap rule are covered by unit tests. GPU, driver and backend: RTX 4070 Ti SUPER 16 GB, 620.73.04, GE-Proton11-14, vkd3d-proton. 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 ba24f252a976, no uncommitted changes, no GPU checks: 12 passed, 1 failed, 0 not run ``` The one failure is `test_stage_baseline.GuestWatch`, which fails on this machine on main too. Commands run and their results: ```text cargo fmt --all --check clean cargo clippy ... -p tuxbox-d3d12 -- -D warnings clean (Rust 1.98.1) tuxbox-d3d12 unit tests under Wine 596 passed, 3 failed, 8 ignored (the 3 are scene_publication, which need a hardware device) python -m unittest tests.test_repository_hygiene OK cargo miri test ... -- console_heap console::tests console_structure box_tree pass ``` In ProjectScarlett, one run each. - On `717a74c4`, before this rebase: with packed positions only the main scene holds 765 to 779 of about 2,700 instances; with `late`, 2,550 to 2,590 of about 3,250 (of 8,192 builds in float positions read again, 5,777 were written at the second reading and 946 could not be read). - On `5523fc01` with this change and `late`, before the last rebase: 349 s of the world, then the title's own access violation, which the run without the switch ends on too (#625). The main scene holds 2,109 of 2,818 instances at the end; 4,096 structures written, 53 left out, 1,001 given up under later structures; of 2,048 builds read again, 128 were written at the second reading. About the buffer in `late`: in that run it doubled up to its 1,024 MiB limit, with 594 MiB held when the title stopped. That is what the structures in it take, not places left behind: 4,096 built structures were written and 1,001 given up under later ones, beside about 900 rehydrated ones, so some 4,000 structures at about 150 KiB each, in a form that spends about 110 bytes a triangle (a 64-byte leaf, its share of the 128-byte box nodes and its parent entry). A scene that needs more than `TUXBOX_CONSOLE_HEAP_MB` loses the structures that find no room, and the log says so. Still open: the structures written at the second reading have not been checked against a reference; the tests check the writer itself against brute force. There is no visible effect to show: see #586 for why. Under Miri the two tests that walk large structures use small ones. ## Checks CI runs the code checks. No evidence JSON changes.
Copilot commented 2026-12-01 18:39:21 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by Copilot on 2026-12-01T18:39:21Z.

Code review location: runtime/d3d12/src/commands/build_raytracing/console.rs; line 268

@@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: *
     }
 }
 
-/// The bottom-level builds of a build call. A structure the title builds
-/// from geometry while it runs is not written yet, so whatever was placed
-/// under its address is no longer what the title has there.
+/// Which of the structures a title builds while it runs are written.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Built {
+    /// None: their instances stay out of the scenes.
+    None,
+    /// Those whose geometry is final at the call.
+    Settled,
+    /// Those, and the others read at the call and once more when the GPU is
+    /// past the frame: for a host whose GPU works in the title's own memory.
+    Late,
+    /// Every one the CPU can read at the call, right or not: for comparing pictures.
+    All,
+}
+
+/// What `TUXBOX_CONSOLE_BUILT` asks for.
+fn built_from(asked: Option<&str>) -> Built {
+    match asked.map(str::trim) {
+        Some("0") => Built::None,
+        Some("late") => Built::Late,
+        Some("all") => Built::All,
+        _ => Built::Settled,
+    }
+}
+
+fn built_mode() -> Built {
+    static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| {
+        let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref());
+        if mode != Built::Settled {
+            log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}"));
+        }
+        mode
+    });
+    *MODE
+}
+
+/// Why a build in float positions is left out.
+const UNSETTLED: &str = "float positions, which the GPU may write after the call";
+
+/// Whether title memory holds a geometry's final positions when its build is
+/// called. Packed positions are streamed in with the mesh and stay as they
+/// are. Float positions are what a skinned or simulated mesh is written in,
+/// by the GPU, after the title has recorded the build: read at the call they
+/// are an earlier frame's, or not positions at all.
+fn settled(format: DXGI_FORMAT) -> bool {
+    format == DXGI_FORMAT_R32G32_FLOAT
+}
+
+/// The geometry descriptions of one bottom-level build, copied: what is
+/// needed to read its triangles after the call as well.
 ///
 /// # Safety
-/// `owner` is the list's controlling guest device.
+/// `build` is the title's description, live for the call.
+unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> {
+    let inputs = &build.Inputs;
+    // SAFETY: the title supplies the descriptions for the duration of the call.
+    if !unsafe { ray_build::valid(inputs) } {
+        return Err("inputs that are not valid");
+    }
+    let mut out = Vec::new();
+    for index in 0..inputs.NumDescs as usize {
+        // SAFETY: `ray_build::valid` checked the layout and every pointer.
+        let description =
+            unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?;
+        if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES {
+            return Err("a geometry that is not triangles");
+        }
+        out.push(description);
+    }
+    Ok(out)
+}
+
+/// The vertex format of a triangle geometry.
+fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT {
+    // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles.
+    unsafe { description.Anonymous.Triangles.VertexFormat }
+}
+
+/// The structure over the triangles the descriptions name, as title memory
+/// holds them now.
+fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> {
+    let mut geometry = Vec::new();
+    for description in descriptions {
+        // SAFETY: as in `format`.
+        geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?);
+    }
+    let parts: Vec<(&title_geometry::Geometry, u32)> = geometry
+        .iter()
+        .zip(descriptions)
+        .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned()))
+        .collect();
+    console_structure::build(&parts)
+}
+
+/// A build to read again.
+struct Later {
+    geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>,
+    /// The present the GPU must be past: the one that follows the call.
+    due: u64,
+    /// Of the structure written at the call, 0 when none was.
+    digest: u64,
+}
+
+static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> =
+    std::sync::Mutex::new(std::collections::BTreeMap::new());

In late mode, this process-wide queue lets a build on device B consume device A's pending rereads using B's heap. That loses A's update and can publish A's geometry into B's heap, since entries carry no owner identity. Keep pending work with its owning device, or key and filter it by device identity with appropriate lifetime handling.

<!-- greyfinch-sync:brcly/TuxBox:review-comment:4759082682 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/623#discussion_r4759082682). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-12-01T18:39:21Z. **Code review location:** `runtime/d3d12/src/commands/build_raytracing/console.rs`; line 268 ~~~~diff @@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: * } } -/// The bottom-level builds of a build call. A structure the title builds -/// from geometry while it runs is not written yet, so whatever was placed -/// under its address is no longer what the title has there. +/// Which of the structures a title builds while it runs are written. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Built { + /// None: their instances stay out of the scenes. + None, + /// Those whose geometry is final at the call. + Settled, + /// Those, and the others read at the call and once more when the GPU is + /// past the frame: for a host whose GPU works in the title's own memory. + Late, + /// Every one the CPU can read at the call, right or not: for comparing pictures. + All, +} + +/// What `TUXBOX_CONSOLE_BUILT` asks for. +fn built_from(asked: Option<&str>) -> Built { + match asked.map(str::trim) { + Some("0") => Built::None, + Some("late") => Built::Late, + Some("all") => Built::All, + _ => Built::Settled, + } +} + +fn built_mode() -> Built { + static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| { + let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref()); + if mode != Built::Settled { + log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}")); + } + mode + }); + *MODE +} + +/// Why a build in float positions is left out. +const UNSETTLED: &str = "float positions, which the GPU may write after the call"; + +/// Whether title memory holds a geometry's final positions when its build is +/// called. Packed positions are streamed in with the mesh and stay as they +/// are. Float positions are what a skinned or simulated mesh is written in, +/// by the GPU, after the title has recorded the build: read at the call they +/// are an earlier frame's, or not positions at all. +fn settled(format: DXGI_FORMAT) -> bool { + format == DXGI_FORMAT_R32G32_FLOAT +} + +/// The geometry descriptions of one bottom-level build, copied: what is +/// needed to read its triangles after the call as well. /// /// # Safety -/// `owner` is the list's controlling guest device. +/// `build` is the title's description, live for the call. +unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> { + let inputs = &build.Inputs; + // SAFETY: the title supplies the descriptions for the duration of the call. + if !unsafe { ray_build::valid(inputs) } { + return Err("inputs that are not valid"); + } + let mut out = Vec::new(); + for index in 0..inputs.NumDescs as usize { + // SAFETY: `ray_build::valid` checked the layout and every pointer. + let description = + unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?; + if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES { + return Err("a geometry that is not triangles"); + } + out.push(description); + } + Ok(out) +} + +/// The vertex format of a triangle geometry. +fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT { + // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles. + unsafe { description.Anonymous.Triangles.VertexFormat } +} + +/// The structure over the triangles the descriptions name, as title memory +/// holds them now. +fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> { + let mut geometry = Vec::new(); + for description in descriptions { + // SAFETY: as in `format`. + geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?); + } + let parts: Vec<(&title_geometry::Geometry, u32)> = geometry + .iter() + .zip(descriptions) + .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned())) + .collect(); + console_structure::build(&parts) +} + +/// A build to read again. +struct Later { + geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, + /// The present the GPU must be past: the one that follows the call. + due: u64, + /// Of the structure written at the call, 0 when none was. + digest: u64, +} + +static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); ~~~~ --- In `late` mode, this process-wide queue lets a build on device B consume device A's pending rereads using B's heap. That loses A's update and can publish A's geometry into B's heap, since entries carry no owner identity. Keep pending work with its owning device, or key and filter it by device identity with appropriate lifetime handling.
Copilot commented 2026-12-01 18:39:21 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by Copilot on 2026-12-01T18:39:21Z.

Code review location: runtime/d3d12/src/commands/build_raytracing/console.rs; line 305

@@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: *
     }
 }
 
-/// The bottom-level builds of a build call. A structure the title builds
-/// from geometry while it runs is not written yet, so whatever was placed
-/// under its address is no longer what the title has there.
+/// Which of the structures a title builds while it runs are written.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Built {
+    /// None: their instances stay out of the scenes.
+    None,
+    /// Those whose geometry is final at the call.
+    Settled,
+    /// Those, and the others read at the call and once more when the GPU is
+    /// past the frame: for a host whose GPU works in the title's own memory.
+    Late,
+    /// Every one the CPU can read at the call, right or not: for comparing pictures.
+    All,
+}
+
+/// What `TUXBOX_CONSOLE_BUILT` asks for.
+fn built_from(asked: Option<&str>) -> Built {
+    match asked.map(str::trim) {
+        Some("0") => Built::None,
+        Some("late") => Built::Late,
+        Some("all") => Built::All,
+        _ => Built::Settled,
+    }
+}
+
+fn built_mode() -> Built {
+    static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| {
+        let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref());
+        if mode != Built::Settled {
+            log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}"));
+        }
+        mode
+    });
+    *MODE
+}
+
+/// Why a build in float positions is left out.
+const UNSETTLED: &str = "float positions, which the GPU may write after the call";
+
+/// Whether title memory holds a geometry's final positions when its build is
+/// called. Packed positions are streamed in with the mesh and stay as they
+/// are. Float positions are what a skinned or simulated mesh is written in,
+/// by the GPU, after the title has recorded the build: read at the call they
+/// are an earlier frame's, or not positions at all.
+fn settled(format: DXGI_FORMAT) -> bool {
+    format == DXGI_FORMAT_R32G32_FLOAT
+}
+
+/// The geometry descriptions of one bottom-level build, copied: what is
+/// needed to read its triangles after the call as well.
 ///
 /// # Safety
-/// `owner` is the list's controlling guest device.
+/// `build` is the title's description, live for the call.
+unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> {
+    let inputs = &build.Inputs;
+    // SAFETY: the title supplies the descriptions for the duration of the call.
+    if !unsafe { ray_build::valid(inputs) } {
+        return Err("inputs that are not valid");
+    }
+    let mut out = Vec::new();
+    for index in 0..inputs.NumDescs as usize {
+        // SAFETY: `ray_build::valid` checked the layout and every pointer.
+        let description =
+            unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?;
+        if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES {
+            return Err("a geometry that is not triangles");
+        }
+        out.push(description);
+    }
+    Ok(out)
+}
+
+/// The vertex format of a triangle geometry.
+fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT {
+    // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles.
+    unsafe { description.Anonymous.Triangles.VertexFormat }
+}
+
+/// The structure over the triangles the descriptions name, as title memory
+/// holds them now.
+fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> {
+    let mut geometry = Vec::new();
+    for description in descriptions {
+        // SAFETY: as in `format`.
+        geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?);
+    }
+    let parts: Vec<(&title_geometry::Geometry, u32)> = geometry
+        .iter()
+        .zip(descriptions)
+        .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned()))
+        .collect();
+    console_structure::build(&parts)
+}
+
+/// A build to read again.
+struct Later {
+    geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>,
+    /// The present the GPU must be past: the one that follows the call.
+    due: u64,
+    /// Of the structure written at the call, 0 when none was.
+    digest: u64,
+}
+
+static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> =
+    std::sync::Mutex::new(std::collections::BTreeMap::new());
+
+fn later() -> std::sync::MutexGuard<'static, std::collections::BTreeMap<u64, Later>> {
+    LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+/// The bytes of title memory the console's own structure is sure to cover
+/// for a structure this writer made: its header, and half a leaf for each
+/// triangle, since a console leaf holds two at most. The console's builder
+/// writes more than that, never less.
+fn least_extent(bytes: &[u8]) -> u64 {
+    let leaves = bytes.get(12..16).map_or(0, |word| u32::from_le_bytes(core::array::from_fn(|byte| word[byte])));
+    64 + 32 * u64::from(leaves)
+}
+
+/// A digest of a structure's bytes, never 0.
+fn digest(bytes: &[u8]) -> u64 {
+    bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3))
+        | 1
+}
+
+/// The builds whose second reading is due: each is read again and, when the
+/// GPU has changed its positions since the call, written anew.
+fn look_again(heap: &ConsoleHeap, device: &ID3D12Device) {
+    static READ: AtomicU64 = AtomicU64::new(0);
+    static CHANGED: AtomicU64 = AtomicU64::new(0);
+    static UNREADABLE: AtomicU64 = AtomicU64::new(0);
+    let now = console_heap::finished();
+    let due: Vec<(u64, Later)> = {
+        let mut later = later();
+        let ready: Vec<u64> = later.iter().filter(|(_, look)| look.due <= now).map(|(at, _)| *at).collect();
+        ready.into_iter().filter_map(|at| later.remove(&at).map(|look| (at, look))).collect()
+    };
+    for (destination, look) in due {
+        // Written at the call and given up since: the title has built over it.
+        if look.digest != 0 && heap.placed(destination).is_none() {
+            continue;
+        }

In late mode, a failed first read at 0x1400 leaves a zero-digest retry pending even if a newer structure at 0x1000 covers that address. This guard lets the obsolete retry publish if its geometry becomes readable, and its overlap claim then evicts the newer structure. Track pending-build validity independently of successful placement and cancel retries when a newer build overlaps their destination.

<!-- greyfinch-sync:brcly/TuxBox:review-comment:4759082790 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/623#discussion_r4759082790). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-12-01T18:39:21Z. **Code review location:** `runtime/d3d12/src/commands/build_raytracing/console.rs`; line 305 ~~~~diff @@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: * } } -/// The bottom-level builds of a build call. A structure the title builds -/// from geometry while it runs is not written yet, so whatever was placed -/// under its address is no longer what the title has there. +/// Which of the structures a title builds while it runs are written. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Built { + /// None: their instances stay out of the scenes. + None, + /// Those whose geometry is final at the call. + Settled, + /// Those, and the others read at the call and once more when the GPU is + /// past the frame: for a host whose GPU works in the title's own memory. + Late, + /// Every one the CPU can read at the call, right or not: for comparing pictures. + All, +} + +/// What `TUXBOX_CONSOLE_BUILT` asks for. +fn built_from(asked: Option<&str>) -> Built { + match asked.map(str::trim) { + Some("0") => Built::None, + Some("late") => Built::Late, + Some("all") => Built::All, + _ => Built::Settled, + } +} + +fn built_mode() -> Built { + static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| { + let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref()); + if mode != Built::Settled { + log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}")); + } + mode + }); + *MODE +} + +/// Why a build in float positions is left out. +const UNSETTLED: &str = "float positions, which the GPU may write after the call"; + +/// Whether title memory holds a geometry's final positions when its build is +/// called. Packed positions are streamed in with the mesh and stay as they +/// are. Float positions are what a skinned or simulated mesh is written in, +/// by the GPU, after the title has recorded the build: read at the call they +/// are an earlier frame's, or not positions at all. +fn settled(format: DXGI_FORMAT) -> bool { + format == DXGI_FORMAT_R32G32_FLOAT +} + +/// The geometry descriptions of one bottom-level build, copied: what is +/// needed to read its triangles after the call as well. /// /// # Safety -/// `owner` is the list's controlling guest device. +/// `build` is the title's description, live for the call. +unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> { + let inputs = &build.Inputs; + // SAFETY: the title supplies the descriptions for the duration of the call. + if !unsafe { ray_build::valid(inputs) } { + return Err("inputs that are not valid"); + } + let mut out = Vec::new(); + for index in 0..inputs.NumDescs as usize { + // SAFETY: `ray_build::valid` checked the layout and every pointer. + let description = + unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?; + if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES { + return Err("a geometry that is not triangles"); + } + out.push(description); + } + Ok(out) +} + +/// The vertex format of a triangle geometry. +fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT { + // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles. + unsafe { description.Anonymous.Triangles.VertexFormat } +} + +/// The structure over the triangles the descriptions name, as title memory +/// holds them now. +fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> { + let mut geometry = Vec::new(); + for description in descriptions { + // SAFETY: as in `format`. + geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?); + } + let parts: Vec<(&title_geometry::Geometry, u32)> = geometry + .iter() + .zip(descriptions) + .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned())) + .collect(); + console_structure::build(&parts) +} + +/// A build to read again. +struct Later { + geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, + /// The present the GPU must be past: the one that follows the call. + due: u64, + /// Of the structure written at the call, 0 when none was. + digest: u64, +} + +static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +fn later() -> std::sync::MutexGuard<'static, std::collections::BTreeMap<u64, Later>> { + LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// The bytes of title memory the console's own structure is sure to cover +/// for a structure this writer made: its header, and half a leaf for each +/// triangle, since a console leaf holds two at most. The console's builder +/// writes more than that, never less. +fn least_extent(bytes: &[u8]) -> u64 { + let leaves = bytes.get(12..16).map_or(0, |word| u32::from_le_bytes(core::array::from_fn(|byte| word[byte]))); + 64 + 32 * u64::from(leaves) +} + +/// A digest of a structure's bytes, never 0. +fn digest(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)) + | 1 +} + +/// The builds whose second reading is due: each is read again and, when the +/// GPU has changed its positions since the call, written anew. +fn look_again(heap: &ConsoleHeap, device: &ID3D12Device) { + static READ: AtomicU64 = AtomicU64::new(0); + static CHANGED: AtomicU64 = AtomicU64::new(0); + static UNREADABLE: AtomicU64 = AtomicU64::new(0); + let now = console_heap::finished(); + let due: Vec<(u64, Later)> = { + let mut later = later(); + let ready: Vec<u64> = later.iter().filter(|(_, look)| look.due <= now).map(|(at, _)| *at).collect(); + ready.into_iter().filter_map(|at| later.remove(&at).map(|look| (at, look))).collect() + }; + for (destination, look) in due { + // Written at the call and given up since: the title has built over it. + if look.digest != 0 && heap.placed(destination).is_none() { + continue; + } ~~~~ --- In `late` mode, a failed first read at 0x1400 leaves a zero-digest retry pending even if a newer structure at 0x1000 covers that address. This guard lets the obsolete retry publish if its geometry becomes readable, and its overlap claim then evicts the newer structure. Track pending-build validity independently of successful placement and cancel retries when a newer build overlaps their destination.
Copilot commented 2026-12-01 18:39:21 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by Copilot on 2026-12-01T18:39:21Z.

Code review location: runtime/d3d12/src/commands/build_raytracing/console.rs; line 305

@@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: *
     }
 }
 
-/// The bottom-level builds of a build call. A structure the title builds
-/// from geometry while it runs is not written yet, so whatever was placed
-/// under its address is no longer what the title has there.
+/// Which of the structures a title builds while it runs are written.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Built {
+    /// None: their instances stay out of the scenes.
+    None,
+    /// Those whose geometry is final at the call.
+    Settled,
+    /// Those, and the others read at the call and once more when the GPU is
+    /// past the frame: for a host whose GPU works in the title's own memory.
+    Late,
+    /// Every one the CPU can read at the call, right or not: for comparing pictures.
+    All,
+}
+
+/// What `TUXBOX_CONSOLE_BUILT` asks for.
+fn built_from(asked: Option<&str>) -> Built {
+    match asked.map(str::trim) {
+        Some("0") => Built::None,
+        Some("late") => Built::Late,
+        Some("all") => Built::All,
+        _ => Built::Settled,
+    }
+}
+
+fn built_mode() -> Built {
+    static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| {
+        let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref());
+        if mode != Built::Settled {
+            log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}"));
+        }
+        mode
+    });
+    *MODE
+}
+
+/// Why a build in float positions is left out.
+const UNSETTLED: &str = "float positions, which the GPU may write after the call";
+
+/// Whether title memory holds a geometry's final positions when its build is
+/// called. Packed positions are streamed in with the mesh and stay as they
+/// are. Float positions are what a skinned or simulated mesh is written in,
+/// by the GPU, after the title has recorded the build: read at the call they
+/// are an earlier frame's, or not positions at all.
+fn settled(format: DXGI_FORMAT) -> bool {
+    format == DXGI_FORMAT_R32G32_FLOAT
+}
+
+/// The geometry descriptions of one bottom-level build, copied: what is
+/// needed to read its triangles after the call as well.
 ///
 /// # Safety
-/// `owner` is the list's controlling guest device.
+/// `build` is the title's description, live for the call.
+unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> {
+    let inputs = &build.Inputs;
+    // SAFETY: the title supplies the descriptions for the duration of the call.
+    if !unsafe { ray_build::valid(inputs) } {
+        return Err("inputs that are not valid");
+    }
+    let mut out = Vec::new();
+    for index in 0..inputs.NumDescs as usize {
+        // SAFETY: `ray_build::valid` checked the layout and every pointer.
+        let description =
+            unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?;
+        if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES {
+            return Err("a geometry that is not triangles");
+        }
+        out.push(description);
+    }
+    Ok(out)
+}
+
+/// The vertex format of a triangle geometry.
+fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT {
+    // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles.
+    unsafe { description.Anonymous.Triangles.VertexFormat }
+}
+
+/// The structure over the triangles the descriptions name, as title memory
+/// holds them now.
+fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> {
+    let mut geometry = Vec::new();
+    for description in descriptions {
+        // SAFETY: as in `format`.
+        geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?);
+    }
+    let parts: Vec<(&title_geometry::Geometry, u32)> = geometry
+        .iter()
+        .zip(descriptions)
+        .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned()))
+        .collect();
+    console_structure::build(&parts)
+}
+
+/// A build to read again.
+struct Later {
+    geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>,
+    /// The present the GPU must be past: the one that follows the call.
+    due: u64,
+    /// Of the structure written at the call, 0 when none was.
+    digest: u64,
+}
+
+static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> =
+    std::sync::Mutex::new(std::collections::BTreeMap::new());
+
+fn later() -> std::sync::MutexGuard<'static, std::collections::BTreeMap<u64, Later>> {
+    LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+/// The bytes of title memory the console's own structure is sure to cover
+/// for a structure this writer made: its header, and half a leaf for each
+/// triangle, since a console leaf holds two at most. The console's builder
+/// writes more than that, never less.
+fn least_extent(bytes: &[u8]) -> u64 {
+    let leaves = bytes.get(12..16).map_or(0, |word| u32::from_le_bytes(core::array::from_fn(|byte| word[byte])));
+    64 + 32 * u64::from(leaves)
+}
+
+/// A digest of a structure's bytes, never 0.
+fn digest(bytes: &[u8]) -> u64 {
+    bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3))
+        | 1
+}
+
+/// The builds whose second reading is due: each is read again and, when the
+/// GPU has changed its positions since the call, written anew.
+fn look_again(heap: &ConsoleHeap, device: &ID3D12Device) {
+    static READ: AtomicU64 = AtomicU64::new(0);
+    static CHANGED: AtomicU64 = AtomicU64::new(0);
+    static UNREADABLE: AtomicU64 = AtomicU64::new(0);
+    let now = console_heap::finished();
+    let due: Vec<(u64, Later)> = {
+        let mut later = later();
+        let ready: Vec<u64> = later.iter().filter(|(_, look)| look.due <= now).map(|(at, _)| *at).collect();
+        ready.into_iter().filter_map(|at| later.remove(&at).map(|look| (at, look))).collect()
+    };
+    for (destination, look) in due {
+        // Written at the call and given up since: the title has built over it.
+        if look.digest != 0 && heap.placed(destination).is_none() {
+            continue;
+        }

In late mode, another command-list thread can rebuild this destination after the pending reread is removed from LATER but before it publishes. Removing the pending entry cannot cancel that detached work, so the old reread can replace the newer structure despite this existence check. Track a build generation and validate it atomically with publication and rebuild invalidation.

<!-- greyfinch-sync:brcly/TuxBox:review-comment:4759082863 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/623#discussion_r4759082863). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-12-01T18:39:21Z. **Code review location:** `runtime/d3d12/src/commands/build_raytracing/console.rs`; line 305 ~~~~diff @@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: * } } -/// The bottom-level builds of a build call. A structure the title builds -/// from geometry while it runs is not written yet, so whatever was placed -/// under its address is no longer what the title has there. +/// Which of the structures a title builds while it runs are written. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Built { + /// None: their instances stay out of the scenes. + None, + /// Those whose geometry is final at the call. + Settled, + /// Those, and the others read at the call and once more when the GPU is + /// past the frame: for a host whose GPU works in the title's own memory. + Late, + /// Every one the CPU can read at the call, right or not: for comparing pictures. + All, +} + +/// What `TUXBOX_CONSOLE_BUILT` asks for. +fn built_from(asked: Option<&str>) -> Built { + match asked.map(str::trim) { + Some("0") => Built::None, + Some("late") => Built::Late, + Some("all") => Built::All, + _ => Built::Settled, + } +} + +fn built_mode() -> Built { + static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| { + let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref()); + if mode != Built::Settled { + log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}")); + } + mode + }); + *MODE +} + +/// Why a build in float positions is left out. +const UNSETTLED: &str = "float positions, which the GPU may write after the call"; + +/// Whether title memory holds a geometry's final positions when its build is +/// called. Packed positions are streamed in with the mesh and stay as they +/// are. Float positions are what a skinned or simulated mesh is written in, +/// by the GPU, after the title has recorded the build: read at the call they +/// are an earlier frame's, or not positions at all. +fn settled(format: DXGI_FORMAT) -> bool { + format == DXGI_FORMAT_R32G32_FLOAT +} + +/// The geometry descriptions of one bottom-level build, copied: what is +/// needed to read its triangles after the call as well. /// /// # Safety -/// `owner` is the list's controlling guest device. +/// `build` is the title's description, live for the call. +unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> { + let inputs = &build.Inputs; + // SAFETY: the title supplies the descriptions for the duration of the call. + if !unsafe { ray_build::valid(inputs) } { + return Err("inputs that are not valid"); + } + let mut out = Vec::new(); + for index in 0..inputs.NumDescs as usize { + // SAFETY: `ray_build::valid` checked the layout and every pointer. + let description = + unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?; + if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES { + return Err("a geometry that is not triangles"); + } + out.push(description); + } + Ok(out) +} + +/// The vertex format of a triangle geometry. +fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT { + // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles. + unsafe { description.Anonymous.Triangles.VertexFormat } +} + +/// The structure over the triangles the descriptions name, as title memory +/// holds them now. +fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> { + let mut geometry = Vec::new(); + for description in descriptions { + // SAFETY: as in `format`. + geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?); + } + let parts: Vec<(&title_geometry::Geometry, u32)> = geometry + .iter() + .zip(descriptions) + .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned())) + .collect(); + console_structure::build(&parts) +} + +/// A build to read again. +struct Later { + geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, + /// The present the GPU must be past: the one that follows the call. + due: u64, + /// Of the structure written at the call, 0 when none was. + digest: u64, +} + +static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +fn later() -> std::sync::MutexGuard<'static, std::collections::BTreeMap<u64, Later>> { + LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// The bytes of title memory the console's own structure is sure to cover +/// for a structure this writer made: its header, and half a leaf for each +/// triangle, since a console leaf holds two at most. The console's builder +/// writes more than that, never less. +fn least_extent(bytes: &[u8]) -> u64 { + let leaves = bytes.get(12..16).map_or(0, |word| u32::from_le_bytes(core::array::from_fn(|byte| word[byte]))); + 64 + 32 * u64::from(leaves) +} + +/// A digest of a structure's bytes, never 0. +fn digest(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)) + | 1 +} + +/// The builds whose second reading is due: each is read again and, when the +/// GPU has changed its positions since the call, written anew. +fn look_again(heap: &ConsoleHeap, device: &ID3D12Device) { + static READ: AtomicU64 = AtomicU64::new(0); + static CHANGED: AtomicU64 = AtomicU64::new(0); + static UNREADABLE: AtomicU64 = AtomicU64::new(0); + let now = console_heap::finished(); + let due: Vec<(u64, Later)> = { + let mut later = later(); + let ready: Vec<u64> = later.iter().filter(|(_, look)| look.due <= now).map(|(at, _)| *at).collect(); + ready.into_iter().filter_map(|at| later.remove(&at).map(|look| (at, look))).collect() + }; + for (destination, look) in due { + // Written at the call and given up since: the title has built over it. + if look.digest != 0 && heap.placed(destination).is_none() { + continue; + } ~~~~ --- In `late` mode, another command-list thread can rebuild this destination after the pending reread is removed from `LATER` but before it publishes. Removing the pending entry cannot cancel that detached work, so the old reread can replace the newer structure despite this existence check. Track a build generation and validate it atomically with publication and rebuild invalidation.
copilot-pull-request-reviewer[bot] commented 2026-12-01 18:39:22 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by copilot-pull-request-reviewer[bot] on 2026-12-01T18:39:22Z.

Review: COMMENTED


Critical overlap-invalidation and late-mode queue defects can retain overwritten structures, publish geometry to the wrong device, and let obsolete rereads replace or evict newer builds.

4 open issues
What changed in this PR

Extends the opt-in console ray-walk support to structures built from geometry at runtime, advancing #382 beyond the static structures handled by earlier PRs.

Changes:

  • Adds a console-format structure writer and four-way bounding-box tree, with CPU traversal tests against brute-force triangle intersections.
  • Adds build-selection modes, including delayed rereads for GPU-written float positions.
  • Tracks overlapping title-memory ranges to retire overwritten structures.
File Description
runtime/​d3d12/​src/​tests/​device/​console_heap.rs Tests overlap retirement and extent bookkeeping.
runtime/​d3d12/​src/​tests/​commands/​console.rs Tests build modes, position selection, and digests.
runtime/​d3d12/​src/​tests/​commands/​console_walk.rs Adds CPU traversal helpers for structure validation.
runtime/​d3d12/​src/​tests/​commands/​console_structure.rs Tests structure layout, geometry handling, and ray hits.
runtime/​d3d12/​src/​tests/​commands/​box_tree.rs Tests tree coverage, bounds, and determinism.
runtime/​d3d12/​src/​device/​console_heap.rs Adds overlap bookkeeping and exposes frame progress.
runtime/​d3d12/​src/​commands/​build_raytracing/​title_geometry.rs Adds triangle counting and transformed-corner access.
runtime/​d3d12/​src/​commands/​build_raytracing/​console.rs Wires runtime builds, delayed rereads, and diagnostics.
runtime/​d3d12/​src/​commands/​build_raytracing/​console_structure.rs Encodes triangles into console-format structures.
runtime/​d3d12/​src/​commands/​build_raytracing/​box_tree.rs Builds four-way bounding-box trees.
runtime/​d3d12/​src/​commands/​build_raytracing.rs Registers the tree and structure-writer modules.
docs/​ENVIRONMENT.md Documents TUXBOX_CONSOLE_BUILT modes and limitations.

Review effort: Balanced

<!-- greyfinch-sync:brcly/TuxBox:review:6137647502 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/623#pullrequestreview-6137647502). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-12-01T18:39:22Z. **Review:** COMMENTED --- <!-- ccr-overview-v2 --> ### 🟡 Changes recommended Critical overlap-invalidation and late-mode queue defects can retain overwritten structures, publish geometry to the wrong device, and let obsolete rereads replace or evict newer builds. <details open> <summary><strong>4 open issues</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> [Scope pending rereads to their owning device](https://github.com/brcly/TuxBox/pull/623#discussion_r4759082682) · New - <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> [Cancel pending retries when a newer build overlaps](https://github.com/brcly/TuxBox/pull/623#discussion_r4759082790) · New - <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> [Prevent stale rereads from publishing after a rebuild](https://github.com/brcly/TuxBox/pull/623#discussion_r4759082863) · New - <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> [Claim overlapping structures even when buffer allocation fails](https://github.com/brcly/TuxBox/pull/623#discussion_r4759082963) · New </details> <details> <summary><strong>What changed in this PR</strong></summary> Extends the opt-in console ray-walk support to structures built from geometry at runtime, advancing #382 beyond the static structures handled by earlier PRs. **Changes:** - Adds a console-format structure writer and four-way bounding-box tree, with CPU traversal tests against brute-force triangle intersections. - Adds build-selection modes, including delayed rereads for GPU-written float positions. - Tracks overlapping title-memory ranges to retire overwritten structures. | File | Description | | ---- | ----------- | | `runtime/​d3d12/​src/​tests/​device/​console_heap.rs` | Tests overlap retirement and extent bookkeeping. | | `runtime/​d3d12/​src/​tests/​commands/​console.rs` | Tests build modes, position selection, and digests. | | `runtime/​d3d12/​src/​tests/​commands/​console_walk.rs` | Adds CPU traversal helpers for structure validation. | | `runtime/​d3d12/​src/​tests/​commands/​console_structure.rs` | Tests structure layout, geometry handling, and ray hits. | | `runtime/​d3d12/​src/​tests/​commands/​box_tree.rs` | Tests tree coverage, bounds, and determinism. | | `runtime/​d3d12/​src/​device/​console_heap.rs` | Adds overlap bookkeeping and exposes frame progress. | | `runtime/​d3d12/​src/​commands/​build_raytracing/​title_geometry.rs` | Adds triangle counting and transformed-corner access. | | `runtime/​d3d12/​src/​commands/​build_raytracing/​console.rs` | Wires runtime builds, delayed rereads, and diagnostics. | | `runtime/​d3d12/​src/​commands/​build_raytracing/​console_structure.rs` | Encodes triangles into console-format structures. | | `runtime/​d3d12/​src/​commands/​build_raytracing/​box_tree.rs` | Builds four-way bounding-box trees. | | `runtime/​d3d12/​src/​commands/​build_raytracing.rs` | Registers the tree and structure-writer modules. | | `docs/​ENVIRONMENT.md` | Documents `TUXBOX_CONSOLE_BUILT` modes and limitations. | </details> <sub>Review effort: Balanced</sub>
Copilot commented 2026-12-01 18:39:22 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by Copilot on 2026-12-01T18:39:22Z.

Code review location: runtime/d3d12/src/device/console_heap.rs; line 639

@@ -592,13 +623,26 @@ impl ConsoleHeap {
     /// Places an expanded bottom-level structure and names it by the
     /// addresses the title knows it at. False when it could not be placed:
     /// those addresses then name nothing.
-    pub(crate) fn structure(&self, device: &ID3D12Device, addresses: &[u64], bytes: &[u8]) -> bool {
+    ///
+    /// `extent` is how many bytes of title memory the title's own structure
+    /// is sure to cover from each address: what was named inside them is
+    /// given up (`Book::claim`). 0 claims nothing.
+    pub(crate) fn structure(&self, device: &ID3D12Device, addresses: &[u64], bytes: &[u8], extent: u64) -> bool {
         let mut inner = self.lock();
         let placed = bytes
             .get(..64)
             .and_then(|header| <[u8; 64]>::try_from(header).ok())
             .and_then(|header| Some(Placed { offset: inner.write(device, bytes)?, header }));
-        inner.book.structure(addresses, placed, bytes.len() as u64, presents())
+        let now = presents();
+        if placed.is_some() {
+            inner.book.claim(addresses, extent, now);
+        }

Overlap invalidation must happen even when the replacement cannot fit in the provider buffer. If the title builds over a structure at another address while the buffer is full, this branch skips claim and forgets only the replacement's exact destination, leaving the overwritten structure available to later scenes. Apply the claim independently of allocation success.

<!-- greyfinch-sync:brcly/TuxBox:review-comment:4759082963 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/623#discussion_r4759082963). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-12-01T18:39:22Z. **Code review location:** `runtime/d3d12/src/device/console_heap.rs`; line 639 ~~~~diff @@ -592,13 +623,26 @@ impl ConsoleHeap { /// Places an expanded bottom-level structure and names it by the /// addresses the title knows it at. False when it could not be placed: /// those addresses then name nothing. - pub(crate) fn structure(&self, device: &ID3D12Device, addresses: &[u64], bytes: &[u8]) -> bool { + /// + /// `extent` is how many bytes of title memory the title's own structure + /// is sure to cover from each address: what was named inside them is + /// given up (`Book::claim`). 0 claims nothing. + pub(crate) fn structure(&self, device: &ID3D12Device, addresses: &[u64], bytes: &[u8], extent: u64) -> bool { let mut inner = self.lock(); let placed = bytes .get(..64) .and_then(|header| <[u8; 64]>::try_from(header).ok()) .and_then(|header| Some(Placed { offset: inner.write(device, bytes)?, header })); - inner.book.structure(addresses, placed, bytes.len() as u64, presents()) + let now = presents(); + if placed.is_some() { + inner.book.claim(addresses, extent, now); + } ~~~~ --- Overlap invalidation must happen even when the replacement cannot fit in the provider buffer. If the title builds over a structure at another address while the buffer is full, this branch skips `claim` and forgets only the replacement's exact destination, leaving the overwritten structure available to later scenes. Apply the claim independently of allocation success.
3kynox commented 2026-12-01 22:26:19 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by 3kynox on 2026-12-01T22:26:19Z.

Code review location: runtime/d3d12/src/commands/build_raytracing/console.rs; line 268

@@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: *
     }
 }
 
-/// The bottom-level builds of a build call. A structure the title builds
-/// from geometry while it runs is not written yet, so whatever was placed
-/// under its address is no longer what the title has there.
+/// Which of the structures a title builds while it runs are written.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Built {
+    /// None: their instances stay out of the scenes.
+    None,
+    /// Those whose geometry is final at the call.
+    Settled,
+    /// Those, and the others read at the call and once more when the GPU is
+    /// past the frame: for a host whose GPU works in the title's own memory.
+    Late,
+    /// Every one the CPU can read at the call, right or not: for comparing pictures.
+    All,
+}
+
+/// What `TUXBOX_CONSOLE_BUILT` asks for.
+fn built_from(asked: Option<&str>) -> Built {
+    match asked.map(str::trim) {
+        Some("0") => Built::None,
+        Some("late") => Built::Late,
+        Some("all") => Built::All,
+        _ => Built::Settled,
+    }
+}
+
+fn built_mode() -> Built {
+    static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| {
+        let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref());
+        if mode != Built::Settled {
+            log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}"));
+        }
+        mode
+    });
+    *MODE
+}
+
+/// Why a build in float positions is left out.
+const UNSETTLED: &str = "float positions, which the GPU may write after the call";
+
+/// Whether title memory holds a geometry's final positions when its build is
+/// called. Packed positions are streamed in with the mesh and stay as they
+/// are. Float positions are what a skinned or simulated mesh is written in,
+/// by the GPU, after the title has recorded the build: read at the call they
+/// are an earlier frame's, or not positions at all.
+fn settled(format: DXGI_FORMAT) -> bool {
+    format == DXGI_FORMAT_R32G32_FLOAT
+}
+
+/// The geometry descriptions of one bottom-level build, copied: what is
+/// needed to read its triangles after the call as well.
 ///
 /// # Safety
-/// `owner` is the list's controlling guest device.
+/// `build` is the title's description, live for the call.
+unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> {
+    let inputs = &build.Inputs;
+    // SAFETY: the title supplies the descriptions for the duration of the call.
+    if !unsafe { ray_build::valid(inputs) } {
+        return Err("inputs that are not valid");
+    }
+    let mut out = Vec::new();
+    for index in 0..inputs.NumDescs as usize {
+        // SAFETY: `ray_build::valid` checked the layout and every pointer.
+        let description =
+            unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?;
+        if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES {
+            return Err("a geometry that is not triangles");
+        }
+        out.push(description);
+    }
+    Ok(out)
+}
+
+/// The vertex format of a triangle geometry.
+fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT {
+    // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles.
+    unsafe { description.Anonymous.Triangles.VertexFormat }
+}
+
+/// The structure over the triangles the descriptions name, as title memory
+/// holds them now.
+fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> {
+    let mut geometry = Vec::new();
+    for description in descriptions {
+        // SAFETY: as in `format`.
+        geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?);
+    }
+    let parts: Vec<(&title_geometry::Geometry, u32)> = geometry
+        .iter()
+        .zip(descriptions)
+        .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned()))
+        .collect();
+    console_structure::build(&parts)
+}
+
+/// A build to read again.
+struct Later {
+    geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>,
+    /// The present the GPU must be past: the one that follows the call.
+    due: u64,
+    /// Of the structure written at the call, 0 when none was.
+    digest: u64,
+}
+
+static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> =
+    std::sync::Mutex::new(std::collections::BTreeMap::new());

Fixed in ba24f252: the pending readings now belong to the device's buffer (Reread, kept in console_heap.rs under the buffer's lock), so a build on one device cannot take another's. Test: a_reading_waits_in_its_own_buffer_only_and_only_for_the_last_build_at_its_address.

<!-- greyfinch-sync:brcly/TuxBox:review-comment:4761902202 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/623#discussion_r4761902202). Originally posted by [3kynox](https://github.com/3kynox) on 2026-12-01T22:26:19Z. **Code review location:** `runtime/d3d12/src/commands/build_raytracing/console.rs`; line 268 ~~~~diff @@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: * } } -/// The bottom-level builds of a build call. A structure the title builds -/// from geometry while it runs is not written yet, so whatever was placed -/// under its address is no longer what the title has there. +/// Which of the structures a title builds while it runs are written. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Built { + /// None: their instances stay out of the scenes. + None, + /// Those whose geometry is final at the call. + Settled, + /// Those, and the others read at the call and once more when the GPU is + /// past the frame: for a host whose GPU works in the title's own memory. + Late, + /// Every one the CPU can read at the call, right or not: for comparing pictures. + All, +} + +/// What `TUXBOX_CONSOLE_BUILT` asks for. +fn built_from(asked: Option<&str>) -> Built { + match asked.map(str::trim) { + Some("0") => Built::None, + Some("late") => Built::Late, + Some("all") => Built::All, + _ => Built::Settled, + } +} + +fn built_mode() -> Built { + static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| { + let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref()); + if mode != Built::Settled { + log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}")); + } + mode + }); + *MODE +} + +/// Why a build in float positions is left out. +const UNSETTLED: &str = "float positions, which the GPU may write after the call"; + +/// Whether title memory holds a geometry's final positions when its build is +/// called. Packed positions are streamed in with the mesh and stay as they +/// are. Float positions are what a skinned or simulated mesh is written in, +/// by the GPU, after the title has recorded the build: read at the call they +/// are an earlier frame's, or not positions at all. +fn settled(format: DXGI_FORMAT) -> bool { + format == DXGI_FORMAT_R32G32_FLOAT +} + +/// The geometry descriptions of one bottom-level build, copied: what is +/// needed to read its triangles after the call as well. /// /// # Safety -/// `owner` is the list's controlling guest device. +/// `build` is the title's description, live for the call. +unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> { + let inputs = &build.Inputs; + // SAFETY: the title supplies the descriptions for the duration of the call. + if !unsafe { ray_build::valid(inputs) } { + return Err("inputs that are not valid"); + } + let mut out = Vec::new(); + for index in 0..inputs.NumDescs as usize { + // SAFETY: `ray_build::valid` checked the layout and every pointer. + let description = + unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?; + if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES { + return Err("a geometry that is not triangles"); + } + out.push(description); + } + Ok(out) +} + +/// The vertex format of a triangle geometry. +fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT { + // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles. + unsafe { description.Anonymous.Triangles.VertexFormat } +} + +/// The structure over the triangles the descriptions name, as title memory +/// holds them now. +fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> { + let mut geometry = Vec::new(); + for description in descriptions { + // SAFETY: as in `format`. + geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?); + } + let parts: Vec<(&title_geometry::Geometry, u32)> = geometry + .iter() + .zip(descriptions) + .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned())) + .collect(); + console_structure::build(&parts) +} + +/// A build to read again. +struct Later { + geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, + /// The present the GPU must be past: the one that follows the call. + due: u64, + /// Of the structure written at the call, 0 when none was. + digest: u64, +} + +static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); ~~~~ --- Fixed in `ba24f252`: the pending readings now belong to the device's buffer (`Reread`, kept in `console_heap.rs` under the buffer's lock), so a build on one device cannot take another's. Test: `a_reading_waits_in_its_own_buffer_only_and_only_for_the_last_build_at_its_address`.
3kynox commented 2026-12-01 22:26:21 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by 3kynox on 2026-12-01T22:26:21Z.

Code review location: runtime/d3d12/src/commands/build_raytracing/console.rs; line 305

@@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: *
     }
 }
 
-/// The bottom-level builds of a build call. A structure the title builds
-/// from geometry while it runs is not written yet, so whatever was placed
-/// under its address is no longer what the title has there.
+/// Which of the structures a title builds while it runs are written.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Built {
+    /// None: their instances stay out of the scenes.
+    None,
+    /// Those whose geometry is final at the call.
+    Settled,
+    /// Those, and the others read at the call and once more when the GPU is
+    /// past the frame: for a host whose GPU works in the title's own memory.
+    Late,
+    /// Every one the CPU can read at the call, right or not: for comparing pictures.
+    All,
+}
+
+/// What `TUXBOX_CONSOLE_BUILT` asks for.
+fn built_from(asked: Option<&str>) -> Built {
+    match asked.map(str::trim) {
+        Some("0") => Built::None,
+        Some("late") => Built::Late,
+        Some("all") => Built::All,
+        _ => Built::Settled,
+    }
+}
+
+fn built_mode() -> Built {
+    static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| {
+        let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref());
+        if mode != Built::Settled {
+            log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}"));
+        }
+        mode
+    });
+    *MODE
+}
+
+/// Why a build in float positions is left out.
+const UNSETTLED: &str = "float positions, which the GPU may write after the call";
+
+/// Whether title memory holds a geometry's final positions when its build is
+/// called. Packed positions are streamed in with the mesh and stay as they
+/// are. Float positions are what a skinned or simulated mesh is written in,
+/// by the GPU, after the title has recorded the build: read at the call they
+/// are an earlier frame's, or not positions at all.
+fn settled(format: DXGI_FORMAT) -> bool {
+    format == DXGI_FORMAT_R32G32_FLOAT
+}
+
+/// The geometry descriptions of one bottom-level build, copied: what is
+/// needed to read its triangles after the call as well.
 ///
 /// # Safety
-/// `owner` is the list's controlling guest device.
+/// `build` is the title's description, live for the call.
+unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> {
+    let inputs = &build.Inputs;
+    // SAFETY: the title supplies the descriptions for the duration of the call.
+    if !unsafe { ray_build::valid(inputs) } {
+        return Err("inputs that are not valid");
+    }
+    let mut out = Vec::new();
+    for index in 0..inputs.NumDescs as usize {
+        // SAFETY: `ray_build::valid` checked the layout and every pointer.
+        let description =
+            unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?;
+        if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES {
+            return Err("a geometry that is not triangles");
+        }
+        out.push(description);
+    }
+    Ok(out)
+}
+
+/// The vertex format of a triangle geometry.
+fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT {
+    // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles.
+    unsafe { description.Anonymous.Triangles.VertexFormat }
+}
+
+/// The structure over the triangles the descriptions name, as title memory
+/// holds them now.
+fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> {
+    let mut geometry = Vec::new();
+    for description in descriptions {
+        // SAFETY: as in `format`.
+        geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?);
+    }
+    let parts: Vec<(&title_geometry::Geometry, u32)> = geometry
+        .iter()
+        .zip(descriptions)
+        .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned()))
+        .collect();
+    console_structure::build(&parts)
+}
+
+/// A build to read again.
+struct Later {
+    geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>,
+    /// The present the GPU must be past: the one that follows the call.
+    due: u64,
+    /// Of the structure written at the call, 0 when none was.
+    digest: u64,
+}
+
+static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> =
+    std::sync::Mutex::new(std::collections::BTreeMap::new());
+
+fn later() -> std::sync::MutexGuard<'static, std::collections::BTreeMap<u64, Later>> {
+    LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+/// The bytes of title memory the console's own structure is sure to cover
+/// for a structure this writer made: its header, and half a leaf for each
+/// triangle, since a console leaf holds two at most. The console's builder
+/// writes more than that, never less.
+fn least_extent(bytes: &[u8]) -> u64 {
+    let leaves = bytes.get(12..16).map_or(0, |word| u32::from_le_bytes(core::array::from_fn(|byte| word[byte])));
+    64 + 32 * u64::from(leaves)
+}
+
+/// A digest of a structure's bytes, never 0.
+fn digest(bytes: &[u8]) -> u64 {
+    bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3))
+        | 1
+}
+
+/// The builds whose second reading is due: each is read again and, when the
+/// GPU has changed its positions since the call, written anew.
+fn look_again(heap: &ConsoleHeap, device: &ID3D12Device) {
+    static READ: AtomicU64 = AtomicU64::new(0);
+    static CHANGED: AtomicU64 = AtomicU64::new(0);
+    static UNREADABLE: AtomicU64 = AtomicU64::new(0);
+    let now = console_heap::finished();
+    let due: Vec<(u64, Later)> = {
+        let mut later = later();
+        let ready: Vec<u64> = later.iter().filter(|(_, look)| look.due <= now).map(|(at, _)| *at).collect();
+        ready.into_iter().filter_map(|at| later.remove(&at).map(|look| (at, look))).collect()
+    };
+    for (destination, look) in due {
+        // Written at the call and given up since: the title has built over it.
+        if look.digest != 0 && heap.placed(destination).is_none() {
+            continue;
+        }

Fixed in ba24f252: a claim now makes stale every reading pending for a build at an address inside the claimed bytes, whether that build placed a structure or not (Book::claim, Book::stale). Test: a_reading_pending_at_an_address_a_later_structure_covers_is_dropped.

<!-- greyfinch-sync:brcly/TuxBox:review-comment:4761902516 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/623#discussion_r4761902516). Originally posted by [3kynox](https://github.com/3kynox) on 2026-12-01T22:26:21Z. **Code review location:** `runtime/d3d12/src/commands/build_raytracing/console.rs`; line 305 ~~~~diff @@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: * } } -/// The bottom-level builds of a build call. A structure the title builds -/// from geometry while it runs is not written yet, so whatever was placed -/// under its address is no longer what the title has there. +/// Which of the structures a title builds while it runs are written. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Built { + /// None: their instances stay out of the scenes. + None, + /// Those whose geometry is final at the call. + Settled, + /// Those, and the others read at the call and once more when the GPU is + /// past the frame: for a host whose GPU works in the title's own memory. + Late, + /// Every one the CPU can read at the call, right or not: for comparing pictures. + All, +} + +/// What `TUXBOX_CONSOLE_BUILT` asks for. +fn built_from(asked: Option<&str>) -> Built { + match asked.map(str::trim) { + Some("0") => Built::None, + Some("late") => Built::Late, + Some("all") => Built::All, + _ => Built::Settled, + } +} + +fn built_mode() -> Built { + static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| { + let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref()); + if mode != Built::Settled { + log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}")); + } + mode + }); + *MODE +} + +/// Why a build in float positions is left out. +const UNSETTLED: &str = "float positions, which the GPU may write after the call"; + +/// Whether title memory holds a geometry's final positions when its build is +/// called. Packed positions are streamed in with the mesh and stay as they +/// are. Float positions are what a skinned or simulated mesh is written in, +/// by the GPU, after the title has recorded the build: read at the call they +/// are an earlier frame's, or not positions at all. +fn settled(format: DXGI_FORMAT) -> bool { + format == DXGI_FORMAT_R32G32_FLOAT +} + +/// The geometry descriptions of one bottom-level build, copied: what is +/// needed to read its triangles after the call as well. /// /// # Safety -/// `owner` is the list's controlling guest device. +/// `build` is the title's description, live for the call. +unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> { + let inputs = &build.Inputs; + // SAFETY: the title supplies the descriptions for the duration of the call. + if !unsafe { ray_build::valid(inputs) } { + return Err("inputs that are not valid"); + } + let mut out = Vec::new(); + for index in 0..inputs.NumDescs as usize { + // SAFETY: `ray_build::valid` checked the layout and every pointer. + let description = + unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?; + if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES { + return Err("a geometry that is not triangles"); + } + out.push(description); + } + Ok(out) +} + +/// The vertex format of a triangle geometry. +fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT { + // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles. + unsafe { description.Anonymous.Triangles.VertexFormat } +} + +/// The structure over the triangles the descriptions name, as title memory +/// holds them now. +fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> { + let mut geometry = Vec::new(); + for description in descriptions { + // SAFETY: as in `format`. + geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?); + } + let parts: Vec<(&title_geometry::Geometry, u32)> = geometry + .iter() + .zip(descriptions) + .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned())) + .collect(); + console_structure::build(&parts) +} + +/// A build to read again. +struct Later { + geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, + /// The present the GPU must be past: the one that follows the call. + due: u64, + /// Of the structure written at the call, 0 when none was. + digest: u64, +} + +static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +fn later() -> std::sync::MutexGuard<'static, std::collections::BTreeMap<u64, Later>> { + LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// The bytes of title memory the console's own structure is sure to cover +/// for a structure this writer made: its header, and half a leaf for each +/// triangle, since a console leaf holds two at most. The console's builder +/// writes more than that, never less. +fn least_extent(bytes: &[u8]) -> u64 { + let leaves = bytes.get(12..16).map_or(0, |word| u32::from_le_bytes(core::array::from_fn(|byte| word[byte]))); + 64 + 32 * u64::from(leaves) +} + +/// A digest of a structure's bytes, never 0. +fn digest(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)) + | 1 +} + +/// The builds whose second reading is due: each is read again and, when the +/// GPU has changed its positions since the call, written anew. +fn look_again(heap: &ConsoleHeap, device: &ID3D12Device) { + static READ: AtomicU64 = AtomicU64::new(0); + static CHANGED: AtomicU64 = AtomicU64::new(0); + static UNREADABLE: AtomicU64 = AtomicU64::new(0); + let now = console_heap::finished(); + let due: Vec<(u64, Later)> = { + let mut later = later(); + let ready: Vec<u64> = later.iter().filter(|(_, look)| look.due <= now).map(|(at, _)| *at).collect(); + ready.into_iter().filter_map(|at| later.remove(&at).map(|look| (at, look))).collect() + }; + for (destination, look) in due { + // Written at the call and given up since: the title has built over it. + if look.digest != 0 && heap.placed(destination).is_none() { + continue; + } ~~~~ --- Fixed in `ba24f252`: a claim now makes stale every reading pending for a build at an address inside the claimed bytes, whether that build placed a structure or not (`Book::claim`, `Book::stale`). Test: `a_reading_pending_at_an_address_a_later_structure_covers_is_dropped`.
3kynox commented 2026-12-01 22:26:23 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by 3kynox on 2026-12-01T22:26:23Z.

Code review location: runtime/d3d12/src/commands/build_raytracing/console.rs; line 305

@@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: *
     }
 }
 
-/// The bottom-level builds of a build call. A structure the title builds
-/// from geometry while it runs is not written yet, so whatever was placed
-/// under its address is no longer what the title has there.
+/// Which of the structures a title builds while it runs are written.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Built {
+    /// None: their instances stay out of the scenes.
+    None,
+    /// Those whose geometry is final at the call.
+    Settled,
+    /// Those, and the others read at the call and once more when the GPU is
+    /// past the frame: for a host whose GPU works in the title's own memory.
+    Late,
+    /// Every one the CPU can read at the call, right or not: for comparing pictures.
+    All,
+}
+
+/// What `TUXBOX_CONSOLE_BUILT` asks for.
+fn built_from(asked: Option<&str>) -> Built {
+    match asked.map(str::trim) {
+        Some("0") => Built::None,
+        Some("late") => Built::Late,
+        Some("all") => Built::All,
+        _ => Built::Settled,
+    }
+}
+
+fn built_mode() -> Built {
+    static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| {
+        let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref());
+        if mode != Built::Settled {
+            log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}"));
+        }
+        mode
+    });
+    *MODE
+}
+
+/// Why a build in float positions is left out.
+const UNSETTLED: &str = "float positions, which the GPU may write after the call";
+
+/// Whether title memory holds a geometry's final positions when its build is
+/// called. Packed positions are streamed in with the mesh and stay as they
+/// are. Float positions are what a skinned or simulated mesh is written in,
+/// by the GPU, after the title has recorded the build: read at the call they
+/// are an earlier frame's, or not positions at all.
+fn settled(format: DXGI_FORMAT) -> bool {
+    format == DXGI_FORMAT_R32G32_FLOAT
+}
+
+/// The geometry descriptions of one bottom-level build, copied: what is
+/// needed to read its triangles after the call as well.
 ///
 /// # Safety
-/// `owner` is the list's controlling guest device.
+/// `build` is the title's description, live for the call.
+unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> {
+    let inputs = &build.Inputs;
+    // SAFETY: the title supplies the descriptions for the duration of the call.
+    if !unsafe { ray_build::valid(inputs) } {
+        return Err("inputs that are not valid");
+    }
+    let mut out = Vec::new();
+    for index in 0..inputs.NumDescs as usize {
+        // SAFETY: `ray_build::valid` checked the layout and every pointer.
+        let description =
+            unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?;
+        if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES {
+            return Err("a geometry that is not triangles");
+        }
+        out.push(description);
+    }
+    Ok(out)
+}
+
+/// The vertex format of a triangle geometry.
+fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT {
+    // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles.
+    unsafe { description.Anonymous.Triangles.VertexFormat }
+}
+
+/// The structure over the triangles the descriptions name, as title memory
+/// holds them now.
+fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> {
+    let mut geometry = Vec::new();
+    for description in descriptions {
+        // SAFETY: as in `format`.
+        geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?);
+    }
+    let parts: Vec<(&title_geometry::Geometry, u32)> = geometry
+        .iter()
+        .zip(descriptions)
+        .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned()))
+        .collect();
+    console_structure::build(&parts)
+}
+
+/// A build to read again.
+struct Later {
+    geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>,
+    /// The present the GPU must be past: the one that follows the call.
+    due: u64,
+    /// Of the structure written at the call, 0 when none was.
+    digest: u64,
+}
+
+static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> =
+    std::sync::Mutex::new(std::collections::BTreeMap::new());
+
+fn later() -> std::sync::MutexGuard<'static, std::collections::BTreeMap<u64, Later>> {
+    LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+/// The bytes of title memory the console's own structure is sure to cover
+/// for a structure this writer made: its header, and half a leaf for each
+/// triangle, since a console leaf holds two at most. The console's builder
+/// writes more than that, never less.
+fn least_extent(bytes: &[u8]) -> u64 {
+    let leaves = bytes.get(12..16).map_or(0, |word| u32::from_le_bytes(core::array::from_fn(|byte| word[byte])));
+    64 + 32 * u64::from(leaves)
+}
+
+/// A digest of a structure's bytes, never 0.
+fn digest(bytes: &[u8]) -> u64 {
+    bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3))
+        | 1
+}
+
+/// The builds whose second reading is due: each is read again and, when the
+/// GPU has changed its positions since the call, written anew.
+fn look_again(heap: &ConsoleHeap, device: &ID3D12Device) {
+    static READ: AtomicU64 = AtomicU64::new(0);
+    static CHANGED: AtomicU64 = AtomicU64::new(0);
+    static UNREADABLE: AtomicU64 = AtomicU64::new(0);
+    let now = console_heap::finished();
+    let due: Vec<(u64, Later)> = {
+        let mut later = later();
+        let ready: Vec<u64> = later.iter().filter(|(_, look)| look.due <= now).map(|(at, _)| *at).collect();
+        ready.into_iter().filter_map(|at| later.remove(&at).map(|look| (at, look))).collect()
+    };
+    for (destination, look) in due {
+        // Written at the call and given up since: the title has built over it.
+        if look.digest != 0 && heap.placed(destination).is_none() {
+            continue;
+        }

Fixed in ba24f252: each address counts the builds made at it (Book::begun), a reading carries the number of the build it is for, and ConsoleHeap::structure_if_current checks that number and places the structure in one step under the buffer's lock. A build recorded meanwhile either comes first and makes the reading stale, or comes after and replaces what it placed. Test: a_reading_taken_before_the_title_builds_there_again_is_no_longer_current.

<!-- greyfinch-sync:brcly/TuxBox:review-comment:4761902802 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/623#discussion_r4761902802). Originally posted by [3kynox](https://github.com/3kynox) on 2026-12-01T22:26:23Z. **Code review location:** `runtime/d3d12/src/commands/build_raytracing/console.rs`; line 305 ~~~~diff @@ -142,19 +162,243 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: * } } -/// The bottom-level builds of a build call. A structure the title builds -/// from geometry while it runs is not written yet, so whatever was placed -/// under its address is no longer what the title has there. +/// Which of the structures a title builds while it runs are written. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Built { + /// None: their instances stay out of the scenes. + None, + /// Those whose geometry is final at the call. + Settled, + /// Those, and the others read at the call and once more when the GPU is + /// past the frame: for a host whose GPU works in the title's own memory. + Late, + /// Every one the CPU can read at the call, right or not: for comparing pictures. + All, +} + +/// What `TUXBOX_CONSOLE_BUILT` asks for. +fn built_from(asked: Option<&str>) -> Built { + match asked.map(str::trim) { + Some("0") => Built::None, + Some("late") => Built::Late, + Some("all") => Built::All, + _ => Built::Settled, + } +} + +fn built_mode() -> Built { + static MODE: std::sync::LazyLock<Built> = std::sync::LazyLock::new(|| { + let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref()); + if mode != Built::Settled { + log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}")); + } + mode + }); + *MODE +} + +/// Why a build in float positions is left out. +const UNSETTLED: &str = "float positions, which the GPU may write after the call"; + +/// Whether title memory holds a geometry's final positions when its build is +/// called. Packed positions are streamed in with the mesh and stay as they +/// are. Float positions are what a skinned or simulated mesh is written in, +/// by the GPU, after the title has recorded the build: read at the call they +/// are an earlier frame's, or not positions at all. +fn settled(format: DXGI_FORMAT) -> bool { + format == DXGI_FORMAT_R32G32_FLOAT +} + +/// The geometry descriptions of one bottom-level build, copied: what is +/// needed to read its triangles after the call as well. /// /// # Safety -/// `owner` is the list's controlling guest device. +/// `build` is the title's description, live for the call. +unsafe fn descriptions(build: &Build) -> Result<Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, &'static str> { + let inputs = &build.Inputs; + // SAFETY: the title supplies the descriptions for the duration of the call. + if !unsafe { ray_build::valid(inputs) } { + return Err("inputs that are not valid"); + } + let mut out = Vec::new(); + for index in 0..inputs.NumDescs as usize { + // SAFETY: `ray_build::valid` checked the layout and every pointer. + let description = + unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?; + if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES { + return Err("a geometry that is not triangles"); + } + out.push(description); + } + Ok(out) +} + +/// The vertex format of a triangle geometry. +fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT { + // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles. + unsafe { description.Anonymous.Triangles.VertexFormat } +} + +/// The structure over the triangles the descriptions name, as title memory +/// holds them now. +fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result<Vec<u8>, &'static str> { + let mut geometry = Vec::new(); + for description in descriptions { + // SAFETY: as in `format`. + geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?); + } + let parts: Vec<(&title_geometry::Geometry, u32)> = geometry + .iter() + .zip(descriptions) + .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned())) + .collect(); + console_structure::build(&parts) +} + +/// A build to read again. +struct Later { + geometry: Vec<D3D12_RAYTRACING_GEOMETRY_DESC>, + /// The present the GPU must be past: the one that follows the call. + due: u64, + /// Of the structure written at the call, 0 when none was. + digest: u64, +} + +static LATER: std::sync::Mutex<std::collections::BTreeMap<u64, Later>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +fn later() -> std::sync::MutexGuard<'static, std::collections::BTreeMap<u64, Later>> { + LATER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// The bytes of title memory the console's own structure is sure to cover +/// for a structure this writer made: its header, and half a leaf for each +/// triangle, since a console leaf holds two at most. The console's builder +/// writes more than that, never less. +fn least_extent(bytes: &[u8]) -> u64 { + let leaves = bytes.get(12..16).map_or(0, |word| u32::from_le_bytes(core::array::from_fn(|byte| word[byte]))); + 64 + 32 * u64::from(leaves) +} + +/// A digest of a structure's bytes, never 0. +fn digest(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)) + | 1 +} + +/// The builds whose second reading is due: each is read again and, when the +/// GPU has changed its positions since the call, written anew. +fn look_again(heap: &ConsoleHeap, device: &ID3D12Device) { + static READ: AtomicU64 = AtomicU64::new(0); + static CHANGED: AtomicU64 = AtomicU64::new(0); + static UNREADABLE: AtomicU64 = AtomicU64::new(0); + let now = console_heap::finished(); + let due: Vec<(u64, Later)> = { + let mut later = later(); + let ready: Vec<u64> = later.iter().filter(|(_, look)| look.due <= now).map(|(at, _)| *at).collect(); + ready.into_iter().filter_map(|at| later.remove(&at).map(|look| (at, look))).collect() + }; + for (destination, look) in due { + // Written at the call and given up since: the title has built over it. + if look.digest != 0 && heap.placed(destination).is_none() { + continue; + } ~~~~ --- Fixed in `ba24f252`: each address counts the builds made at it (`Book::begun`), a reading carries the number of the build it is for, and `ConsoleHeap::structure_if_current` checks that number and places the structure in one step under the buffer's lock. A build recorded meanwhile either comes first and makes the reading stale, or comes after and replaces what it placed. Test: `a_reading_taken_before_the_title_builds_there_again_is_no_longer_current`.
3kynox commented 2026-12-01 22:26:24 +00:00 (Migrated from github.com)

Imported from brcly/TuxBox. Originally posted by 3kynox on 2026-12-01T22:26:24Z.

Code review location: runtime/d3d12/src/device/console_heap.rs; line 639

@@ -592,13 +623,26 @@ impl ConsoleHeap {
     /// Places an expanded bottom-level structure and names it by the
     /// addresses the title knows it at. False when it could not be placed:
     /// those addresses then name nothing.
-    pub(crate) fn structure(&self, device: &ID3D12Device, addresses: &[u64], bytes: &[u8]) -> bool {
+    ///
+    /// `extent` is how many bytes of title memory the title's own structure
+    /// is sure to cover from each address: what was named inside them is
+    /// given up (`Book::claim`). 0 claims nothing.
+    pub(crate) fn structure(&self, device: &ID3D12Device, addresses: &[u64], bytes: &[u8], extent: u64) -> bool {
         let mut inner = self.lock();
         let placed = bytes
             .get(..64)
             .and_then(|header| <[u8; 64]>::try_from(header).ok())
             .and_then(|header| Some(Placed { offset: inner.write(device, bytes)?, header }));
-        inner.book.structure(addresses, placed, bytes.len() as u64, presents())
+        let now = presents();
+        if placed.is_some() {
+            inner.book.claim(addresses, extent, now);
+        }

Fixed in ba24f252: the claim is applied whether or not the new structure finds room (Book::built_over). Test: a_structure_that_finds_no_place_still_gives_up_what_the_title_built_over.

<!-- greyfinch-sync:brcly/TuxBox:review-comment:4761903104 --> Imported from [brcly/TuxBox](https://github.com/brcly/TuxBox/pull/623#discussion_r4761903104). Originally posted by [3kynox](https://github.com/3kynox) on 2026-12-01T22:26:24Z. **Code review location:** `runtime/d3d12/src/device/console_heap.rs`; line 639 ~~~~diff @@ -592,13 +623,26 @@ impl ConsoleHeap { /// Places an expanded bottom-level structure and names it by the /// addresses the title knows it at. False when it could not be placed: /// those addresses then name nothing. - pub(crate) fn structure(&self, device: &ID3D12Device, addresses: &[u64], bytes: &[u8]) -> bool { + /// + /// `extent` is how many bytes of title memory the title's own structure + /// is sure to cover from each address: what was named inside them is + /// given up (`Book::claim`). 0 claims nothing. + pub(crate) fn structure(&self, device: &ID3D12Device, addresses: &[u64], bytes: &[u8], extent: u64) -> bool { let mut inner = self.lock(); let placed = bytes .get(..64) .and_then(|header| <[u8; 64]>::try_from(header).ok()) .and_then(|header| Some(Placed { offset: inner.write(device, bytes)?, header })); - inner.book.structure(addresses, placed, bytes.len() as u64, presents()) + let now = presents(); + if placed.is_some() { + inner.book.claim(addresses, extent, now); + } ~~~~ --- Fixed in `ba24f252`: the claim is applied whether or not the new structure finds room (`Book::built_over`). Test: `a_structure_that_finds_no_place_still_gives_up_what_the_title_built_over`.
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!623
No description provided.