D3D12.X: XboxBvhBuilder builds give their destinations video memory #3521

Open
Lakanya wants to merge 1 commit from upstream-pr/3521 into main
Lakanya commented 2026-11-30 11:45:59 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Lakanya on 2026-11-30T11:45:59Z.


With XCL_SPARSE_LAZY=1 a tile the title commits gets no video memory until the CPU's first bytes go up to it, or a placed buffer or a copy names it. XboxBvhBuilder.dll writes its acceleration structures with compute programs through the sparse windows, which none of those see. In a retail title, the destination tiles of its builds and of every compaction copy had none, so what the builder wrote went nowhere: the structures read as zeros and rays hit nothing. This gives those ranges video memory before the builder records its passes, through the existing sparse::will_write (the same path a list's memory writes take). Part of #505.

What is in it (one commit, 2e2d9320; updated after review)

  • crates/xcl/src/hle/d3d12x/bvh_builder.rs (new): with XCL_SPARSE_LAZY=1, the builder's BuildRaytracingAccelerationStructureBatched2X, BuildRaytracingAccelerationStructure and CopyRaytracingAccelerationStructure exports are hooked when the title resolves them. Each build asks the builder's own GetRaytracingAccelerationStructurePrebuildInfo for the most it writes (bvh::prebuild_size underestimates some top levels: 0x198400 against the builder's 0x227000 for one with flags 0x4) and hands the destination range to sparse::will_write. The query is made before the size map's lock is taken.
    • A clone or compacted copy writes as much as its source's build, or as the copy that made the source: each copy records that size for its destination, so a copy of a copy is covered. A copy of unknown size or of another mode, and a build that gives no size, forget the destination's old size instead of leaving it stale.
    • Each build's postbuild infos (both build exports) get their DestBuffer backed for their type's size (8 bytes, 16 for serialization), which can be on a tile of its own.
    • Without the switch nothing is hooked.
  • crates/xcl/src/resolver.rs: exports resolved from a mapped module go through bvh_builder::intercept (it returns the original address for every other module and export).
  • crates/xcl/src/hle/d3d12x/sparse.rs: lazy_asked is pub(super); one GPU test.
  • Tests: a_build_and_its_copies_write_the_builders_own_result_size (now with chained copies), a_reused_destination_never_keeps_a_stale_size, postbuild_infos_write_their_own_buffers, the_build_and_copy_exports_are_hooked; GPU: a_postbuild_result_on_a_tile_of_its_own_gets_memory (a compacted-size result on a separate lazy tile gets that tile's memory, the tiles of the destination and between are left alone).

This is one of two fixes the builder needs under XCL_SPARSE_LAZY=1; the build scratch, which no commit lists at all, is the stacked PR after this one (#3522). #1319 (merged) fixed the third cause found on the way.

Tested

  • NVIDIA GeForce RTX 5070 Laptop GPU 8 GB (driver 621.40), AMD Ryzen AI 7 350, Windows 11 Pro build 26300.10075, Rust 1.100.0. Tests in debug, the regression runs in release. XCL_DIRECT_DXIL, XCL_HEAP_WINDOWS, XCL_HEAP_FLAT and XCL_SPARSE_LAZY unset for the tests.
  • cargo build --workspace, then cargo test --workspace --no-fail-fast -- --test-threads=4 on 2e2d9320: the 41 integration harnesses and binaries 148 passed, 0 failed, 20 ignored. The library harness ends early (0x80004005) on this PR and on main 9dfbe3ea alike: a test's title reaches end_title ("sparse upload preparation still failed after bounded retries"). It does with --test-threads=1 too (checked on #3522's head: during bind::tests::gpu_two_pass_indirect_commands_keep_their_own_records, after the tests before it; that test passes in hle::d3d12x::bind alone).
  • So the library groups this PR touches, each in its own process, cargo test -p xcl --lib <filters> -- --test-threads=4:
    • hle::d3d12x::sparse hle::d3d12x::bvh_builder: 145 passed, 0 failed, 1 ignored, none skipped.
    • hle::d3d12x::bind: 116 passed, 0 failed, 0 ignored. In 8 runs of it on this commit one had 1 failure (not identified; 3 of 3 on 0744aa01 passed); it reaches none of this code.
    • hle::d3d12x::list_x: 113 passed, 0 failed, 0 ignored (the same on main 9dfbe3ea).
    • The rest of the library (--skip hle::d3d12x::bind --skip hle::d3d12x::list_x) ends at the same end_title on this PR and on main, so it has no count; gpu_direct_image_get_resinfo_d16 fails in it on both.
  • Each new test fails without its fix: with copy_writes' old logic put back, a_build_and_its_copies_write_the_builders_own_result_size and a_reused_destination_never_keeps_a_stale_size fail. The reviewer's chained-copy assertion is in the first.
  • SKIPPED on this adapter before the library harness ended: 22 "no wave64", heap_window_out_of_memory_falls_back_to_the_switch_form (no heap windows). None is a test of this PR.

Regression run
scripts/smoke.ps1 -Game <retail title> -Seconds 600, the release build of each commit, the same environment for both: XCL_DEVICE_TYPE=lockhart XCL_DIRECT_DXIL=1 XCL_DXC_THREADS=6 XCL_SPARSE_LAZY=1 XCL_SMALL_TEXTURES=1 XCL_TEXTURE_LEVEL_PAGES=1 XCL_COHERENT_HEAPS=sparse:1024 XCL_TWO_PASS_BATCH=1 XCL_TWO_PASS_MB=1536 XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_HEAP_FLAT=1 XCL_DEPTH_UAV_TWIN=1 XCL_FRAME_DUMP=300, scripted A presses (XCL_PRESS_A_AT). The main block is the one from the first revision of this PR (2026-11-30); this PR's was run again on its new head (2026-12-01).

main:

xcl-smoke v1
commit: 9dfbe3ea6653a9c76ef3ea0d66187a4b5407483b
gpu: NVIDIA GeForce RTX 5070 Laptop GPU
title: 2c508222
seconds: 600
exit: 0x0
frames shown: 1571 (PresentX 1571)
presents per 2 s (last 3): 0 0 0
device removals: 0
crashes: 0
peak commit: 31033 MB

this PR's head:

xcl-smoke v1
commit: 2e2d9320ae0d72e2e635eebfacb6a8913c0107a9
gpu: NVIDIA GeForce RTX 5070 Laptop GPU
title: 2c508222
seconds: 600
exit: 0x0
frames shown: 1866 (PresentX 1866)
presents per 2 s (last 3): 0 0 0
device removals: 0
crashes: 0
peak commit: 28683 MB

Not tested

  • That the structures are correct on this commit: the per-build checks are lab instrumentation and were not run on it. With this PR alone they are not: the build scratch still has no video memory (#3522).
  • That the lighting is better: the frames of the two runs are not compared.
  • The regression runs do not check the change itself, and may not reach it: XCL logs nothing per build. The postbuild path is tested through sparse::State::give_memory with the ranges this PR computes, not through the hook with a real builder.
  • A full library count (see Tested).
  • RehydrateRaytracingAccelerationStructureBatched2X (structures loaded compressed from the title's files) is not hooked: its destinations may still have no video memory.
  • Without XCL_SPARSE_LAZY=1 nothing changes and that path was not run.
  • AMD, other NVIDIA cards, wave64 GPUs.

Follow-ups (from the reviews, left out of this PR to keep it small)

  • The size map is never pruned: entries stay until their address is built or copied over again. It needs a release signal for a structure's memory.
  • will_write goes through give_memory / materialize(force=false), which leaves tiles without memory and logs nothing when video memory is short, so under VRAM pressure a build can still write to a destination with nothing behind it. A compacted copy is also given the source's maximum size, not its compacted size (memory only).

AI use

  • Claude Code (Claude Opus 5.5): found the cause with lab instrumentation, wrote the change and its tests, addressed the review (chained copies, stale sizes, postbuild outputs, the query outside the lock), ran the tests and the regression runs, and wrote this description.

🤖 Generated with Claude Code

<!-- greyfinch-sync:ivall/xcl:issue:5564617463 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521). Originally posted by [Lakanya](https://github.com/Lakanya) on 2026-11-30T11:45:59Z. --- With `XCL_SPARSE_LAZY=1` a tile the title commits gets no video memory until the CPU's first bytes go up to it, or a placed buffer or a copy names it. XboxBvhBuilder.dll writes its acceleration structures with compute programs through the sparse windows, which none of those see. In a retail title, the destination tiles of its builds and of every compaction copy had none, so what the builder wrote went nowhere: the structures read as zeros and rays hit nothing. This gives those ranges video memory before the builder records its passes, through the existing `sparse::will_write` (the same path a list's memory writes take). Part of #505. **What is in it** (one commit, `2e2d9320`; updated after review) - `crates/xcl/src/hle/d3d12x/bvh_builder.rs` (new): with `XCL_SPARSE_LAZY=1`, the builder's `BuildRaytracingAccelerationStructureBatched2X`, `BuildRaytracingAccelerationStructure` and `CopyRaytracingAccelerationStructure` exports are hooked when the title resolves them. Each build asks the builder's own `GetRaytracingAccelerationStructurePrebuildInfo` for the most it writes (`bvh::prebuild_size` underestimates some top levels: 0x198400 against the builder's 0x227000 for one with flags 0x4) and hands the destination range to `sparse::will_write`. The query is made before the size map's lock is taken. - A clone or compacted copy writes as much as its source's build, or as the copy that made the source: each copy records that size for its destination, so a copy of a copy is covered. A copy of unknown size or of another mode, and a build that gives no size, forget the destination's old size instead of leaving it stale. - Each build's postbuild infos (both build exports) get their `DestBuffer` backed for their type's size (8 bytes, 16 for serialization), which can be on a tile of its own. - Without the switch nothing is hooked. - `crates/xcl/src/resolver.rs`: exports resolved from a mapped module go through `bvh_builder::intercept` (it returns the original address for every other module and export). - `crates/xcl/src/hle/d3d12x/sparse.rs`: `lazy_asked` is `pub(super)`; one GPU test. - Tests: `a_build_and_its_copies_write_the_builders_own_result_size` (now with chained copies), `a_reused_destination_never_keeps_a_stale_size`, `postbuild_infos_write_their_own_buffers`, `the_build_and_copy_exports_are_hooked`; GPU: `a_postbuild_result_on_a_tile_of_its_own_gets_memory` (a compacted-size result on a separate lazy tile gets that tile's memory, the tiles of the destination and between are left alone). This is one of two fixes the builder needs under `XCL_SPARSE_LAZY=1`; the build scratch, which no commit lists at all, is the stacked PR after this one (#3522). #1319 (merged) fixed the third cause found on the way. **Tested** - NVIDIA GeForce RTX 5070 Laptop GPU 8 GB (driver 621.40), AMD Ryzen AI 7 350, Windows 11 Pro build 26300.10075, Rust 1.100.0. Tests in debug, the regression runs in release. `XCL_DIRECT_DXIL`, `XCL_HEAP_WINDOWS`, `XCL_HEAP_FLAT` and `XCL_SPARSE_LAZY` unset for the tests. - `cargo build --workspace`, then `cargo test --workspace --no-fail-fast -- --test-threads=4` on `2e2d9320`: the 41 integration harnesses and binaries 148 passed, 0 failed, 20 ignored. The library harness ends early (`0x80004005`) on this PR and on `main` `9dfbe3ea` alike: a test's title reaches `end_title` ("sparse upload preparation still failed after bounded retries"). It does with `--test-threads=1` too (checked on #3522's head: during `bind::tests::gpu_two_pass_indirect_commands_keep_their_own_records`, after the tests before it; that test passes in `hle::d3d12x::bind` alone). - So the library groups this PR touches, each in its own process, `cargo test -p xcl --lib <filters> -- --test-threads=4`: - `hle::d3d12x::sparse hle::d3d12x::bvh_builder`: 145 passed, 0 failed, 1 ignored, none skipped. - `hle::d3d12x::bind`: 116 passed, 0 failed, 0 ignored. In 8 runs of it on this commit one had 1 failure (not identified; 3 of 3 on `0744aa01` passed); it reaches none of this code. - `hle::d3d12x::list_x`: 113 passed, 0 failed, 0 ignored (the same on `main` `9dfbe3ea`). - The rest of the library (`--skip hle::d3d12x::bind --skip hle::d3d12x::list_x`) ends at the same `end_title` on this PR and on `main`, so it has no count; `gpu_direct_image_get_resinfo_d16` fails in it on both. - Each new test fails without its fix: with `copy_writes`' old logic put back, `a_build_and_its_copies_write_the_builders_own_result_size` and `a_reused_destination_never_keeps_a_stale_size` fail. The reviewer's chained-copy assertion is in the first. - `SKIPPED` on this adapter before the library harness ended: 22 "no wave64", `heap_window_out_of_memory_falls_back_to_the_switch_form` (no heap windows). None is a test of this PR. **Regression run** `scripts/smoke.ps1 -Game <retail title> -Seconds 600`, the release build of each commit, the same environment for both: `XCL_DEVICE_TYPE=lockhart XCL_DIRECT_DXIL=1 XCL_DXC_THREADS=6 XCL_SPARSE_LAZY=1 XCL_SMALL_TEXTURES=1 XCL_TEXTURE_LEVEL_PAGES=1 XCL_COHERENT_HEAPS=sparse:1024 XCL_TWO_PASS_BATCH=1 XCL_TWO_PASS_MB=1536 XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_HEAP_FLAT=1 XCL_DEPTH_UAV_TWIN=1 XCL_FRAME_DUMP=300`, scripted A presses (`XCL_PRESS_A_AT`). The `main` block is the one from the first revision of this PR (2026-11-30); this PR's was run again on its new head (2026-12-01). main: ``` xcl-smoke v1 commit: 9dfbe3ea6653a9c76ef3ea0d66187a4b5407483b gpu: NVIDIA GeForce RTX 5070 Laptop GPU title: 2c508222 seconds: 600 exit: 0x0 frames shown: 1571 (PresentX 1571) presents per 2 s (last 3): 0 0 0 device removals: 0 crashes: 0 peak commit: 31033 MB ``` this PR's head: ``` xcl-smoke v1 commit: 2e2d9320ae0d72e2e635eebfacb6a8913c0107a9 gpu: NVIDIA GeForce RTX 5070 Laptop GPU title: 2c508222 seconds: 600 exit: 0x0 frames shown: 1866 (PresentX 1866) presents per 2 s (last 3): 0 0 0 device removals: 0 crashes: 0 peak commit: 28683 MB ``` **Not tested** - That the structures are correct on this commit: the per-build checks are lab instrumentation and were not run on it. With this PR alone they are not: the build scratch still has no video memory (#3522). - That the lighting is better: the frames of the two runs are not compared. - The regression runs do not check the change itself, and may not reach it: XCL logs nothing per build. The postbuild path is tested through `sparse::State::give_memory` with the ranges this PR computes, not through the hook with a real builder. - A full library count (see **Tested**). - `RehydrateRaytracingAccelerationStructureBatched2X` (structures loaded compressed from the title's files) is not hooked: its destinations may still have no video memory. - Without `XCL_SPARSE_LAZY=1` nothing changes and that path was not run. - AMD, other NVIDIA cards, wave64 GPUs. **Follow-ups** (from the reviews, left out of this PR to keep it small) - The size map is never pruned: entries stay until their address is built or copied over again. It needs a release signal for a structure's memory. - `will_write` goes through `give_memory` / `materialize(force=false)`, which leaves tiles without memory and logs nothing when video memory is short, so under VRAM pressure a build can still write to a destination with nothing behind it. A compacted copy is also given the source's maximum size, not its compacted size (memory only). **AI use** - Claude Code (Claude Opus 5.5): found the cause with lab instrumentation, wrote the change and its tests, addressed the review (chained copies, stale sizes, postbuild outputs, the query outside the lock), ran the tests and the regression runs, and wrote this description. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
thehollowedone commented 2026-11-30 23:26:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by thehollowedone on 2026-11-30T23:26:00Z.


merge-check
base: d0832e614f
head: 0744aa01bf
merge: clean (local merge a3877d341313a238250b19464f54a30db7da84c6)
build: cargo build --workspace --target-dir ..\target -> ok
tests: A focused, test-only chained-copy assertion on the unchanged PR logic failed: cargo test -p xcl --lib a_build_and_its_copies_write_the_builders_own_result_size --target-dir ..\target -- --nocapture --test-threads=1 -> 0 passed, 1 failed, 0 ignored, 0 skipped. With the local candidate below, the same command -> 1 passed, 0 failed, 0 ignored, 0 skipped. The full workspace suite and paired smoke were not run after this blocking failure.
review: A build A, clone A to B, then clone B to C has no tracked size for B. The second copy therefore does not prepare C's destination tiles. Reusing B after an older, smaller build can instead use B's stale size. The candidate records each known copy destination and invalidates a destination when its new size is unknown. Separately, both build wrappers forward postbuild descriptors without preparing their DestBuffer. For example, a compacted-size result on a separate lazy tile can remain unbacked; Microsoft's postbuild descriptor contract identifies the destination and the compacted-size result is eight bytes. Add a separate-tile regression for this path. These are source and synthetic findings, not a title-run observation.
performance: The candidate adds one size-map update per intercepted copy; no frame-time or memory measurement was made. The current map retains entries indefinitely, and give_build holds its mutex while calling the builder's prebuild query. Querying before taking that lock would avoid serializing unrelated builds; lifecycle cleanup still needs an owner or release signal.
verdict: not yet: chained copies can leave GPU outputs without backing; postbuild output preparation also needs coverage and a fix.
hardware / tool and model: NVIDIA RTX 3080 Ti (621.40), Ryzen 7 9800X3D, Windows 11 build 26300, rustc 1.99.1 MSVC / OpenAI Codex (GPT-6 Sol) ran the local build and regression; OpenAI Codex (GPT-6.2 Astra) independently traced the hook paths.

Tested candidate for chained copies and stale destinations
diff --git a/crates/xcl/src/hle/d3d12x/bvh_builder.rs b/crates/xcl/src/hle/d3d12x/bvh_builder.rs
index 02aef8f9..f3f6c13c 100644
--- a/crates/xcl/src/hle/d3d12x/bvh_builder.rs
+++ b/crates/xcl/src/hle/d3d12x/bvh_builder.rs
@@ -104,11 +104,18 @@ unsafe fn build_writes(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_
 
 /// What a copy of `source` to `dest` writes: as much as `source`'s build could write (a clone
 /// or a compacted copy is no larger). Other modes, and sources whose build was not seen: None.
-fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &HashMap<u64, u64>) -> Option<(u64, u64)> {
-    if dest == 0 || (mode != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE && mode != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT) {
+fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> {
+    if dest == 0 {
         return None;
     }
-    sizes.get(&source).map(|&n| (dest, n))
+    let known = (mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE || mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT)
+        .then(|| sizes.get(&source).copied())
+        .flatten();
+    sizes.remove(&dest);
+    known.map(|n| {
+        sizes.insert(dest, n);
+        (dest, n)
+    })
 }
 
 /// The GPU writes `[va, va + len)`: its tiles get video memory before the list runs.
@@ -186,11 +193,14 @@ mod tests {
             assert_eq!(build_writes(fake_prebuild, std::ptr::null_mut(), &b, &mut sizes), None, "no destination");
         }
         assert_eq!(sizes.len(), 1);
-        assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &sizes), Some((0x10_5000_0000, 0x3000)));
-        assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &sizes), Some((0x10_5000_0000, 0x3000)));
-        assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE, &sizes), None, "a serialized copy has another size");
-        assert_eq!(copy_writes(0x10_5000_0000, 0x10_6000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &sizes), None, "a source whose build was not seen");
-        assert_eq!(copy_writes(0, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &sizes), None);
+        assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), Some((0x10_5000_0000, 0x3000)));
+        assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((0x10_5000_0000, 0x3000)));
+        assert_eq!(copy_writes(0x10_6000_0000, 0x10_5000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((0x10_6000_0000, 0x3000)), "a second copy must inherit its source's tracked size");
+        assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE, &mut sizes), None, "a serialized copy has another size");
+        assert!(!sizes.contains_key(&0x10_5000_0000), "an unsupported write invalidates the old destination size");
+        assert_eq!(copy_writes(0x10_6000_0000, 0x10_7000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), None, "a source whose build was not seen");
+        assert!(!sizes.contains_key(&0x10_6000_0000), "an unknown copy invalidates the old destination size");
+        assert_eq!(copy_writes(0, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), None);
     }
 
     /// Only the build and copy exports are hooked; the batched element is laid out as the
