Skip to content

D3D12.X: hook XboxBvhBuilder builds and ask for every range whole in GPU views - #3662

Open
Kalmarv wants to merge 1 commit into
xcl-dev:mainfrom
Kalmarv:pr/bvh-builder-views
Open

Kalmarv wants to merge 1 commit into
xcl-dev:mainfrom
Kalmarv:pr/bvh-builder-views

Conversation

@Kalmarv

@Kalmarv Kalmarv commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Outer XboxBvhBuilder.dll HLE hooks that ask for every acceleration-structure build and rehydrate range whole in GPU views (d3d12x::view_want::Path::BvhBuild), laying the hook layer needed for the opt-in DXR 1.1 shadow builder follow-up.

On the 16-window GPU-view layout (XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16), XboxBvhBuilder.dll's compute passes reach vertex, index, and transform buffers through addresses inside uploaded geometry descriptions, and read/write destination, source, and scratch through root views that view_want only asks for 64 KiB for. Wrapping BuildRaytracingAccelerationStructureBatched2X and RehydrateRaytracingAccelerationStructureBatched2X on import resolution and GetProcAddress (named or by ordinal) lets XCL ask for every range whole before forwarding. On the default 4-window layout nothing is wrapped.

Part of #1751. Standalone on main (5eaadb54c; no stacked PRs underneath). Note: the solid-character improvement observed earlier in this thread was bisected by @KDenKC to #3517's 16-window layout change, not this PR.

(Why this is 1139 lines and not split further: ~585 lines are the XboxBvhBuilder.dll ABI definitions, range calculation, and extern "system-unwind" hooks, and ~554 lines are their unit tests, kept together because CONTRIBUTING.md requires new code to ship with its tests.)

Related: #2184-#2189 (specifically #2186) and #3521. Concrete differences: this PR hooks XboxBvhBuilder.dll (BuildBatched2X + RehydrateBatched2X) on both import resolution and GetProcAddress without modifying the DLL or title shaders, asks for whole ranges in 16-window GPU views via view_want::Path::BvhBuild (sized by the DLL's own GetRaytracingAccelerationStructurePrebuildInfo), and uses extern "system-unwind" on all hook trampolines. The PERFORM_UPDATE scratch-size cache (UPDATE_SCRATCH) duplicates #3521's inner-hook SIZES logic on purpose because #3521 is not on main; the two can be unified once #3521 lands.

What is in it

  • crates/xcl/src/hle/bvh_builder.rs:
    • XboxBvhBuilder.dll ABI structs (BuildInputs, BuildDesc, BatchedBuildDesc2, GeometryDesc, PrebuildInfo, PostbuildInfoDesc, StreamDesc), safe geometry/postbuild readers, whole-range calculation (ranges_of_build), and extern "system-unwind" passthrough hooks for BuildBatched2X and RehydrateBatched2X, gated on active GPU view windows.
    • Resolves GetRaytracingAccelerationStructurePrebuildInfo directly from the mapped XboxBvhBuilder.dll module when wrapping any export (named or by ordinal), instead of waiting for the title to import it.
    • Caches UpdateScratchDataSizeInBytes on ALLOW_UPDATE builds so a later PERFORM_UPDATE whose prebuild query returns 0 reuses the cached size (in-place or out-of-place), falling back to scratch_size.max(update_scratch_size).max(SCRATCH_GUESS) instead of dropping the scratch range.
    • For ARRAY_OF_POINTERS TLAS builds, translates the GPU-VA pointer array via list_x::cpu_at, reads it under shader::readable, and sorts/coalesces overlapping or contiguous 64-byte D3D12_RAYTRACING_INSTANCE_DESC target ranges before calling view_want::want (to avoid one want call per instance on large TLAS builds).
    • 11 unit tests covering ABI layout, wrap gating, mapped-module prebuild resolution and ordinal imports, geometry readers, R16_TYPELESS (53) index sizing, whole-range bottom-level and PERFORM_UPDATE scratch caching/fallback, ARRAY_OF_POINTERS GPU-VA translation + target coalescing, fallback estimation, and build/rehydrate hook forwarding.
  • crates/xcl/src/hle/d3d12x/view_want.rs: add Path::BvhBuild ("acceleration-structure builds", PATHS = 14).
  • crates/xcl/src/hle/mod.rs, crates/xcl/src/resolver.rs: wire hle::bvh_builder::wrap in resolve_import and get_proc_address for xboxbvhbuilder.dll, passing the mapped module and ImportName.