<!-- greyfinch-sync:ivall/xcl:comment:7295110840 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#issuecomment-7295110840). Originally posted by [thehollowedone](https://github.com/thehollowedone) on 2026-11-30T23:26:00Z. --- merge-check base: d0832e614fa7d6ae027bb4feb27ccb9121f54a8f head: 0744aa01bf720c214e9a52ee94a0315fad6aa647 merge: clean (local merge a3877d341313a238250b19464f54a30db7da84c6) build: `cargo build --workspace --target-dir ..\target` -> ok tests: A focused, test-only chained-copy assertion on the unchanged PR logic failed: `cargo test -p xcl --lib a_build_and_its_copies_write_the_builders_own_result_size --target-dir ..\target -- --nocapture --test-threads=1` -> 0 passed, 1 failed, 0 ignored, 0 skipped. With the local candidate below, the same command -> 1 passed, 0 failed, 0 ignored, 0 skipped. The full workspace suite and paired smoke were not run after this blocking failure. review: A build A, clone A to B, then clone B to C has no tracked size for B. The second copy therefore does not prepare C's destination tiles. Reusing B after an older, smaller build can instead use B's stale size. The candidate records each known copy destination and invalidates a destination when its new size is unknown. Separately, both build wrappers forward postbuild descriptors without preparing their `DestBuffer`. For example, a compacted-size result on a separate lazy tile can remain unbacked; Microsoft's [postbuild descriptor contract](https://learn.microsoft.com/en-us/windows/desktop/api/d3d12/ns-d3d12-d3d12_raytracing_acceleration_structure_postbuild_info_desc) identifies the destination and the [compacted-size result](https://learn.microsoft.com/en-us/windows/desktop/api/d3d12/ns-d3d12-d3d12_raytracing_acceleration_structure_postbuild_info_compacted_size_desc) is eight bytes. Add a separate-tile regression for this path. These are source and synthetic findings, not a title-run observation. performance: The candidate adds one size-map update per intercepted copy; no frame-time or memory measurement was made. The current map retains entries indefinitely, and `give_build` holds its mutex while calling the builder's prebuild query. Querying before taking that lock would avoid serializing unrelated builds; lifecycle cleanup still needs an owner or release signal. verdict: not yet: chained copies can leave GPU outputs without backing; postbuild output preparation also needs coverage and a fix. hardware / tool and model: NVIDIA RTX 3080 Ti (621.40), Ryzen 7 9800X3D, Windows 11 build 26300, rustc 1.99.1 MSVC / OpenAI Codex (GPT-6 Sol) ran the local build and regression; OpenAI Codex (GPT-6.2 Astra) independently traced the hook paths. <details> <summary>Tested candidate for chained copies and stale destinations</summary> ```diff diff --git a/crates/xcl/src/hle/d3d12x/bvh_builder.rs b/crates/xcl/src/hle/d3d12x/bvh_builder.rs index 02aef8f9..f3f6c13c 100644 --- a/crates/xcl/src/hle/d3d12x/bvh_builder.rs +++ b/crates/xcl/src/hle/d3d12x/bvh_builder.rs @@ -104,11 +104,18 @@ unsafe fn build_writes(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_ /// What a copy of `source` to `dest` writes: as much as `source`'s build could write (a clone /// or a compacted copy is no larger). Other modes, and sources whose build was not seen: None. -fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &HashMap<u64, u64>) -> Option<(u64, u64)> { - if dest == 0 || (mode != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE && mode != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT) { +fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> { + if dest == 0 { return None; } - sizes.get(&source).map(|&n| (dest, n)) + let known = (mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE || mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT) + .then(|| sizes.get(&source).copied()) + .flatten(); + sizes.remove(&dest); + known.map(|n| { + sizes.insert(dest, n); + (dest, n) + }) } /// The GPU writes `[va, va + len)`: its tiles get video memory before the list runs. @@ -186,11 +193,14 @@ mod tests { assert_eq!(build_writes(fake_prebuild, std::ptr::null_mut(), &b, &mut sizes), None, "no destination"); } assert_eq!(sizes.len(), 1); - assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &sizes), Some((0x10_5000_0000, 0x3000))); - assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &sizes), Some((0x10_5000_0000, 0x3000))); - assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE, &sizes), None, "a serialized copy has another size"); - assert_eq!(copy_writes(0x10_5000_0000, 0x10_6000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &sizes), None, "a source whose build was not seen"); - assert_eq!(copy_writes(0, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &sizes), None); + assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), Some((0x10_5000_0000, 0x3000))); + assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((0x10_5000_0000, 0x3000))); + assert_eq!(copy_writes(0x10_6000_0000, 0x10_5000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, &mut sizes), Some((0x10_6000_0000, 0x3000)), "a second copy must inherit its source's tracked size"); + assert_eq!(copy_writes(0x10_5000_0000, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE, &mut sizes), None, "a serialized copy has another size"); + assert!(!sizes.contains_key(&0x10_5000_0000), "an unsupported write invalidates the old destination size"); + assert_eq!(copy_writes(0x10_6000_0000, 0x10_7000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), None, "a source whose build was not seen"); + assert!(!sizes.contains_key(&0x10_6000_0000), "an unknown copy invalidates the old destination size"); + assert_eq!(copy_writes(0, 0x10_4000_0000, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT, &mut sizes), None); } /// Only the build and copy exports are hooked; the batched element is laid out as the ``` </details>
Foniass commented 2026-12-01 08:25:47 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T08:25:47Z.