Tested

  • Hardware & toolchain: NVIDIA GeForce RTX 5070 Ti (driver 610.74), AMD Ryzen 9 9950X, Windows 11 x64, rustc 1.99.0, DXC 1.9.2609.5.
  • cargo build --release -p xcl (commit a65c38b16bb4bb8bd68c7985c73509fe03de6a37): passed, 39 warnings (0 new vs main).
  • .\scripts\test.ps1 (commit a65c38b16bb4bb8bd68c7985c73509fe03de6a37): 2985 passed, 0 failed, 52 ignored across 43 binaries (including all 11 hle::bvh_builder and 5 hle::d3d12x::view_want tests); 24 SKIPPED GPU lines on this adapter (22 no wave64, 2 no heap windows).
  • 240 s live 16-window GPU-views run (XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_VIEW_STATS=1, commit a65c38b16): exit: 0x0, 1754 frames shown, 0 device removals, 0 crashes; hooks installed (XboxBvhBuilder: builds and rehydrates wrapped (asking for their ranges whole in GPU views)), 28 GPU view (2 s) lines logged, 0 acceleration-structure builds lines before 240 s (180 s cold run: exit: 0x0, 1959 frames, 0 removals).
  • Warm-cache 180 s live 16-window GPU-views run (XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_VIEW_STATS=1, from the stacked D3D12.X: opt-in XCL_HW_RT shadow builder #3700 binary with XCL_HW_RT unset, where D3D12.X: hook XboxBvhBuilder builds and ask for every range whole in GPU views #3662's hook is the only active one): exit: 0x0, 1920 frames shown, 0 device removals, 0 crashes; logged 27 GPU view (2 s) lines containing acceleration-structure builds, including 4089 acceleration-structure builds (139392 KB new) at 91.5 s and 1517 acceleration-structure builds (89152 KB new) at 174.9 s.

Regression run
(Clean back-to-back pair; earlier a65c38b16 runs while sibling builds saturated CPU gave 1462 / 1482 / 1035 / 1127 frames — the XboxBvhBuilder hook is not installed on the default 4-window layout.)

xcl-smoke v1
commit: 5eaadb54c14e0fc29597b2a1689d7dbd83491303
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1691 (PresentX 1691)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 16674 MB
xcl-smoke v1
commit: a65c38b16bb4bb8bd68c7985c73509fe03de6a37
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1686 (PresentX 1686)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 17020 MB

Not tested

  • Default 4-window smoke does not exercise the hooks because view_windows() is false there.
  • The 27 acceleration-structure builds XCL_VIEW_STATS lines above were recorded on the stacked D3D12.X: opt-in XCL_HW_RT shadow builder #3700 binary with XCL_HW_RT unset (identical #3662 hook path) once the 16-window shader cache was warm; the earlier 240 s run on a65c38b16 itself did not reach world BVH builds before exit.
  • CopyRaytracingAccelerationStructure is not hooked: a compacted or cloned copy whose destination is in a view window is still only asked for its first 64 KiB.
  • Not tested on AMD or Intel GPUs, or combined with D3D12.X: XboxBvhBuilder builds give their destinations video memory #3521 (XCL_SPARSE_LAZY=1).

AI use

  • Antigravity (Gemini 4 Neon): rebased standalone onto main, implemented the 3 review fixes and unit tests, ran the build, full test suite, smoke runs, and 180 s 16-window run, and drafted the PR description.
  • Claude Code (Claude Opus 5.5): authored the original range-request logic and reviewed the fixes (including list_x::cpu_at GPU-VA translation and target coalescing) and PR description.

@github-actions github-actions Bot added area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH area:memory Virtual/physical memory, arenas, VRAM budget, UMA area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 area:tests Unit, integration, e2e tests, or testtitle gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks) labels Dec 2, 2026
@KDenKC

KDenKC commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@Kalmarv a first in-world result with #3662 on the RTX 5090, and it's a big one for the picture, though we don't know yet which part of it does it.

What ran. Our tree (our window/alias fixes and diagnostics) + #3662 + #3656 (with #3327 under it), XCL_NATIVE_MESH=0 (so #3656's native path was off; its global shader changes were in), XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16, XCL_SKIP_CS=95cc13288a27a96e, a fully prepared shader cache plus a warm-up, one ~530 s run in the first interior scene.

Picture: clearly better than anything we've had in that scene. By eye and in the saved frames:

  • the window is lit: sky, the building, the watch tower, and the yard with its tables and several people sitting and standing in it;
  • the characters are solid and lit (hair, shoulders, jacket with rim light) instead of the see-through "glass" look every earlier build had;
  • what's still wrong is now localised: flat-coloured rectangles (missing texture tiles) over parts of the main character's head, neck and back, one flat tile on the wall, a part of the room's right side still unrendered, and frequent textures flickering in and out.
    Our own estimate: roughly 70 % of the scene correct, against far less before.

Performance: degraded. 4.6 fps in the world (stalls 7, longest 26 s) vs 6.8–7.2 fps for the #3656 A/B arms on the same save; peak commit 40,946 MB and peak local VRAM 20,376 MB (vs 39,228 / 19,217 MB for #3327 alone), no device removal or crash.

Ray tracing: our GPU counter on the node test still reads 0 node tests in this run. But with #3662 the top-level headers the walk reads moved (to 0x145db10000 / 0x145f8cf100 / 0x1460868d00 in this run) and their GPU-side roots now hold what looks like real node data, where before they read empty. Why the walk still tests no node is the next thing we're checking (which backend the ray programs take, which view they read the root through).

We don't know yet why the picture improved. Candidates: #3662's 16-window memory-layout commits (trailing view windows for overflow MEM_GRAPHICS reservations, 4 runtime sparse windows: e.g. character vertex/skinning data that was partly uncovered before), its null-window raw UAV fix, or #3656's global signature/optimizer changes. A run of our tree + #3662 alone is next and will split those; we'll post which one it is.

From here we'll focus on tools that find and pin down the remaining small artifacts (the tiles and flicker) automatically. The speed side we'd happily leave to you or a later step.

AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.

@KDenKC

KDenKC commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@Kalmarv follow-up to the result above, as promised: the solid characters come from #3662's stack, not #3656. Our tree + #3662 alone (no #3656 or #3327), same env, same scene: the main character and the people in the yard are solid and lit, the window is lit, with the same flat missing-texture tiles on the character as the combined run. One more run will split #3662's memory-layout commits (the trailing view windows for overflow MEM_GRAPHICS reservations and the 4 runtime sparse windows) from the builder hook and the null raw-UAV fix; we'll add which one it is.

On the ray-tracing side, with #3662 the top-level headers on the GPU now hold built structures (one walk finds ~915,000 nodes in 787 bottom levels), and the title's ray programs do start (about 540 million lanes over a run), but they leave before their first node test: in the program we read, every lane exits at an early check on a per-pixel 32-bit classification word read from a 2D texture before any intersect instruction. We're tracing which pass writes that word next.

AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.

@KDenKC