merge-check
base: 7d86c5d2b7
head: 0744aa01bf
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2898 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: read the whole diff (new bvh_builder.rs, d3d12x/mod.rs, one line in sparse.rs, resolver.rs). Nothing changes by default: without XCL_SPARSE_LAZY=1 intercept returns the original address (one name compare per resolved export), so neither the suite nor a smoke run reaches the new hook. Findings: (1) a COMPACT copy is given the source's ResultDataMaxSizeInBytes (bvh_builder.rs ~111), so committed tiles past the smaller compacted allocation get video memory early (memory only). (2) The requests go through give_memory / materialize(force=false), which skips the remaining tiles and drops the request without a log once memory is short, so under VRAM pressure a build still writes nowhere. (3) SIZES (~41) is never pruned and its lock is held across the builder's prebuild call (~127), serialising recording threads. (4) The tests only cover pure functions; the BatchedDesc size check compares the struct with its own definition plus 32, so it can't catch a wrong layout, and the resolver hook is untested. By its own description this doesn't make the structures correct without #3522. Fine: it reuses the will_write path, so tiles are mapped on the sparse queue and the title queue waits on the fence before its lists run; it only backs tiles the title committed, so nothing new leaks.
performance: no smoke run (the default path doesn't reach this change); not measured.
verdict: safe to merge together with #3522 once that one's findings are fixed (on its own it doesn't make the structures correct, per its description); nothing changes without XCL_SPARSE_LAZY=1
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7305305339 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#issuecomment-7305305339). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T08:25:47Z. --- merge-check base: 7d86c5d2b7845695031eeea1327aa81b6c439323 head: 0744aa01bf720c214e9a52ee94a0315fad6aa647 merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2898 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none review: read the whole diff (new `bvh_builder.rs`, `d3d12x/mod.rs`, one line in `sparse.rs`, `resolver.rs`). Nothing changes by default: without `XCL_SPARSE_LAZY=1` `intercept` returns the original address (one name compare per resolved export), so neither the suite nor a smoke run reaches the new hook. Findings: (1) a COMPACT copy is given the source's `ResultDataMaxSizeInBytes` (`bvh_builder.rs` ~111), so committed tiles past the smaller compacted allocation get video memory early (memory only). (2) The requests go through `give_memory` / `materialize(force=false)`, which skips the remaining tiles and drops the request without a log once memory is short, so under VRAM pressure a build still writes nowhere. (3) `SIZES` (~41) is never pruned and its lock is held across the builder's prebuild call (~127), serialising recording threads. (4) The tests only cover pure functions; the `BatchedDesc` size check compares the struct with its own definition plus 32, so it can't catch a wrong layout, and the resolver hook is untested. By its own description this doesn't make the structures correct without #3522. Fine: it reuses the `will_write` path, so tiles are mapped on the sparse queue and the title queue waits on the fence before its lists run; it only backs tiles the title committed, so nothing new leaks. performance: no smoke run (the default path doesn't reach this change); not measured. verdict: safe to merge together with #3522 once that one's findings are fixed (on its own it doesn't make the structures correct, per its description); nothing changes without XCL_SPARSE_LAZY=1 hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5 AI-written and posted by Foniass without a human check of each point.
Foniass commented 2026-12-01 10:08:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T10:08:25Z.


Triage (#1607) – head 2e2d932

#3522 (same author) is stacked on this PR and adds scratch tiles on top of it; that is not a duplicate. No other open or merged PR hooks XboxBvhBuilder's build/copy exports.
Notes on the diff: bvh_builder.rs:give_build now makes the builder's prebuild query before taking SIZES. BatchedDesc assumes a 32-byte tail after the build desc; nothing beyond the size assert checks that layout against the DLL.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

<!-- greyfinch-sync:ivall/xcl:comment:7307730065 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#issuecomment-7307730065). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T10:08:25Z. --- **Triage (#1607)** – head 2e2d932 #3522 (same author) is stacked on this PR and adds scratch tiles on top of it; that is not a duplicate. No other open or merged PR hooks XboxBvhBuilder's build/copy exports. Notes on the diff: `bvh_builder.rs:give_build` now makes the builder's prebuild query before taking `SIZES`. `BatchedDesc` assumes a 32-byte tail after the build desc; nothing beyond the size assert checks that layout against the DLL. Recommendation: keep open. AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.
Lakanya commented 2026-12-01 10:40:57 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Lakanya on 2026-12-01T10:40:57Z.


Thanks both. Updated to 2e2d9320 (squashed into the one commit):

  • Chained copies / stale sizes (thehollowedone): a clone or compacted copy now records its size for its destination, so A → B → C writes the full size at C; a copy of unknown size or another mode, and a build with no size, forget the destination's old size. Your chained-copy assertion is in a_build_and_its_copies_write_the_builders_own_result_size, and a_reused_destination_never_keeps_a_stale_size covers B built smaller before. Both fail with the old copy_writes.
  • Postbuild outputs (thehollowedone): both build hooks now back each postbuild info's DestBuffer for its type's size (8, or 16 for serialization). postbuild_infos_write_their_own_buffers, and the GPU test a_postbuild_result_on_a_tile_of_its_own_gets_memory (compacted-size result on a separate lazy tile).
  • Prebuild query under the lock (both): the query now runs before the size map's lock is taken.
  • Tests (Foniass 4): the new tests cover copies, stale sizes and postbuild ranges, and one runs on the GPU through give_memory. The hook itself and the BatchedDesc layout are still only checked as before.

Left as follow-ups, listed in the description: pruning the size map (needs a release signal), will_write dropping tiles without a log when video memory is short, and compacted copies being given the source's maximum size (memory only).

Tests and a new xcl-smoke block for the head are in the description. The library harness ends at an end_title on main 9dfbe3ea too, so the library counts are per group.

AI use: Claude Code (Claude Opus 5.5) made the changes, ran the tests and the regression run, and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:comment:7308551190 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#issuecomment-7308551190). Originally posted by [Lakanya](https://github.com/Lakanya) on 2026-12-01T10:40:57Z. --- Thanks both. Updated to `2e2d9320` (squashed into the one commit): - **Chained copies / stale sizes** (thehollowedone): a clone or compacted copy now records its size for its destination, so A → B → C writes the full size at C; a copy of unknown size or another mode, and a build with no size, forget the destination's old size. Your chained-copy assertion is in `a_build_and_its_copies_write_the_builders_own_result_size`, and `a_reused_destination_never_keeps_a_stale_size` covers B built smaller before. Both fail with the old `copy_writes`. - **Postbuild outputs** (thehollowedone): both build hooks now back each postbuild info's `DestBuffer` for its type's size (8, or 16 for serialization). `postbuild_infos_write_their_own_buffers`, and the GPU test `a_postbuild_result_on_a_tile_of_its_own_gets_memory` (compacted-size result on a separate lazy tile). - **Prebuild query under the lock** (both): the query now runs before the size map's lock is taken. - **Tests** (Foniass 4): the new tests cover copies, stale sizes and postbuild ranges, and one runs on the GPU through `give_memory`. The hook itself and the `BatchedDesc` layout are still only checked as before. Left as follow-ups, listed in the description: pruning the size map (needs a release signal), `will_write` dropping tiles without a log when video memory is short, and compacted copies being given the source's maximum size (memory only). Tests and a new `xcl-smoke` block for the head are in the description. The library harness ends at an `end_title` on `main` `9dfbe3ea` too, so the library counts are per group. AI use: Claude Code (Claude Opus 5.5) made the changes, ran the tests and the regression run, and wrote this reply.
Foniass commented 2026-12-01 10:42:13 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T10:42:13Z.


Re-review (head 2e2d9320; diff from 0744aa01, which I merge-checked, read). Not a merge-check: PR description is red until the smoke pair is rerun on this head, and no full suite has run on it yet.

  • Fixed: thehollowedone's two points. Copies of copies keep their size, and a destination of unknown size drops its old one (bvh_builder.rs ~117-130). Postbuild DestBuffers now get memory, with the right sizes: 8 bytes for compacted, current and visualization, 16 for serialization (~136-150, ~173-196). The prebuild query now runs before the SIZES lock is taken (~164-166).
  • Still open from my merge-check:
    1. A compacted copy is still recorded at the source's maximum size (~117-130); that only costs memory.
    2. Requests are still dropped without a log when memory is short (give_memory, materialize(force=false)).
    3. SIZES is never pruned (~41).
    4. The hook wiring and the resolver hook are untested, and the BatchedDesc size assert is unchanged.
  • The BatchedDesc layout matters more now: d.postbuild is read and its targets get memory. readable() prevents a crash, but a wrong layout would back the wrong addresses (unverified against the DLL).
  • a_reused_destination_never_keeps_a_stale_size and the chained-copy asserts fail on the old code. The two postbuild tests only fail to compile without the change, and the sparse one exercises give_memory, not give_postbuild being called.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7308582073 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#issuecomment-7308582073). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T10:42:13Z. --- Re-review (head 2e2d9320; diff from 0744aa01, which I merge-checked, read). Not a merge-check: `PR description` is red until the smoke pair is rerun on this head, and no full suite has run on it yet. - **Fixed:** thehollowedone's two points. Copies of copies keep their size, and a destination of unknown size drops its old one (`bvh_builder.rs` ~117-130). Postbuild `DestBuffer`s now get memory, with the right sizes: 8 bytes for compacted, current and visualization, 16 for serialization (~136-150, ~173-196). The prebuild query now runs before the `SIZES` lock is taken (~164-166). - **Still open from my merge-check:** 1. A compacted copy is still recorded at the source's maximum size (~117-130); that only costs memory. 2. Requests are still dropped without a log when memory is short (`give_memory`, `materialize(force=false)`). 3. `SIZES` is never pruned (~41). 4. The hook wiring and the resolver hook are untested, and the `BatchedDesc` size assert is unchanged. - The `BatchedDesc` layout matters more now: `d.postbuild` is read and its targets get memory. `readable()` prevents a crash, but a wrong layout would back the wrong addresses (unverified against the DLL). - `a_reused_destination_never_keeps_a_stale_size` and the chained-copy asserts fail on the old code. The two postbuild tests only fail to compile without the change, and the sparse one exercises `give_memory`, not `give_postbuild` being called. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
fromthemoonx commented 2026-12-02 00:07:12 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by fromthemoonx on 2026-12-02T00:07:12Z.


merge-check
base: 1c8b551475
head: 2e2d9320ae
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2914 passed, 0 failed, 51 ignored (base: 2909 passed, 0 failed, 51 ignored); SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps), the same set as base; failing: none from this PR. The whole-suite run ended the lib binary with 0xc0000005 during eh::tests::thread_dumps_while_threads_run_and_exit (#3586, on main too). The counts are the lib binary run on its own (2766 passed, 0 failed, 31 ignored) plus the other binaries (148 passed, 0 failed, 20 ignored).
review: read the whole diff (4 files, +315 -2). No correctness problem found. Foniass's re-review notes stand.

  • With XCL_SPARSE_LAZY=1 only, the resolver hands the title hooks for XboxBvhBuilder's batched build, single build and copy exports. Without the switch, intercept returns the export as before.
  • Each build asks the builder's own prebuild query (before SIZES is locked) and gives the destination that much video memory through sparse::will_write. Clone and compact copies carry their source's size forward; other modes, and a build with no size, forget the destination's.
  • Postbuild DestBuffers get their type's bytes.
  • The 5 new tests (hle::d3d12x::bvh_builder::tests::*, sparse::tests::a_postbuild_result_on_a_tile_of_its_own_gets_memory): 3 of 3 runs passed. The sparse one ran here (tiled resources tier 2), not skipped.
  • Mutation: a clone / compact copy not recording its size for its destination fails a_build_and_its_copies_write_the_builders_own_result_size and a_reused_destination_never_keeps_a_stale_size. Good.
  • No retail title on this machine, so XboxBvhBuilder itself was not run here. The hooks are tested only through the_build_and_copy_exports_are_hooked and the size helpers.
    performance: none by default (XCL_SPARSE_LAZY unset). With it, one prebuild query per build plus the memory it gives.
    verdict: safe to merge
    hardware / tool and model: RTX 3060 12 GB (610.88), Ryzen 7 5700X, Windows 11 Pro 26300 / Claude Code (Claude Opus 5.5)
<!-- greyfinch-sync:ivall/xcl:comment:7330163836 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#issuecomment-7330163836). Originally posted by [fromthemoonx](https://github.com/fromthemoonx) on 2026-12-02T00:07:12Z. --- merge-check base: 1c8b551475e1e7bfe48f94448492a4c3544a2e0f head: 2e2d9320ae0d72e2e635eebfacb6a8913c0107a9 merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2914 passed, 0 failed, 51 ignored (base: 2909 passed, 0 failed, 51 ignored); SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps), the same set as base; failing: none from this PR. The whole-suite run ended the lib binary with 0xc0000005 during `eh::tests::thread_dumps_while_threads_run_and_exit` (#3586, on main too). The counts are the lib binary run on its own (2766 passed, 0 failed, 31 ignored) plus the other binaries (148 passed, 0 failed, 20 ignored). review: read the whole diff (4 files, +315 -2). No correctness problem found. Foniass's re-review notes stand. - With `XCL_SPARSE_LAZY=1` only, the resolver hands the title hooks for XboxBvhBuilder's batched build, single build and copy exports. Without the switch, `intercept` returns the export as before. - Each build asks the builder's own prebuild query (before `SIZES` is locked) and gives the destination that much video memory through `sparse::will_write`. Clone and compact copies carry their source's size forward; other modes, and a build with no size, forget the destination's. - Postbuild `DestBuffer`s get their type's bytes. - The 5 new tests (`hle::d3d12x::bvh_builder::tests::*`, `sparse::tests::a_postbuild_result_on_a_tile_of_its_own_gets_memory`): 3 of 3 runs passed. The sparse one ran here (tiled resources tier 2), not skipped. - Mutation: a clone / compact copy not recording its size for its destination fails `a_build_and_its_copies_write_the_builders_own_result_size` and `a_reused_destination_never_keeps_a_stale_size`. Good. - No retail title on this machine, so XboxBvhBuilder itself was not run here. The hooks are tested only through `the_build_and_copy_exports_are_hooked` and the size helpers. performance: none by default (`XCL_SPARSE_LAZY` unset). With it, one prebuild query per build plus the memory it gives. verdict: safe to merge hardware / tool and model: RTX 3060 12 GB (610.88), Ryzen 7 5700X, Windows 11 Pro 26300 / Claude Code (Claude Opus 5.5)
bmjask commented 2026-12-02 10:46:57 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T10:46:57Z.

Review: COMMENTED


Review of 2e2d9320: 4 finding(s). 4 are inline.


These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

<!-- greyfinch-sync:ivall/xcl:review:6149279141 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#pullrequestreview-6149279141). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T10:46:57Z. **Review:** COMMENTED --- Review of `2e2d9320`: 4 finding(s). 4 are inline. --- _These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it._
bmjask commented 2026-12-02 10:46:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T10:46:58Z.

Code review location: crates/xcl/src/hle/d3d12x/bvh_builder.rs; line 121

@@ -0,0 +1,291 @@
+//! XboxBvhBuilder.dll's exports that build and copy acceleration structures, when the title
+//! resolves them with `XCL_SPARSE_LAZY=1`: the ranges each call writes on the GPU are given
+//! video memory (`sparse::will_write`) before the builder records its passes.
+//!
+//! With the switch, a tile the title commits has no video memory until the CPU's first bytes go
+//! up to it or a placed buffer or a copy names it. The builder writes its structures with
+//! compute programs through the sparse windows, which none of those see: in a retail title all
+//! of a build's destination tiles and every compaction copy's had none, so what the builder
+//! wrote went nowhere and the structures read as zeros (rays found nothing).
+
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Mutex;
+
+use windows::Win32::Graphics::Direct3D12::*;
+
+use crate::modules::MappedModule;
+use crate::pe::{ExportTarget, ImportName};
+
+const BATCHED: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z";
+const SINGLE: &str = "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z";
+const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z";
+const PREBUILD: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z";
+
+/// the builder's own entry points (0: not resolved by the title yet)
+static F_BATCHED: AtomicUsize = AtomicUsize::new(0);
+static F_SINGLE: AtomicUsize = AtomicUsize::new(0);
+static F_COPY: AtomicUsize = AtomicUsize::new(0);
+/// its `GetRaytracingAccelerationStructurePrebuildInfo`, found in the module when a hook is made
+static F_PREBUILD: AtomicUsize = AtomicUsize::new(0);
+
+type PrebuildFn = unsafe extern "system-unwind" fn(
+    *mut c_void,
+    *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS,
+    *const c_void,
+    *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO,
+);
+
+/// destination -> the bytes its build may write: what a copy of it writes
+static SIZES: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None);
+
+/// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's
+/// description, then 32 bytes of the builder's (its postbuild infos and two words).
+#[repr(C)]
+#[derive(Clone, Copy)]
+struct BatchedDesc {
+    build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC,
+    postbuild_count: u32,
+    _padding: u32,
+    postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC,
+    _tail: [u64; 2],
+}
+
+/// The address the title gets for an export of `module` it resolves (`original`): one of
+/// XboxBvhBuilder.dll's build and copy exports goes through its hook here, with
+/// `XCL_SPARSE_LAZY=1` only.
+pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize {
+    if !module.name.eq_ignore_ascii_case("xboxbvhbuilder.dll") || !super::sparse::lazy_asked() {
+        return original;
+    }
+    let name = match what {
+        ImportName::Name { name, .. } => Some(name.as_str()),
+        ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(n, t)| matches!(t, ExportTarget::Rva(v) if *v == rva).then_some(n.as_str())),
+    };
+    let Some((slot, hook)) = hook_for(name.unwrap_or("")) else { return original };
+    if let Some(ExportTarget::Rva(p)) = module.exports.by_name.get(PREBUILD) {
+        F_PREBUILD.store(module.base + *p as usize, Ordering::Release);
+    }
+    match slot.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) {
+        Ok(_) => {
+            crate::xlog_info!("D3D12.X: XboxBvhBuilder's {} gives the ranges it writes video memory (XCL_SPARSE_LAZY)", name.unwrap_or("?").split('@').next().unwrap_or("?").trim_start_matches('?'));
+            hook
+        }
+        Err(e) if e == original => hook,
+        Err(_) => original,
+    }
+}
+
+/// the slot and hook of one of the exports hooked here
+fn hook_for(name: &str) -> Option<(&'static AtomicUsize, usize)> {
+    match name {
+        BATCHED => Some((&F_BATCHED, batched as usize)),
+        SINGLE => Some((&F_SINGLE, single as usize)),
+        COPY => Some((&F_COPY, copy as usize)),
+        _ => None,
+    }
+}
+
+/// The builder's own `prebuild` answer for build `b`'s inputs (asked without a stream).
+unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO {
+    let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default();
+    prebuild(this, &b.Inputs, std::ptr::null(), &mut info);
+    info
+}
+
+/// What build `b` writes on the GPU, `info` being the builder's prebuild answer for it: its
+/// destination, for the most the builder writes there (remembered in `sizes` for a copy of it;
+/// with no size given, the destination's old one is forgotten).
+fn build_writes(b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, info: &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> {
+    let dest = b.DestAccelerationStructureData;
+    if dest == 0 {
+        return None;
+    }
+    if info.ResultDataMaxSizeInBytes == 0 {
+        sizes.remove(&dest);
+        return None;
+    }
+    sizes.insert(dest, info.ResultDataMaxSizeInBytes);
+    Some((dest, info.ResultDataMaxSizeInBytes))
+}
+
+/// What a copy of `source` to `dest` writes: as much as `source`'s build (or the copy that made
+/// it) could write, a clone or a compacted copy being no larger; that size becomes `dest`'s, for
+/// a copy of the copy. Other modes, and sources of unknown size: None, and `dest`'s old size is
+/// forgotten.
+fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> {
+    if dest == 0 {
+        return None;
+    }
+    let same_size = mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE || mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT;

copy_writes gives memory only for CLONE and COMPACT. SERIALIZE and DESERIALIZE copies are also GPU compute writes through the windows, but they get none and also forget the destination's size. A title that serializes structure X into a freshly committed lazy buffer to cache it, or deserializes a cached blob into a new lazy destination, gets None from copy_writes. The destination tiles stay LAZY, the builder's writes go nowhere, and the blob or deserialized BVH reads as zeros. Both cases have an upper bound: source size plus the serialization header for SERIALIZE, and the blob header's deserialized size for DESERIALIZE.

<!-- greyfinch-sync:ivall/xcl:review-comment:4768348637 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#discussion_r4768348637). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T10:46:58Z. **Code review location:** `crates/xcl/src/hle/d3d12x/bvh_builder.rs`; line 121 ~~~~diff @@ -0,0 +1,291 @@ +//! XboxBvhBuilder.dll's exports that build and copy acceleration structures, when the title +//! resolves them with `XCL_SPARSE_LAZY=1`: the ranges each call writes on the GPU are given +//! video memory (`sparse::will_write`) before the builder records its passes. +//! +//! With the switch, a tile the title commits has no video memory until the CPU's first bytes go +//! up to it or a placed buffer or a copy names it. The builder writes its structures with +//! compute programs through the sparse windows, which none of those see: in a retail title all +//! of a build's destination tiles and every compaction copy's had none, so what the builder +//! wrote went nowhere and the structures read as zeros (rays found nothing). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; + +const BATCHED: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +const SINGLE: &str = "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z"; +const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; +const PREBUILD: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; + +/// the builder's own entry points (0: not resolved by the title yet) +static F_BATCHED: AtomicUsize = AtomicUsize::new(0); +static F_SINGLE: AtomicUsize = AtomicUsize::new(0); +static F_COPY: AtomicUsize = AtomicUsize::new(0); +/// its `GetRaytracingAccelerationStructurePrebuildInfo`, found in the module when a hook is made +static F_PREBUILD: AtomicUsize = AtomicUsize::new(0); + +type PrebuildFn = unsafe extern "system-unwind" fn( + *mut c_void, + *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, + *const c_void, + *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, +); + +/// destination -> the bytes its build may write: what a copy of it writes +static SIZES: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None); + +/// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's +/// description, then 32 bytes of the builder's (its postbuild infos and two words). +#[repr(C)] +#[derive(Clone, Copy)] +struct BatchedDesc { + build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, + postbuild_count: u32, + _padding: u32, + postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC, + _tail: [u64; 2], +} + +/// The address the title gets for an export of `module` it resolves (`original`): one of +/// XboxBvhBuilder.dll's build and copy exports goes through its hook here, with +/// `XCL_SPARSE_LAZY=1` only. +pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize { + if !module.name.eq_ignore_ascii_case("xboxbvhbuilder.dll") || !super::sparse::lazy_asked() { + return original; + } + let name = match what { + ImportName::Name { name, .. } => Some(name.as_str()), + ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(n, t)| matches!(t, ExportTarget::Rva(v) if *v == rva).then_some(n.as_str())), + }; + let Some((slot, hook)) = hook_for(name.unwrap_or("")) else { return original }; + if let Some(ExportTarget::Rva(p)) = module.exports.by_name.get(PREBUILD) { + F_PREBUILD.store(module.base + *p as usize, Ordering::Release); + } + match slot.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + crate::xlog_info!("D3D12.X: XboxBvhBuilder's {} gives the ranges it writes video memory (XCL_SPARSE_LAZY)", name.unwrap_or("?").split('@').next().unwrap_or("?").trim_start_matches('?')); + hook + } + Err(e) if e == original => hook, + Err(_) => original, + } +} + +/// the slot and hook of one of the exports hooked here +fn hook_for(name: &str) -> Option<(&'static AtomicUsize, usize)> { + match name { + BATCHED => Some((&F_BATCHED, batched as usize)), + SINGLE => Some((&F_SINGLE, single as usize)), + COPY => Some((&F_COPY, copy as usize)), + _ => None, + } +} + +/// The builder's own `prebuild` answer for build `b`'s inputs (asked without a stream). +unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { + let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(); + prebuild(this, &b.Inputs, std::ptr::null(), &mut info); + info +} + +/// What build `b` writes on the GPU, `info` being the builder's prebuild answer for it: its +/// destination, for the most the builder writes there (remembered in `sizes` for a copy of it; +/// with no size given, the destination's old one is forgotten). +fn build_writes(b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, info: &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> { + let dest = b.DestAccelerationStructureData; + if dest == 0 { + return None; + } + if info.ResultDataMaxSizeInBytes == 0 { + sizes.remove(&dest); + return None; + } + sizes.insert(dest, info.ResultDataMaxSizeInBytes); + Some((dest, info.ResultDataMaxSizeInBytes)) +} + +/// What a copy of `source` to `dest` writes: as much as `source`'s build (or the copy that made +/// it) could write, a clone or a compacted copy being no larger; that size becomes `dest`'s, for +/// a copy of the copy. Other modes, and sources of unknown size: None, and `dest`'s old size is +/// forgotten. +fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> { + if dest == 0 { + return None; + } + let same_size = mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE || mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT; ~~~~ --- `copy_writes` gives memory only for CLONE and COMPACT. SERIALIZE and DESERIALIZE copies are also GPU compute writes through the windows, but they get none and also forget the destination's size. A title that serializes structure X into a freshly committed lazy buffer to cache it, or deserializes a cached blob into a new lazy destination, gets None from `copy_writes`. The destination tiles stay LAZY, the builder's writes go nowhere, and the blob or deserialized BVH reads as zeros. Both cases have an upper bound: source size plus the serialization header for SERIALIZE, and the blob header's deserialized size for DESERIALIZE.
bmjask commented 2026-12-02 10:46:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T10:46:58Z.

Code review location: crates/xcl/src/hle/d3d12x/bvh_builder.rs; line 106

@@ -0,0 +1,291 @@
+//! XboxBvhBuilder.dll's exports that build and copy acceleration structures, when the title
+//! resolves them with `XCL_SPARSE_LAZY=1`: the ranges each call writes on the GPU are given
+//! video memory (`sparse::will_write`) before the builder records its passes.
+//!
+//! With the switch, a tile the title commits has no video memory until the CPU's first bytes go
+//! up to it or a placed buffer or a copy names it. The builder writes its structures with
+//! compute programs through the sparse windows, which none of those see: in a retail title all
+//! of a build's destination tiles and every compaction copy's had none, so what the builder
+//! wrote went nowhere and the structures read as zeros (rays found nothing).
+
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Mutex;
+
+use windows::Win32::Graphics::Direct3D12::*;
+
+use crate::modules::MappedModule;
+use crate::pe::{ExportTarget, ImportName};
+
+const BATCHED: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z";
+const SINGLE: &str = "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z";
+const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z";
+const PREBUILD: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z";
+
+/// the builder's own entry points (0: not resolved by the title yet)
+static F_BATCHED: AtomicUsize = AtomicUsize::new(0);
+static F_SINGLE: AtomicUsize = AtomicUsize::new(0);
+static F_COPY: AtomicUsize = AtomicUsize::new(0);
+/// its `GetRaytracingAccelerationStructurePrebuildInfo`, found in the module when a hook is made
+static F_PREBUILD: AtomicUsize = AtomicUsize::new(0);
+
+type PrebuildFn = unsafe extern "system-unwind" fn(
+    *mut c_void,
+    *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS,
+    *const c_void,
+    *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO,
+);
+
+/// destination -> the bytes its build may write: what a copy of it writes
+static SIZES: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None);
+
+/// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's
+/// description, then 32 bytes of the builder's (its postbuild infos and two words).
+#[repr(C)]
+#[derive(Clone, Copy)]
+struct BatchedDesc {
+    build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC,
+    postbuild_count: u32,
+    _padding: u32,
+    postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC,
+    _tail: [u64; 2],
+}
+
+/// The address the title gets for an export of `module` it resolves (`original`): one of
+/// XboxBvhBuilder.dll's build and copy exports goes through its hook here, with
+/// `XCL_SPARSE_LAZY=1` only.
+pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize {
+    if !module.name.eq_ignore_ascii_case("xboxbvhbuilder.dll") || !super::sparse::lazy_asked() {
+        return original;
+    }
+    let name = match what {
+        ImportName::Name { name, .. } => Some(name.as_str()),
+        ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(n, t)| matches!(t, ExportTarget::Rva(v) if *v == rva).then_some(n.as_str())),
+    };
+    let Some((slot, hook)) = hook_for(name.unwrap_or("")) else { return original };
+    if let Some(ExportTarget::Rva(p)) = module.exports.by_name.get(PREBUILD) {
+        F_PREBUILD.store(module.base + *p as usize, Ordering::Release);
+    }
+    match slot.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) {
+        Ok(_) => {
+            crate::xlog_info!("D3D12.X: XboxBvhBuilder's {} gives the ranges it writes video memory (XCL_SPARSE_LAZY)", name.unwrap_or("?").split('@').next().unwrap_or("?").trim_start_matches('?'));
+            hook
+        }
+        Err(e) if e == original => hook,
+        Err(_) => original,
+    }
+}
+
+/// the slot and hook of one of the exports hooked here
+fn hook_for(name: &str) -> Option<(&'static AtomicUsize, usize)> {
+    match name {
+        BATCHED => Some((&F_BATCHED, batched as usize)),
+        SINGLE => Some((&F_SINGLE, single as usize)),
+        COPY => Some((&F_COPY, copy as usize)),
+        _ => None,
+    }
+}
+
+/// The builder's own `prebuild` answer for build `b`'s inputs (asked without a stream).
+unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO {
+    let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default();
+    prebuild(this, &b.Inputs, std::ptr::null(), &mut info);
+    info
+}
+
+/// What build `b` writes on the GPU, `info` being the builder's prebuild answer for it: its
+/// destination, for the most the builder writes there (remembered in `sizes` for a copy of it;
+/// with no size given, the destination's old one is forgotten).
+fn build_writes(b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, info: &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> {
+    let dest = b.DestAccelerationStructureData;
+    if dest == 0 {
+        return None;
+    }
+    if info.ResultDataMaxSizeInBytes == 0 {
+        sizes.remove(&dest);

Not certain about this one, because it depends on what XboxBvhBuilder's prebuild returns for update inputs: an update build (PERFORM_UPDATE, often in place with dest == source) re-queries the builder's prebuild with update inputs, and if that returns ResultDataMaxSizeInBytes == 0, build_writes forgets the size the original build recorded. A BLAS built with ALLOW_UPDATE|ALLOW_COMPACTION (0x3000 recorded), refit in place, then compacted into Y: sizes.remove(X) ran, copy_writes(Y, X, COMPACT) finds no source size, Y gets no memory, and the compacted structure reads as zeros, the bug this PR fixes, coming back after a refit. Updates could keep the existing size instead of re-querying.

<!-- greyfinch-sync:ivall/xcl:review-comment:4768348640 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#discussion_r4768348640). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T10:46:58Z. **Code review location:** `crates/xcl/src/hle/d3d12x/bvh_builder.rs`; line 106 ~~~~diff @@ -0,0 +1,291 @@ +//! XboxBvhBuilder.dll's exports that build and copy acceleration structures, when the title +//! resolves them with `XCL_SPARSE_LAZY=1`: the ranges each call writes on the GPU are given +//! video memory (`sparse::will_write`) before the builder records its passes. +//! +//! With the switch, a tile the title commits has no video memory until the CPU's first bytes go +//! up to it or a placed buffer or a copy names it. The builder writes its structures with +//! compute programs through the sparse windows, which none of those see: in a retail title all +//! of a build's destination tiles and every compaction copy's had none, so what the builder +//! wrote went nowhere and the structures read as zeros (rays found nothing). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; + +const BATCHED: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +const SINGLE: &str = "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z"; +const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; +const PREBUILD: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; + +/// the builder's own entry points (0: not resolved by the title yet) +static F_BATCHED: AtomicUsize = AtomicUsize::new(0); +static F_SINGLE: AtomicUsize = AtomicUsize::new(0); +static F_COPY: AtomicUsize = AtomicUsize::new(0); +/// its `GetRaytracingAccelerationStructurePrebuildInfo`, found in the module when a hook is made +static F_PREBUILD: AtomicUsize = AtomicUsize::new(0); + +type PrebuildFn = unsafe extern "system-unwind" fn( + *mut c_void, + *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, + *const c_void, + *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, +); + +/// destination -> the bytes its build may write: what a copy of it writes +static SIZES: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None); + +/// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's +/// description, then 32 bytes of the builder's (its postbuild infos and two words). +#[repr(C)] +#[derive(Clone, Copy)] +struct BatchedDesc { + build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, + postbuild_count: u32, + _padding: u32, + postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC, + _tail: [u64; 2], +} + +/// The address the title gets for an export of `module` it resolves (`original`): one of +/// XboxBvhBuilder.dll's build and copy exports goes through its hook here, with +/// `XCL_SPARSE_LAZY=1` only. +pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize { + if !module.name.eq_ignore_ascii_case("xboxbvhbuilder.dll") || !super::sparse::lazy_asked() { + return original; + } + let name = match what { + ImportName::Name { name, .. } => Some(name.as_str()), + ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(n, t)| matches!(t, ExportTarget::Rva(v) if *v == rva).then_some(n.as_str())), + }; + let Some((slot, hook)) = hook_for(name.unwrap_or("")) else { return original }; + if let Some(ExportTarget::Rva(p)) = module.exports.by_name.get(PREBUILD) { + F_PREBUILD.store(module.base + *p as usize, Ordering::Release); + } + match slot.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + crate::xlog_info!("D3D12.X: XboxBvhBuilder's {} gives the ranges it writes video memory (XCL_SPARSE_LAZY)", name.unwrap_or("?").split('@').next().unwrap_or("?").trim_start_matches('?')); + hook + } + Err(e) if e == original => hook, + Err(_) => original, + } +} + +/// the slot and hook of one of the exports hooked here +fn hook_for(name: &str) -> Option<(&'static AtomicUsize, usize)> { + match name { + BATCHED => Some((&F_BATCHED, batched as usize)), + SINGLE => Some((&F_SINGLE, single as usize)), + COPY => Some((&F_COPY, copy as usize)), + _ => None, + } +} + +/// The builder's own `prebuild` answer for build `b`'s inputs (asked without a stream). +unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { + let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(); + prebuild(this, &b.Inputs, std::ptr::null(), &mut info); + info +} + +/// What build `b` writes on the GPU, `info` being the builder's prebuild answer for it: its +/// destination, for the most the builder writes there (remembered in `sizes` for a copy of it; +/// with no size given, the destination's old one is forgotten). +fn build_writes(b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, info: &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> { + let dest = b.DestAccelerationStructureData; + if dest == 0 { + return None; + } + if info.ResultDataMaxSizeInBytes == 0 { + sizes.remove(&dest); ~~~~ --- Not certain about this one, because it depends on what XboxBvhBuilder's prebuild returns for update inputs: an update build (PERFORM_UPDATE, often in place with dest == source) re-queries the builder's prebuild with update inputs, and if that returns ResultDataMaxSizeInBytes == 0, `build_writes` forgets the size the original build recorded. A BLAS built with ALLOW_UPDATE|ALLOW_COMPACTION (0x3000 recorded), refit in place, then compacted into Y: `sizes.remove(X)` ran, `copy_writes(Y, X, COMPACT)` finds no source size, Y gets no memory, and the compacted structure reads as zeros, the bug this PR fixes, coming back after a refit. Updates could keep the existing size instead of re-querying.
bmjask commented 2026-12-02 10:46:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T10:46:58Z.

Code review location: crates/xcl/src/hle/d3d12x/bvh_builder.rs; line 93

@@ -0,0 +1,291 @@
+//! XboxBvhBuilder.dll's exports that build and copy acceleration structures, when the title
+//! resolves them with `XCL_SPARSE_LAZY=1`: the ranges each call writes on the GPU are given
+//! video memory (`sparse::will_write`) before the builder records its passes.
+//!
+//! With the switch, a tile the title commits has no video memory until the CPU's first bytes go
+//! up to it or a placed buffer or a copy names it. The builder writes its structures with
+//! compute programs through the sparse windows, which none of those see: in a retail title all
+//! of a build's destination tiles and every compaction copy's had none, so what the builder
+//! wrote went nowhere and the structures read as zeros (rays found nothing).
+
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Mutex;
+
+use windows::Win32::Graphics::Direct3D12::*;
+
+use crate::modules::MappedModule;
+use crate::pe::{ExportTarget, ImportName};
+
+const BATCHED: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z";
+const SINGLE: &str = "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z";
+const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z";
+const PREBUILD: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z";
+
+/// the builder's own entry points (0: not resolved by the title yet)
+static F_BATCHED: AtomicUsize = AtomicUsize::new(0);
+static F_SINGLE: AtomicUsize = AtomicUsize::new(0);
+static F_COPY: AtomicUsize = AtomicUsize::new(0);
+/// its `GetRaytracingAccelerationStructurePrebuildInfo`, found in the module when a hook is made
+static F_PREBUILD: AtomicUsize = AtomicUsize::new(0);
+
+type PrebuildFn = unsafe extern "system-unwind" fn(
+    *mut c_void,
+    *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS,
+    *const c_void,
+    *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO,
+);
+
+/// destination -> the bytes its build may write: what a copy of it writes
+static SIZES: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None);
+
+/// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's
+/// description, then 32 bytes of the builder's (its postbuild infos and two words).
+#[repr(C)]
+#[derive(Clone, Copy)]
+struct BatchedDesc {
+    build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC,
+    postbuild_count: u32,
+    _padding: u32,
+    postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC,
+    _tail: [u64; 2],
+}
+
+/// The address the title gets for an export of `module` it resolves (`original`): one of
+/// XboxBvhBuilder.dll's build and copy exports goes through its hook here, with
+/// `XCL_SPARSE_LAZY=1` only.
+pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize {
+    if !module.name.eq_ignore_ascii_case("xboxbvhbuilder.dll") || !super::sparse::lazy_asked() {
+        return original;
+    }
+    let name = match what {
+        ImportName::Name { name, .. } => Some(name.as_str()),
+        ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(n, t)| matches!(t, ExportTarget::Rva(v) if *v == rva).then_some(n.as_str())),
+    };
+    let Some((slot, hook)) = hook_for(name.unwrap_or("")) else { return original };
+    if let Some(ExportTarget::Rva(p)) = module.exports.by_name.get(PREBUILD) {
+        F_PREBUILD.store(module.base + *p as usize, Ordering::Release);
+    }
+    match slot.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) {
+        Ok(_) => {
+            crate::xlog_info!("D3D12.X: XboxBvhBuilder's {} gives the ranges it writes video memory (XCL_SPARSE_LAZY)", name.unwrap_or("?").split('@').next().unwrap_or("?").trim_start_matches('?'));
+            hook
+        }
+        Err(e) if e == original => hook,
+        Err(_) => original,
+    }
+}
+
+/// the slot and hook of one of the exports hooked here
+fn hook_for(name: &str) -> Option<(&'static AtomicUsize, usize)> {
+    match name {
+        BATCHED => Some((&F_BATCHED, batched as usize)),
+        SINGLE => Some((&F_SINGLE, single as usize)),
+        COPY => Some((&F_COPY, copy as usize)),
+        _ => None,
+    }
+}
+
+/// The builder's own `prebuild` answer for build `b`'s inputs (asked without a stream).
+unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO {
+    let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default();
+    prebuild(this, &b.Inputs, std::ptr::null(), &mut info);

Not certain about this one: the prebuild query always passes a null D3D12XBOX_XDXR_STREAM_DESC, even for batched builds whose element carries builder data in _tail (possibly a stream), so the size can differ from what the real build writes. If a Batched2X element built with an XDXR stream writes more than the stream-less prebuild answer (as bvh::prebuild_size underestimates flags-0x4 top levels: 0x198400 vs 0x227000), only part of the destination gets memory and the BVH's tail lands on LAZY tiles, so traversal reads zero nodes.

<!-- greyfinch-sync:ivall/xcl:review-comment:4768348647 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#discussion_r4768348647). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T10:46:58Z. **Code review location:** `crates/xcl/src/hle/d3d12x/bvh_builder.rs`; line 93 ~~~~diff @@ -0,0 +1,291 @@ +//! XboxBvhBuilder.dll's exports that build and copy acceleration structures, when the title +//! resolves them with `XCL_SPARSE_LAZY=1`: the ranges each call writes on the GPU are given +//! video memory (`sparse::will_write`) before the builder records its passes. +//! +//! With the switch, a tile the title commits has no video memory until the CPU's first bytes go +//! up to it or a placed buffer or a copy names it. The builder writes its structures with +//! compute programs through the sparse windows, which none of those see: in a retail title all +//! of a build's destination tiles and every compaction copy's had none, so what the builder +//! wrote went nowhere and the structures read as zeros (rays found nothing). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; + +const BATCHED: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +const SINGLE: &str = "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z"; +const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; +const PREBUILD: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; + +/// the builder's own entry points (0: not resolved by the title yet) +static F_BATCHED: AtomicUsize = AtomicUsize::new(0); +static F_SINGLE: AtomicUsize = AtomicUsize::new(0); +static F_COPY: AtomicUsize = AtomicUsize::new(0); +/// its `GetRaytracingAccelerationStructurePrebuildInfo`, found in the module when a hook is made +static F_PREBUILD: AtomicUsize = AtomicUsize::new(0); + +type PrebuildFn = unsafe extern "system-unwind" fn( + *mut c_void, + *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, + *const c_void, + *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, +); + +/// destination -> the bytes its build may write: what a copy of it writes +static SIZES: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None); + +/// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's +/// description, then 32 bytes of the builder's (its postbuild infos and two words). +#[repr(C)] +#[derive(Clone, Copy)] +struct BatchedDesc { + build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, + postbuild_count: u32, + _padding: u32, + postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC, + _tail: [u64; 2], +} + +/// The address the title gets for an export of `module` it resolves (`original`): one of +/// XboxBvhBuilder.dll's build and copy exports goes through its hook here, with +/// `XCL_SPARSE_LAZY=1` only. +pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize { + if !module.name.eq_ignore_ascii_case("xboxbvhbuilder.dll") || !super::sparse::lazy_asked() { + return original; + } + let name = match what { + ImportName::Name { name, .. } => Some(name.as_str()), + ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(n, t)| matches!(t, ExportTarget::Rva(v) if *v == rva).then_some(n.as_str())), + }; + let Some((slot, hook)) = hook_for(name.unwrap_or("")) else { return original }; + if let Some(ExportTarget::Rva(p)) = module.exports.by_name.get(PREBUILD) { + F_PREBUILD.store(module.base + *p as usize, Ordering::Release); + } + match slot.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + crate::xlog_info!("D3D12.X: XboxBvhBuilder's {} gives the ranges it writes video memory (XCL_SPARSE_LAZY)", name.unwrap_or("?").split('@').next().unwrap_or("?").trim_start_matches('?')); + hook + } + Err(e) if e == original => hook, + Err(_) => original, + } +} + +/// the slot and hook of one of the exports hooked here +fn hook_for(name: &str) -> Option<(&'static AtomicUsize, usize)> { + match name { + BATCHED => Some((&F_BATCHED, batched as usize)), + SINGLE => Some((&F_SINGLE, single as usize)), + COPY => Some((&F_COPY, copy as usize)), + _ => None, + } +} + +/// The builder's own `prebuild` answer for build `b`'s inputs (asked without a stream). +unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { + let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(); + prebuild(this, &b.Inputs, std::ptr::null(), &mut info); ~~~~ --- Not certain about this one: the prebuild query always passes a null D3D12XBOX_XDXR_STREAM_DESC, even for batched builds whose element carries builder data in `_tail` (possibly a stream), so the size can differ from what the real build writes. If a Batched2X element built with an XDXR stream writes more than the stream-less prebuild answer (as `bvh::prebuild_size` underestimates flags-0x4 top levels: 0x198400 vs 0x227000), only part of the destination gets memory and the BVH's tail lands on LAZY tiles, so traversal reads zero nodes.
bmjask commented 2026-12-02 10:46:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T10:46:58Z.

Code review location: crates/xcl/src/hle/d3d12x/bvh_builder.rs; line 185

@@ -0,0 +1,291 @@
+//! XboxBvhBuilder.dll's exports that build and copy acceleration structures, when the title
+//! resolves them with `XCL_SPARSE_LAZY=1`: the ranges each call writes on the GPU are given
+//! video memory (`sparse::will_write`) before the builder records its passes.
+//!
+//! With the switch, a tile the title commits has no video memory until the CPU's first bytes go
+//! up to it or a placed buffer or a copy names it. The builder writes its structures with
+//! compute programs through the sparse windows, which none of those see: in a retail title all
+//! of a build's destination tiles and every compaction copy's had none, so what the builder
+//! wrote went nowhere and the structures read as zeros (rays found nothing).
+
+use std::collections::HashMap;
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Mutex;
+
+use windows::Win32::Graphics::Direct3D12::*;
+
+use crate::modules::MappedModule;
+use crate::pe::{ExportTarget, ImportName};
+
+const BATCHED: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z";
+const SINGLE: &str = "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z";
+const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z";
+const PREBUILD: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z";
+
+/// the builder's own entry points (0: not resolved by the title yet)
+static F_BATCHED: AtomicUsize = AtomicUsize::new(0);
+static F_SINGLE: AtomicUsize = AtomicUsize::new(0);
+static F_COPY: AtomicUsize = AtomicUsize::new(0);
+/// its `GetRaytracingAccelerationStructurePrebuildInfo`, found in the module when a hook is made
+static F_PREBUILD: AtomicUsize = AtomicUsize::new(0);
+
+type PrebuildFn = unsafe extern "system-unwind" fn(
+    *mut c_void,
+    *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS,
+    *const c_void,
+    *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO,
+);
+
+/// destination -> the bytes its build may write: what a copy of it writes
+static SIZES: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None);
+
+/// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's
+/// description, then 32 bytes of the builder's (its postbuild infos and two words).
+#[repr(C)]
+#[derive(Clone, Copy)]
+struct BatchedDesc {
+    build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC,
+    postbuild_count: u32,
+    _padding: u32,
+    postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC,
+    _tail: [u64; 2],
+}
+
+/// The address the title gets for an export of `module` it resolves (`original`): one of
+/// XboxBvhBuilder.dll's build and copy exports goes through its hook here, with
+/// `XCL_SPARSE_LAZY=1` only.
+pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize {
+    if !module.name.eq_ignore_ascii_case("xboxbvhbuilder.dll") || !super::sparse::lazy_asked() {
+        return original;
+    }
+    let name = match what {
+        ImportName::Name { name, .. } => Some(name.as_str()),
+        ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(n, t)| matches!(t, ExportTarget::Rva(v) if *v == rva).then_some(n.as_str())),
+    };
+    let Some((slot, hook)) = hook_for(name.unwrap_or("")) else { return original };
+    if let Some(ExportTarget::Rva(p)) = module.exports.by_name.get(PREBUILD) {
+        F_PREBUILD.store(module.base + *p as usize, Ordering::Release);
+    }
+    match slot.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) {
+        Ok(_) => {
+            crate::xlog_info!("D3D12.X: XboxBvhBuilder's {} gives the ranges it writes video memory (XCL_SPARSE_LAZY)", name.unwrap_or("?").split('@').next().unwrap_or("?").trim_start_matches('?'));
+            hook
+        }
+        Err(e) if e == original => hook,
+        Err(_) => original,
+    }
+}
+
+/// the slot and hook of one of the exports hooked here
+fn hook_for(name: &str) -> Option<(&'static AtomicUsize, usize)> {
+    match name {
+        BATCHED => Some((&F_BATCHED, batched as usize)),
+        SINGLE => Some((&F_SINGLE, single as usize)),
+        COPY => Some((&F_COPY, copy as usize)),
+        _ => None,
+    }
+}
+
+/// The builder's own `prebuild` answer for build `b`'s inputs (asked without a stream).
+unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO {
+    let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default();
+    prebuild(this, &b.Inputs, std::ptr::null(), &mut info);
+    info
+}
+
+/// What build `b` writes on the GPU, `info` being the builder's prebuild answer for it: its
+/// destination, for the most the builder writes there (remembered in `sizes` for a copy of it;
+/// with no size given, the destination's old one is forgotten).
+fn build_writes(b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, info: &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> {
+    let dest = b.DestAccelerationStructureData;
+    if dest == 0 {
+        return None;
+    }
+    if info.ResultDataMaxSizeInBytes == 0 {
+        sizes.remove(&dest);
+        return None;
+    }
+    sizes.insert(dest, info.ResultDataMaxSizeInBytes);
+    Some((dest, info.ResultDataMaxSizeInBytes))
+}
+
+/// What a copy of `source` to `dest` writes: as much as `source`'s build (or the copy that made
+/// it) could write, a clone or a compacted copy being no larger; that size becomes `dest`'s, for
+/// a copy of the copy. Other modes, and sources of unknown size: None, and `dest`'s old size is
+/// forgotten.
+fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> {
+    if dest == 0 {
+        return None;
+    }
+    let same_size = mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE || mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT;
+    match sizes.get(&source).copied().filter(|_| same_size) {
+        Some(n) => {
+            sizes.insert(dest, n);
+            Some((dest, n))
+        }
+        None => {
+            sizes.remove(&dest);
+            None
+        }
+    }
+}
+
+/// What a build's postbuild infos `posts` write on the GPU: each one's `DestBuffer`, for the
+/// bytes of its info type (an unknown type: nothing).
+pub(super) fn postbuild_writes(posts: &[D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC]) -> impl Iterator<Item = (u64, u64)> + '_ {
+    posts.iter().filter_map(|p| {
+        let n = match p.InfoType {
+            D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE => std::mem::size_of::<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE_DESC>(),
+            D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION => std::mem::size_of::<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION_DESC>(),
+            D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION => std::mem::size_of::<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION_DESC>(),
+            D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE => std::mem::size_of::<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE_DESC>(),
+            _ => return None,
+        };
+        (p.DestBuffer != 0).then_some((p.DestBuffer, n as u64))
+    })
+}
+
+/// The GPU writes `[va, va + len)`: its tiles get video memory before the list runs.
+fn give(va: u64, len: u64) {
+    super::sparse::will_write(va as usize, len as usize);
+}
+
+unsafe fn give_build(this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) {
+    let pf = F_PREBUILD.load(Ordering::Acquire);
+    if pf == 0 {
+        static ONCE: std::sync::Once = std::sync::Once::new();
+        ONCE.call_once(|| crate::xlog_warn!("D3D12.X: XboxBvhBuilder exports no prebuild-info query: its builds get no video memory where they write"));
+        return;
+    }
+    if b.DestAccelerationStructureData == 0 {
+        return;
+    }
+    // asked before the lock: other lists' builds do not wait for this one's query
+    let info = prebuild_info(std::mem::transmute::<usize, PrebuildFn>(pf), this, b);
+    let writes = build_writes(b, &info, SIZES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new));
+    if let Some((va, len)) = writes {
+        give(va, len);
+    }
+}
+
+/// a build's `count` postbuild infos at `posts` give what they write video memory
+unsafe fn give_postbuild(count: u32, posts: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) {
+    if count > 0 && crate::gpu::shader::readable(posts as usize, count as usize * std::mem::size_of::<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC>()) {
+        for (va, len) in postbuild_writes(std::slice::from_raw_parts(posts, count as usize)) {
+            give(va, len);
+        }
+    }
+}
+
+unsafe extern "system-unwind" fn batched(this: *mut c_void, list: *mut c_void, count: u32, descs: *const BatchedDesc) {
+    if count > 0 && crate::gpu::shader::readable(descs as usize, count as usize * std::mem::size_of::<BatchedDesc>()) {
+        for d in std::slice::from_raw_parts(descs, count as usize) {
+            give_build(this, &d.build);
+            give_postbuild(d.postbuild_count, d.postbuild);

Not certain about this one: postbuild DestBuffers get GPU memory but are never added to the list's read-back set (list_x note_write / sparse_writes). So a title that reads the compacted size on the CPU from a window the GPU has a copy of (read_back(va) true), after waiting on the fence, still reads 0, and then allocates or compacts with size 0 or skips compaction.

<!-- greyfinch-sync:ivall/xcl:review-comment:4768348654 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#discussion_r4768348654). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T10:46:58Z. **Code review location:** `crates/xcl/src/hle/d3d12x/bvh_builder.rs`; line 185 ~~~~diff @@ -0,0 +1,291 @@ +//! XboxBvhBuilder.dll's exports that build and copy acceleration structures, when the title +//! resolves them with `XCL_SPARSE_LAZY=1`: the ranges each call writes on the GPU are given +//! video memory (`sparse::will_write`) before the builder records its passes. +//! +//! With the switch, a tile the title commits has no video memory until the CPU's first bytes go +//! up to it or a placed buffer or a copy names it. The builder writes its structures with +//! compute programs through the sparse windows, which none of those see: in a retail title all +//! of a build's destination tiles and every compaction copy's had none, so what the builder +//! wrote went nowhere and the structures read as zeros (rays found nothing). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; + +const BATCHED: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +const SINGLE: &str = "?BuildRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@PEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@IPEBUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC@@@Z"; +const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; +const PREBUILD: &str = "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; + +/// the builder's own entry points (0: not resolved by the title yet) +static F_BATCHED: AtomicUsize = AtomicUsize::new(0); +static F_SINGLE: AtomicUsize = AtomicUsize::new(0); +static F_COPY: AtomicUsize = AtomicUsize::new(0); +/// its `GetRaytracingAccelerationStructurePrebuildInfo`, found in the module when a hook is made +static F_PREBUILD: AtomicUsize = AtomicUsize::new(0); + +type PrebuildFn = unsafe extern "system-unwind" fn( + *mut c_void, + *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, + *const c_void, + *mut D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, +); + +/// destination -> the bytes its build may write: what a copy of it writes +static SIZES: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None); + +/// One element of `BuildRaytracingAccelerationStructureBatched2X`'s array: the build's +/// description, then 32 bytes of the builder's (its postbuild infos and two words). +#[repr(C)] +#[derive(Clone, Copy)] +struct BatchedDesc { + build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, + postbuild_count: u32, + _padding: u32, + postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC, + _tail: [u64; 2], +} + +/// The address the title gets for an export of `module` it resolves (`original`): one of +/// XboxBvhBuilder.dll's build and copy exports goes through its hook here, with +/// `XCL_SPARSE_LAZY=1` only. +pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize { + if !module.name.eq_ignore_ascii_case("xboxbvhbuilder.dll") || !super::sparse::lazy_asked() { + return original; + } + let name = match what { + ImportName::Name { name, .. } => Some(name.as_str()), + ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(n, t)| matches!(t, ExportTarget::Rva(v) if *v == rva).then_some(n.as_str())), + }; + let Some((slot, hook)) = hook_for(name.unwrap_or("")) else { return original }; + if let Some(ExportTarget::Rva(p)) = module.exports.by_name.get(PREBUILD) { + F_PREBUILD.store(module.base + *p as usize, Ordering::Release); + } + match slot.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + crate::xlog_info!("D3D12.X: XboxBvhBuilder's {} gives the ranges it writes video memory (XCL_SPARSE_LAZY)", name.unwrap_or("?").split('@').next().unwrap_or("?").trim_start_matches('?')); + hook + } + Err(e) if e == original => hook, + Err(_) => original, + } +} + +/// the slot and hook of one of the exports hooked here +fn hook_for(name: &str) -> Option<(&'static AtomicUsize, usize)> { + match name { + BATCHED => Some((&F_BATCHED, batched as usize)), + SINGLE => Some((&F_SINGLE, single as usize)), + COPY => Some((&F_COPY, copy as usize)), + _ => None, + } +} + +/// The builder's own `prebuild` answer for build `b`'s inputs (asked without a stream). +unsafe fn prebuild_info(prebuild: PrebuildFn, this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO { + let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(); + prebuild(this, &b.Inputs, std::ptr::null(), &mut info); + info +} + +/// What build `b` writes on the GPU, `info` being the builder's prebuild answer for it: its +/// destination, for the most the builder writes there (remembered in `sizes` for a copy of it; +/// with no size given, the destination's old one is forgotten). +fn build_writes(b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, info: &D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> { + let dest = b.DestAccelerationStructureData; + if dest == 0 { + return None; + } + if info.ResultDataMaxSizeInBytes == 0 { + sizes.remove(&dest); + return None; + } + sizes.insert(dest, info.ResultDataMaxSizeInBytes); + Some((dest, info.ResultDataMaxSizeInBytes)) +} + +/// What a copy of `source` to `dest` writes: as much as `source`'s build (or the copy that made +/// it) could write, a clone or a compacted copy being no larger; that size becomes `dest`'s, for +/// a copy of the copy. Other modes, and sources of unknown size: None, and `dest`'s old size is +/// forgotten. +fn copy_writes(dest: u64, source: u64, mode: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE, sizes: &mut HashMap<u64, u64>) -> Option<(u64, u64)> { + if dest == 0 { + return None; + } + let same_size = mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE || mode == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT; + match sizes.get(&source).copied().filter(|_| same_size) { + Some(n) => { + sizes.insert(dest, n); + Some((dest, n)) + } + None => { + sizes.remove(&dest); + None + } + } +} + +/// What a build's postbuild infos `posts` write on the GPU: each one's `DestBuffer`, for the +/// bytes of its info type (an unknown type: nothing). +pub(super) fn postbuild_writes(posts: &[D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC]) -> impl Iterator<Item = (u64, u64)> + '_ { + posts.iter().filter_map(|p| { + let n = match p.InfoType { + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE => std::mem::size_of::<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE_DESC>(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION => std::mem::size_of::<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION_DESC>(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION => std::mem::size_of::<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION_DESC>(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE => std::mem::size_of::<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE_DESC>(), + _ => return None, + }; + (p.DestBuffer != 0).then_some((p.DestBuffer, n as u64)) + }) +} + +/// The GPU writes `[va, va + len)`: its tiles get video memory before the list runs. +fn give(va: u64, len: u64) { + super::sparse::will_write(va as usize, len as usize); +} + +unsafe fn give_build(this: *mut c_void, b: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) { + let pf = F_PREBUILD.load(Ordering::Acquire); + if pf == 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: XboxBvhBuilder exports no prebuild-info query: its builds get no video memory where they write")); + return; + } + if b.DestAccelerationStructureData == 0 { + return; + } + // asked before the lock: other lists' builds do not wait for this one's query + let info = prebuild_info(std::mem::transmute::<usize, PrebuildFn>(pf), this, b); + let writes = build_writes(b, &info, SIZES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new)); + if let Some((va, len)) = writes { + give(va, len); + } +} + +/// a build's `count` postbuild infos at `posts` give what they write video memory +unsafe fn give_postbuild(count: u32, posts: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) { + if count > 0 && crate::gpu::shader::readable(posts as usize, count as usize * std::mem::size_of::<D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC>()) { + for (va, len) in postbuild_writes(std::slice::from_raw_parts(posts, count as usize)) { + give(va, len); + } + } +} + +unsafe extern "system-unwind" fn batched(this: *mut c_void, list: *mut c_void, count: u32, descs: *const BatchedDesc) { + if count > 0 && crate::gpu::shader::readable(descs as usize, count as usize * std::mem::size_of::<BatchedDesc>()) { + for d in std::slice::from_raw_parts(descs, count as usize) { + give_build(this, &d.build); + give_postbuild(d.postbuild_count, d.postbuild); ~~~~ --- Not certain about this one: postbuild DestBuffers get GPU memory but are never added to the list's read-back set (list_x `note_write` / `sparse_writes`). So a title that reads the compacted size on the CPU from a window the GPU has a copy of (`read_back(va)` true), after waiting on the fence, still reads 0, and then allocates or compacts with size 0 or skips compaction.
kole07139 commented 2026-12-02 10:53:33 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by kole07139 on 2026-12-02T10:53:33Z.


merge-check claim
head: 2e2d9320ae

<!-- greyfinch-sync:ivall/xcl:comment:7343129186 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#issuecomment-7343129186). Originally posted by [kole07139](https://github.com/kole07139) on 2026-12-02T10:53:33Z. --- merge-check claim head: 2e2d9320ae0d72e2e635eebfacb6a8913c0107a9
kole07139 commented 2026-12-02 11:28:39 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by kole07139 on 2026-12-02T11:28:39Z.


merge-check
base: 1c8b551475
head: 2e2d9320ae
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2914 passed, 0 failed, 51 ignored; SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 driver cache needs Developer Mode; the same set as main). The library harness ran to its end here, and the PR's 5 tests passed; the sparse GPU one ran (not skipped). Failing: none.
review: read the whole diff (bvh_builder.rs, mod.rs, sparse.rs, resolver.rs). No correctness problem found.

  • Switch off: intercept returns the original address unless the module is xboxbvhbuilder.dll and XCL_SPARSE_LAZY=1 was given, so nothing changes by default. The resolver pays one case-insensitive name compare per export it resolves.
  • Switch on: will_write only queues the range (it gets memory at the next submit, before the list) and acts only with lazy_commits(), so the hooks never wait on the sparse state.
  • In the retail title, with XCL_SPARSE_LAZY=1, the hooks are installed for BuildRaytracingAccelerationStructureBatched2X and CopyRaytracingAccelerationStructure (0.8 s; the title doesn't resolve the single-build export).
    • A local counting probe in the hooks (not part of the PR) saw no call in a 150 s run: the title builds no acceleration structure before world load, which this card doesn't reach.
    • So the prebuild query with a null stream desc, the BatchedDesc layout and the copy sizes are still not exercised by a real title here, as in fromthemoonx's check.
  • Foniass's open points from the re-review stand; none matters with the switch off:
    • a compacted copy recorded at its source's maximum size;
    • requests dropped without a log when memory is short;
    • SIZES never pruned;
    • the BatchedDesc layout unverified against the DLL.
      performance: none by default. Retail title, main 1c8b5514 vs this merge (9e545b7a), 0 device removals and 0 crashes in every run:
  • 60 s, defaults: 1557 -> 1564 frames, peak commit 16672 -> 18605 MB (within the 16.3-19.0 GB spread of this title's 60 s runs here).
  • 60 s with XCL_SPARSE_LAZY=1: 1562 -> 1565 frames, 17252 -> 17627 MB.
  • 150 s with XCL_SPARSE_LAZY=1, two runs each:
    • base: 4291 frames / 17027 MB, and 2497 / 34467 MB;
    • merge: 4079 / 25386 MB, and 2920 / 30832 MB with the probe.
    • The large peaks come from the title starting to stream after its menus, at a time that varies from run to run, on base as well. In none of these runs did the PR's hooks run.
      verdict: safe to merge
      hardware / tool and model: NVIDIA GeForce RTX 3070 8 GB (driver 32.0.16.2140), Intel Core i9-9900K, Windows 11 Pro N 26200 / Claude Code with Claude Opus 5.5 (ran the merge, build, suite, smoke runs and probe, and wrote this check)

AI-written; posted without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7343973878 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#issuecomment-7343973878). Originally posted by [kole07139](https://github.com/kole07139) on 2026-12-02T11:28:39Z. --- merge-check base: 1c8b551475e1e7bfe48f94448492a4c3544a2e0f head: 2e2d9320ae0d72e2e635eebfacb6a8913c0107a9 merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2914 passed, 0 failed, 51 ignored; SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 driver cache needs Developer Mode; the same set as main). The library harness ran to its end here, and the PR's 5 tests passed; the sparse GPU one ran (not skipped). Failing: none. review: read the whole diff (bvh_builder.rs, mod.rs, sparse.rs, resolver.rs). No correctness problem found. - Switch off: `intercept` returns the original address unless the module is xboxbvhbuilder.dll and `XCL_SPARSE_LAZY=1` was given, so nothing changes by default. The resolver pays one case-insensitive name compare per export it resolves. - Switch on: `will_write` only queues the range (it gets memory at the next submit, before the list) and acts only with `lazy_commits()`, so the hooks never wait on the sparse state. - In the retail title, with `XCL_SPARSE_LAZY=1`, the hooks are installed for `BuildRaytracingAccelerationStructureBatched2X` and `CopyRaytracingAccelerationStructure` (0.8 s; the title doesn't resolve the single-build export). - A local counting probe in the hooks (not part of the PR) saw no call in a 150 s run: the title builds no acceleration structure before world load, which this card doesn't reach. - So the prebuild query with a null stream desc, the `BatchedDesc` layout and the copy sizes are still not exercised by a real title here, as in fromthemoonx's check. - Foniass's open points from the re-review stand; none matters with the switch off: - a compacted copy recorded at its source's maximum size; - requests dropped without a log when memory is short; - `SIZES` never pruned; - the `BatchedDesc` layout unverified against the DLL. performance: none by default. Retail title, main 1c8b5514 vs this merge (9e545b7a), 0 device removals and 0 crashes in every run: - 60 s, defaults: 1557 -> 1564 frames, peak commit 16672 -> 18605 MB (within the 16.3-19.0 GB spread of this title's 60 s runs here). - 60 s with `XCL_SPARSE_LAZY=1`: 1562 -> 1565 frames, 17252 -> 17627 MB. - 150 s with `XCL_SPARSE_LAZY=1`, two runs each: - base: 4291 frames / 17027 MB, and 2497 / 34467 MB; - merge: 4079 / 25386 MB, and 2920 / 30832 MB with the probe. - The large peaks come from the title starting to stream after its menus, at a time that varies from run to run, on base as well. In none of these runs did the PR's hooks run. verdict: safe to merge hardware / tool and model: NVIDIA GeForce RTX 3070 8 GB (driver 32.0.16.2140), Intel Core i9-9900K, Windows 11 Pro N 26200 / Claude Code with Claude Opus 5.5 (ran the merge, build, suite, smoke runs and probe, and wrote this check) AI-written; posted without a human check of each point.
bmjask commented 2026-12-02 14:12:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T14:12:05Z.


@Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.

<!-- greyfinch-sync:ivall/xcl:comment:7348152867 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3521#issuecomment-7348152867). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T14:12:05Z. --- @Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3521:upstream-pr/3521'
git switch 'upstream-pr/3521'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3521'
git switch 'upstream-pr/3521'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3521'
git switch 'upstream-pr/3521'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3521'
git switch 'main'
git merge --squash 'upstream-pr/3521'
git switch 'main'
git merge --ff-only 'upstream-pr/3521'
git switch 'main'
git merge 'upstream-pr/3521'
git push origin 'main'
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
xcl-dev/xcl!3521
No description provided.