KDenKC commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@Kalmarv @CharlyRien the split run answers it: the solid characters come from the two memory-layout commits under #3662, not the builder hook or the null raw-UAV fix. Our tree + only #3517's 16-window layout change (4 runtime sparse windows) and #3653's trailing view windows for overflow MEM_GRAPHICS reservations, same env and scene: the main character and the people in the yard are solid and lit, exactly as with the full #3662 stack (and see-through on every build without them). So #3517 + #3653 on the 16-window layout fix the "glass" characters on our RTX 5090 by themselves. The remaining flat texture tiles on the character are the same with and without the rest of #3662. In that run too, the ray programs start but do no node test.

AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.

@Foniass

Foniass commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Review (head a69189b, diff read, not a merge-check):

  • Size and stack. +2233/-93 in 6 commits, but only a69189b89 (+866/-1, about 350 lines tests) belongs to this PR. By reading, it applies to current main without conflicts and uses nothing from the stacked commits: hle/bvh_builder.rs only calls view_want, gpu::bvh::prebuild_size/HEADER_BYTES and gpu::shader::readable, all on main; the inner d3d12x::bvh_builder hook is only mentioned in doc comments. The stacked copies of Memory: the 16-window layout keeps 4 runtime sparse windows #3517, D3D12.X: write MEM_NULL_LOAD/MEM_NULL_STORE raw UAVs after fill_nulls in shared_heap #3349, D3D12.X: XboxBvhBuilder builds give their destinations video memory #3521 and D3D12.X: a ray-tracing build's scratch gets window tiles of its own #3522 are rebased and do not match those PRs' heads (ce078501 vs 0b4283d1, e3ca17dd vs 5dc64ea7, 23d5cafd vs 2e2d9320, f0c6ae41 vs 5abd576b); with merge commits, each change would land in main twice. D3D12.X: write MEM_NULL_LOAD/MEM_NULL_STORE raw UAVs after fill_nulls in shared_heap #3349 (null raw UAVs in shared_heap) is unrelated to BVH builds. Rebase a69189b89 alone onto main; if it must be smaller: (1) the ABI structs, ranges_of_build and their tests; (2) the hooks and the resolver.rs / view_want::Path::BvhBuild wiring. The two Memory: cover overflow MEM_GRAPHICS reservations in trailing view windows #3653 commits it carries are identical to Memory: cover overflow MEM_GRAPHICS reservations in trailing view windows #3653's.
  • An update's scratch is not asked for when the query returns 0. hle/bvh_builder.rs ~395-401 sizes a PERFORM_UPDATE build's scratch with UpdateScratchDataSizeInBytes from the prebuild query on the update's own inputs; when that is 0, push_range (~336) drops the range and only the 64 KiB root-view ask remains. The inner hook documents that this query "may give none" (d3d12x/bvh_builder.rs ~53) and keeps the size from the earlier ALLOW_UPDATE build, falling back to the larger scratch size. Reusing that logic (and its SIZES map) would fix this and avoid a second copy of the ABI and sizing code.
  • The prebuild query depends on the title importing it. REAL_PREBUILD_INFO (~236-240) is set only when the title resolves GetRaytracingAccelerationStructurePrebuildInfo itself; otherwise scratch is asked for at SCRATCH_GUESS (64 KiB), no better than before. The inner hook looks the export up in the mapped module directly (d3d12x/bvh_builder.rs ~81-82); the outer hook could do the same.
  • Instance descriptions behind pointers are not asked for. For a top-level build with ARRAY_OF_POINTERS (~403-404) only the 8-byte pointer array is asked for, not the 64-byte instance descriptions read through it, so in a GPU view they can still read zeros.
  • No runtime evidence for the hook. The commit says every other tile "read zeros and dropped writes" on the 16-window layout, but the 60 s 16-window run reached no acceleration-structure build, and the default-layout smoke runs install no hook (view_windows() is false). The unit tests check range arithmetic only (under test view_want::want returns early), so nothing shows the tiles get mapped or what that costs per build (sparse::map_mirror walks the ranges' tiles on the recording thread).
  • Nothing is translated. The hook forwards to the title's own XboxBvhBuilder.dll, which keeps writing its console-format BVH for XCL's traversal. No D3D12 acceleration structure is produced, so nothing here connects to Recompiler: emit DXR 1.1 RayQuery and acceleration-structure SRVs #3659's RayQuery SRVs yet (no shared files, no overlap).

Fine (by reading): the ABI layouts (BuildDesc 0x30, BatchedBuildDesc2 0x50, GeometryDesc 0x38, triangle and AABB payloads, R16 index formats 53..=59) match their D3D12 counterparts; with XCL_SPARSE_LAZY=1 the calls go outer hook, inner hook, DLL; wrapping is gated on view windows, so the default 4-window layout is unchanged, and #3653's trailing reservations return None there.

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

@Decodere

Decodere commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Diff review (head a69189b89, read-only code review — not a test report):

Clean ABI verification for XboxBvhBuilder.dll and safe gating on view_windows() (crates/xcl/src/hle/bvh_builder.rs:203-221) so the default 4-window layout is unchanged. Reading the full diff (+2233/-93 across 16 files) turned up 3 concrete issues across both the 5-PR stack and the new hook itself:

  1. 5-PR stack carries rebased copies of unmerged PRs and inherits their open bugs:
    Only the top commit (a69189b89, +866/-1 across 4 files) belongs to this PR, and it depends only on symbols already on main (view_want, gpu::bvh, gpu::shader::readable). The 5 commits underneath carry copies of #3517, #3653, #3349, #3521, and #3522 (4 of 5 with different commit SHAs from those PRs' open heads), inheriting:

    • #3517's with_switch_fallback window-4 cutoff (crates/xcl/src/gpu/uma.rs:48, :59; crates/xcl/src/hle/d3d12x/real.rs:5178-5191; crates/xcl/src/gpu/recomp/pso.rs:147-161; crates/xcl/src/hle/d3d12x/bind.rs:5316-5318): moving 16-window coherent memory to window 4 places it past MAX_WINDOWS = 4 root UAVs (0..3) whenever a pipeline takes #156 switch fallback.
    • #3653's unrelated dead code (crates/xcl/src/hle/d3d12x/title_list.rs:292-298, :1135-1161): unused pub fn active_backing + unit test.
    • #3522's self.own lifecycle/recycle hazards in sparse.rs (un-cleared self.own on commit/decommit and same-submit yield_own -> self.parked -> new_mirror reuse before in-flight GPU completion).
  2. Three range-sizing / hook gaps in crates/xcl/src/hle/bvh_builder.rs:

    • Update scratch dropped when prebuild returns 0 (bvh_builder.rs:335-339, :395-401): for BUILD_FLAG_PERFORM_UPDATE, ranges_of_build passes sizes.update_scratch_data_size_in_bytes directly to push_range, dropping the scratch range whenever querying GetRaytracingAccelerationStructurePrebuildInfo with PERFORM_UPDATE returns 0 (whereas crates/xcl/src/hle/d3d12x/bvh_builder.rs:123-129 retains UpdateScratchDataSizeInBytes from the original ALLOW_UPDATE build and falls back to ScratchDataSizeInBytes.max(UpdateScratchDataSizeInBytes)).
    • REAL_PREBUILD_INFO depends on the title resolving that export first (bvh_builder.rs:236-241, :333, :344-366): REAL_PREBUILD_INFO is only captured if the title imports or calls GetProcAddress on SYM_PREBUILD_INFO before building; otherwise scratch falls back to SCRATCH_GUESS = 64 KiB. Looking up the export directly from the mapped module (as in d3d12x/bvh_builder.rs:81-83) and resolving ordinal imports in resolver.rs:327-329, :444-446 avoids this.
    • Indirect ARRAY_OF_POINTERS TLAS instance descriptions omitted (bvh_builder.rs:402-404): asks only for the 8 * num_descs pointer table, not the pointed-to 64-byte D3D12_RAYTRACING_INSTANCE_DESC targets.
  3. Performance regression & isolation:
    RTX 5090 testing in this thread measured degraded in-world throughput (4.6 fps and a 26 s stall vs 6.8–7.2 fps) and bisected the visual improvement solely to the #3517 + #3653 memory-layout commits rather than this hook. Rebasing a69189b89 standalone onto main (and unifying its prebuild/range sizing with d3d12x::bvh_builder once #3521/#3522 settle) will allow clean isolated measurement of the hook itself.

AI use: Antigravity (Gemini 4 Neon) audited the full diff against main and drafted this review.

@KDenKC

KDenKC commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

A narrower answer than in my last comment: #3517 alone is enough. Our tree + only @CharlyRien's #3517 (the 16-window layout keeping 4 runtime sparse windows), without #3653 or the rest of #3662, same env and scene: the characters are solid and lit, with the same flat texture tiles. So the "glass" characters come from what #3517 changes in the 16-window layout; #3653's overflow coverage isn't needed for that (it may still matter elsewhere). Ray programs: as before, they start and do no node test.

AI use: an agent swarm: Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.2-Sol, Gemini 4 Neon and Gemini 4 Hydrogen.

@Foniass

Foniass commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: 1c8b551
head: a69189b
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2936 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 by one reviewer at this same head; the review is at #3662 (comment) and its findings stand. Most serious: only the top commit is its own (it carries rebased copies of 4 other PRs), and an update build's scratch is dropped when the size query returns 0.
performance: 60 s smoke of a retail title, main 1c8b551 vs this merge (a69189b): 1652 -> 1684 frames shown (101 %; last presents per 2 s: 60 60 60), peak commit 18228 -> 18899 MB, 0 device removals, 0 crashes.
verdict: not yet: only the top commit is its own (it carries rebased copies of 4 other PRs), and an update build's scratch is dropped when the size query returns 0 (see the review)
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.

…GPU views

Add outer XboxBvhBuilder.dll HLE hooks (BuildRaytracingAccelerationStructureBatched2X and RehydrateRaytracingAccelerationStructureBatched2X, extern "system-unwind") that ask view_want (Path::BvhBuild) for every range a build or rehydrate names whole before forwarding to the DLL.

The builder's compute programs reach vertex and index buffers through addresses inside uploaded geometry descriptions and reach destination, source, and scratch through root views, which view_want only asks for 64 KiB from their base address. On the 16-window GPU-view layout, tiles past that first 64 KiB stay unmapped until requested. Asking for each item's result, source, scratch, instance descriptions, per-geometry vertices/indices/transforms/AABBs (handling R16_TYPELESS=53 as 2 bytes), and postbuild destinations sized via GetRaytracingAccelerationStructurePrebuildInfo closes that gap:

- Resolve GetRaytracingAccelerationStructurePrebuildInfo directly from the mapped XboxBvhBuilder.dll module when wrapping any export (including ordinal imports) instead of waiting for the title to import it.
- Cache UpdateScratchDataSizeInBytes on ALLOW_UPDATE builds so a later PERFORM_UPDATE whose prebuild query returns 0 reuses the cached size (or falls back to scratch_size.max(update_scratch_size).max(SCRATCH_GUESS)) instead of dropping the scratch range.
- For ARRAY_OF_POINTERS TLAS builds, translate the GPU-VA pointer table via list_x::cpu_at, read it under shader::readable, and request coalesced 64-byte D3D12_RAYTRACING_INSTANCE_DESC target ranges alongside the pointer array.

Wrapping is gated on Uma view windows existing, so default 4-window runs are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Antigravity (Gemini 4 Neon)
@Kalmarv
Kalmarv force-pushed the pr/bvh-builder-views branch from a69189b to a65c38b Compare December 2, 2026 15:05
@github-actions github-actions Bot added needs-pr-check Failing the PR description check (CONTRIBUTING.md) and removed area:docs-ci Documentation, scripts, workflows, repo governance area:memory Virtual/physical memory, arenas, VRAM budget, UMA area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 area:tests Unit, integration, e2e tests, or testtitle labels Dec 2, 2026
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Updated in a65c38b16 (standalone on main 5eaadb54c — all 5 stacked commits from #3517/#3653/#3349/#3521/#3522 dropped) and addressed every review point:

  • @Foniass (PERFORM_UPDATE scratch size = 0): cached UpdateScratchDataSizeInBytes on ALLOW_UPDATE builds in UPDATE_SCRATCH (crates/xcl/src/hle/bvh_builder.rs, resolve_scratch_bytes) so a later PERFORM_UPDATE whose prebuild query returns 0 reuses the cached size (in-place or out-of-place), falling back to scratch_size.max(update_scratch_size).max(SCRATCH_GUESS) instead of dropping the scratch range; covered by perform_update_uses_cached_allow_update_scratch_and_falls_back_when_zero.
  • @Foniass (prebuild query lookup & ordinal imports): bvh_builder::wrap now takes the mapped XboxBvhBuilder.dll module and ImportName (crates/xcl/src/hle/bvh_builder.rs, record_prebuild_from_module / wrap_with_module; wired in crates/xcl/src/resolver.rs), resolving GetRaytracingAccelerationStructurePrebuildInfo directly from the mapped DLL when any export is wrapped and matching ordinal imports as well as names; covered by wrap_resolves_prebuild_info_from_mapped_module_and_handles_ordinals.
  • @Foniass (TLAS ARRAY_OF_POINTERS): ranges_of_build now translates inp.descs through list_x::cpu_at, reads the pointer array under shader::readable, and sorts/coalesces contiguous or overlapping 64-byte D3D12_RAYTRACING_INSTANCE_DESC target ranges before calling view_want::want; covered by a_top_level_build_names_its_instance_descriptions (including a non-identity GPU VA -> CPU VA mapping).
  • @Decodere (diff size & #3521 relation): rebased standalone onto main (5eaadb54c) so the PR diff is only the 4 files / +1139 -1 lines of this change (~585 prod + ~554 unit tests), and documented the concrete difference vs #3521 (and why UPDATE_SCRATCH temporarily mirrors #3521's SIZES until #3521 lands) in the PR body.
  • @KDenKC (bisect): thanks for bisecting the solid-character improvement to #3517's 16-window layout — updated the PR body to note that and drop the earlier attribution.

PR body updated with fresh scripts/test.ps1 counts, default smoke blocks, and 16-window live run results.

@github-actions github-actions Bot removed the needs-pr-check Failing the PR description check (CONTRIBUTING.md) label Dec 2, 2026
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up runtime evidence (@Foniass): once the 16-window shader cache warmed up, a 180 s XCL_HEAP_WINDOWS=1 XCL_UMA_WINDOWS=16 XCL_VIEW_STATS=1 run on the stacked #3700 binary with XCL_HW_RT unset (where #3662's hook is the only active one) completed with exit: 0x0, 1920 frames, 0 device removals, and logged 27 GPU view (2 s) lines containing acceleration-structure builds (peaking at 4089 acceleration-structure builds (139392 KB new) at 91.5 s and 1517 acceleration-structure builds (89152 KB new) at 174.9 s). Added to Tested / Not tested in the PR body.

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of a65c38b1: 4 finding(s) (1 critical, 1 high, 2 medium), most severe first.

  1. Critical crates/xcl/src/hle/bvh_builder.rs:492: The CPU view of the top-level pointer array is read with raw read_unaligned after a shader::readable check, a check-then-use race on title memory that can be decommitted concurrently. (inline)
  2. High crates/xcl/src/hle/bvh_builder.rs:487: The ARRAY_OF_POINTERS pointer array is translated with cpu_at(inp.descs) (base address only) and then read as one contiguous n*8-byte CPU run, but when the array crosses a 64 KiB GPU-view tile the next tile's CPU page needn't follow .... (inline)
  3. Medium crates/xcl/src/hle/bvh_builder.rs:208: UPDATE_SCRATCH grows without bound and outlives the structures it describes: every ALLOW_UPDATE build inserts its dest VA, and an entry is removed only when a later non-update build hits the same dest. (inline)
  4. Medium crates/xcl/src/hle/bvh_builder.rs:517: Not certain about this one, because it depends on the builder reading bottom-level headers during the top-level pass: top-level builds ask only for the instance descriptions, not for the bottom levels each instance's `AccelerationStructu.... (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.

let ptrs = cpu as *const u64;
let mut targets: Vec<u64> = Vec::with_capacity(n.min(1024));
for i in 0..n {
let target = ptrs.add(i).read_unaligned();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical: The CPU view of the top-level pointer array is read with raw read_unaligned after a shader::readable check, a check-then-use race on title memory that can be decommitted concurrently. bvh_want::read_title uses view_want::cpu_run plus dstorage::read_own (a kernel copy that can't fault) for exactly this. If the title's streaming thread decommits or releases the page holding the instance pointer table between readable() and the loop, the hook takes an access violation inside an extern "system-unwind" function on the title's render thread and the process crashes. Reading through read_own would make it safe.

push_range(out, Use::Instances, inp.descs, u64::from(inp.num_descs).saturating_mul(8));
if n > 0 && inp.descs != 0 {
if let Some(bytes) = n.checked_mul(std::mem::size_of::<u64>()) {
let cpu = cpu_at(inp.descs);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High: The ARRAY_OF_POINTERS pointer array is translated with cpu_at(inp.descs) (base address only) and then read as one contiguous n*8-byte CPU run, but when the array crosses a 64 KiB GPU-view tile the next tile's CPU page needn't follow the first, which view_want::cpu_run exists to detect. For a top-level build with ~3000 instances whose 24 KB pointer array starts 8 KB before a tile boundary, with tiles mapped apart (queue page mappings or kernelx mirrors), the entries past the boundary are read from whatever follows the first CPU page. The wrong instance-desc ranges are asked for and the real ones are never mapped, so the builder reads zeros and those instances drop out of the top level. Translating per tile (or using cpu_run) would fix it.

static REAL_PREBUILD_INFO: AtomicUsize = AtomicUsize::new(0);
/// Destination AS VA -> cached `UpdateScratchDataSizeInBytes` from an `ALLOW_UPDATE` build,
/// used when a later `PERFORM_UPDATE` prebuild query returns 0.
static UPDATE_SCRATCH: Mutex<Option<HashMap<u64, u64>>> = Mutex::new(None);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium: UPDATE_SCRATCH grows without bound and outlives the structures it describes: every ALLOW_UPDATE build inserts its dest VA, and an entry is removed only when a later non-update build hits the same dest. Besides growing for the whole session (the PR's own log shows ~4000 builds every 2 s, and streaming titles use new VAs), when a dest VA is freed and reused for a different, larger ALLOW_UPDATE structure whose PERFORM_UPDATE prebuild returns 0, the stale smaller size is used and the update scratch past it is never asked for. Querying prebuild with flags & !BUILD_FLAG_PERFORM_UPDATE (the DXR-legal form) would give the size directly and remove the cache.

}
}
} else {
push_range(out, Use::Instances, inp.descs, u64::from(inp.num_descs).saturating_mul(INSTANCE_DESC_BYTES));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium: Not certain about this one, because it depends on the builder reading bottom-level headers during the top-level pass: top-level builds ask only for the instance descriptions, not for the bottom levels each instance's AccelerationStructure field names. If a bottom level was built frames earlier and its view tiles have since been dropped or not asked again this generation, the top-level build reads zero bounds or headers for that instance, which ends up degenerate or missing. Asking for each referenced bottom level's range (at least its header) would cover it.

@bmjask

bmjask commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants