Skip to content

XDXR builder: radix-tree BVH, about half the traversal steps (D3D-410, depends on #3315) - #4098

Closed
NiiRoZz wants to merge 9 commits into
ItsNotRexed:mainfrom
NiiRoZz:d3d-410-radix-bvh-on-3315
Closed

NiiRoZz wants to merge 9 commits into
ItsNotRexed:mainfrom
NiiRoZz:d3d-410-radix-bvh-on-3315

Conversation

@NiiRoZz

@NiiRoZz NiiRoZz commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: D3D-410 (claim), found by @DaniSBR1 (finding).

Depends on #3315 (BOX16 nodes and TRI1 pairing, @zneel). This branch is built on top of it, so until #3315 merges the diff here also shows its commits; only the last commit is this PR. Draft until then.

What and why

The GPU BVH builder (runtime/src/xdxr_build.comp) grouped four consecutive Morton-sorted elements per node, level by level. Those groups ignore where the Morton prefix changes, so sibling boxes overlap and a ray takes about twice the traversal steps of a radix tree over the same order.

What it does now:

  1. Binary radix tree over the sorted keys (Karras 2012; equal keys told apart by sorted position), one thread per inner node.
  2. Collapse to 4-wide: the inner nodes at an even depth become the box nodes (BOX32, or BOX16 with MINIMIZE_MEMORY). Each takes its children's children, so it has 2 to 4. They are numbered in sorted order by a tile count, one scan and a per-tile scan, so the root is node 0. This collapse needs no top-down pass. A CPU model put it within 2% of a greedy surface-area collapse (35.7 against 35.1 steps per ray on 5,000 random triangles).
  3. TRI1 pairing (XDXR builder: BOX16 nodes for MINIMIZE_MEMORY BLASes, and TRI1 pairing #3315) pairs triangle children of the same node, as before. The pass records each element's tree pointer, so a paired sibling finds its TRI1 slot.
  4. Boxes bottom-up in one dispatch: each element writes its box into its parent's slot (float or BOX16 halves, by the parent's pointer type) and merges it into the parent's accumulator with atomicMin/atomicMax on order-preserving uints. The last child to arrive reads the accumulator with atomics and carries on. Invocations meet only through atomics. The arrival counter's atomicAdd has acquire-release semantics at device scope (GL_KHR_memory_scope_semantics; still the GLSL450 memory model, no new feature). There is no memoryBarrierBuffer: the pass is divergent, and SPIRV-Cross before MSL 3.2 lowers a memory barrier to threadgroup_barrier, which every thread must reach.
  5. Refit (PERFORM_UPDATE) reuses the same pass through the parent table, after clearing the accumulators. It copies a separate source by its header size, so a compacted source works too.

Sizes. The node count now depends on the keys. XdxrLayout reserves the most a tree can have, (3N − 2) / 4 nodes (proof in xdxr_build.h). The header's totalSizeIn64BNodes counts the nodes written, plus the BOX16 spare unit, which now follows the last node written. So COMPACTED_SIZE is the real size and compaction gives memory back.

tools/xdxr_bvh.py check-build now prints steps per ray: one per node or triangle tested, the work of one image_bvh_intersect_ray.

Results

Steps per ray, from check-build over 1,000 random rays per case. Before is #3315's builder.

Case Before After
blas_three_sort_tiles (5,000 random triangles) 42.0 23.0
blas_box16_sort_tiles (the same, BOX16) 43.9 23.7
blas_paired_sort_tiles (7,200-triangle grid, paired) 37.6 19.5
blas_random (1,000 triangles) 24.1 16.0
blas_refit_in_place (3,000 triangles, moved) 74.8 55.5
tlas 26.3 18.1

The costs:

  • Build and refit time, from vk_xdxr_build_test <dir> <n> (best of 3):

    GPU Triangles Build (ms) Refit (ms)
    RTX 5090 1M 5.50 → 5.99 4.12 → 4.28
    Radeon iGPU (gfx1036) 1M 133 → 180 41.8 → 62.2
  • Memory: about one node per two elements instead of one per three. A compacted 1,000-triangle BLAS is 137,856 bytes instead of 113,536. Prebuild sizes are about 50% larger and scratch about 75% larger.

  • Fewer pairs: 2,208 of 3,600 possible pairs form on the paired grid, against 2,625 before. A radix-tree node often has an inner node among its children, and only triangle children pair.

Open points:

  • Tree depth: the tree can be deeper than log4 N, up to about 32 for clustered geometry. If a translated traversal shader relies on a fixed-size stack, this is worth checking.
  • MoltenVK: not run there. The barrier change above is meant to keep it safe.
  • Coverage: no test refits from a compacted source.

Tested

  • Windows 11, RTX 5090 (NVIDIA driver) and Radeon gfx1036 iGPU (AMD driver), each selected with VK_LOADER_DRIVERS_SELECT:
    • ctest -R xdxr: xdxr_descs, xdxr_build, xdxr_build_check, d3d12_xdxr_rt and d3d12_xdxr_rt_check pass on both GPUs. Every case matches brute force, BOX16 and paired cases included.
    • LEONIDA_VK_VALIDATION=1 vk_xdxr_build_test (validation and synchronization validation): no messages on either GPU.
  • python -I tests/test_xdxr_bvh.py: 37 tests OK.
  • spirv-val --target-env vulkan1.2 on the shader. xdxr_build.inc regenerated with glslc --target-env=vulkan1.2 -O -mfmt=c.
  • An independent review pass (AI) checked the Karras search, the node bound, the host/shader scratch layout, 32-bit offsets, refit and the N = 0/1 cases. Its one finding (the barrier on MoltenVK) is fixed here.

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (No translator change.)

AI-assisted.

🤖 Generated with Claude Code

zneel and others added 8 commits November 22, 2026 23:29
A bottom-level BuildRaytracingAccelerationStructure with MINIMIZE_MEMORY now
writes BOX16 inner nodes (64 bytes, half boxes) instead of BOX32 (128 bytes):
the same tree, about a fifth smaller. Prebuild info, the build and its refits
take the choice from the same flags (xdxr_box16), so the sizes stay exact.
Top-level builds keep BOX32 (world space: a half's step is 2 m at 2 km).

Each child box is rounded outward from the exact box kept in scratch, in
integer code (packHalf2x16's rounding is implementation-defined; AMD rounds
toward zero). Past the half range a bound goes to +-inf outward and +-65504
inward, so empty slots stay empty; below the smallest normal half it goes to
0 or +-2^-14, never a denormal a flushing decoder would shrink.
tools/xdxr_bvh.py half_round gets the same denormal rule, and check-build now
compares every BOX16 word bit for bit with encode_box16 of the exact box of
the triangles under it.

Tests: five blas_box16_* cases in vk_xdxr_build_test (radix and small sort,
an inactive triangle, values past 65504 and below 2^-14, a refit), and a
MINIMIZE_MEMORY BLAS plus its in-place update through the D3D12 API in
d3d12_xdxr_rt_test (prebuild and postbuild sizes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
glslc --target-env=vulkan1.2 -O -mfmt=c xdxr_build.comp -o xdxr_build.inc
(Vulkan SDK 1.4.363.0's glslc; it reproduces the previous blob byte for byte
from the previous .comp).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A bottom-level build without ALLOW_UPDATE now pairs triangles, as the
console builder does in its offline BLASes. The pass that writes the nodes
above the leaves pairs a triangle with a later sibling (among that node's at
most four children) that shares an edge in the opposite direction (the same
vertex bits), from the same geometry, both active. The first triangle is
rotated to put the shared edge in slots 1 -> 2, the sibling's third vertex
goes in slot 3, its primitive in PrimitiveIndex2, and each node type's remap
byte returns D3D12's barycentrics for its own vertex order.

The node keeps one child per triangle with its own box, so the tree, the
layout and the sizes do not change; the TRI1 child points at the first
leaf and the sibling's leaf is left unused. Pairs never cross nodes: one
thread owns each rewritten leaf and each parent-table entry. A refit
rewrites the leaves one triangle each, so the layer does not pair builds
with ALLOW_UPDATE (xdxr_pair), and record_blas ignores `pair` for updates.

check-build now compares barycentrics as well as hits, and checks a case's
"pairs" field: at least one TRI1 node, or none. New cases: paired grids
(BOX32 and BOX16), a transform, a mixed scene, the radix path, and two that
must not pair (pairs split across geometries, edges shared in the same
direction), plus a D3D12 BLAS without ALLOW_UPDATE. Mutating the geometry or
the direction rule, or the remap byte, fails check-build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
glslc --target-env=vulkan1.2 -O -mfmt=c xdxr_build.comp -o xdxr_build.inc

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…omments)

- GetRaytracingAccelerationStructurePrebuildInfo's KHR path passes
  LOW_MEMORY for MINIMIZE_MEMORY, as the build now does (Vulkan sizes a build
  with identical flags).
- check-build enforces a case's "box16" field (only BOX16 or only BOX32
  inner nodes), so a BOX16 case that came out BOX32 cannot pass the bit
  check vacuously; the vk and D3D12 BOX16 cases set it.
- Comments: half_round's inward overflow, the remap byte's positions, what
  the half-rounding table test covers, and what an update that breaks
  D3D12's flag or ALLOW_UPDATE rules would do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…, rotation coverage, docs)

- xdxr_check refuses PERFORM_UPDATE without ALLOW_UPDATE (D3D12 requires
  it): a structure built without it may be paired, and a refit would leave
  its TRI1 children reading wrong vertices.
- blas_paired_rotations: a grid whose triangles start at varied vertices,
  so pairs use all nine (TRI0, TRI1) rotations; check-build asserts it
  ("all_rotations"). Before, the sibling rotation kd = 1 never occurred.
- BOX32 cases now say "box16": false, so a stray BOX16 is caught too.
- docs/bvh.md cites the one traced BOX16-related datum (docs/xdxr.md: a
  bottom-level path needing MINIMIZE_MEMORY and a stream value above 10),
  notes that world-space BLASes only get looser boxes; README says pairing
  saves no memory yet and the BOX16 switch is assumed; comments rewrapped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tes per box node)

tools/rdna2spirv.py's image_bvh_intersect_ray loads a box node's BOX32
bounds (112 bytes) before it selects BOX16 or BOX32, and the root is the
last node, so a BOX16 root was read 48 bytes past the structure. A BOX16
layout now ends with one zeroed 64-byte unit (MODE_INIT clears it); the
D3D12 test's BOX16 BLAS is 39,040 bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ldren (D3D-410)

The GPU builder grouped four consecutive Morton-sorted elements per node,
level by level. Those groups ignore where the Morton prefix changes, so
sibling boxes overlapped and a ray took about twice the traversal steps.

It now builds a binary radix tree over the same sorted keys (Karras 2012,
ties broken by sorted position) and keeps the inner nodes at an even depth
as the BOX32/BOX16 nodes, each taking its children's children (2 to 4),
numbered in sorted order by a scan (root = node 0). Boxes are filled by one
bottom-up pass: each element writes its slot box and merges it into its
parent's accumulator with atomics; the last child to arrive carries on.
The arrival counter's atomicAdd has acquire-release semantics instead of a
memoryBarrierBuffer, since the pass is divergent and SPIRV-Cross before
MSL 3.2 lowers memory barriers to threadgroup_barrier. Refit reuses the pass
through the parent table.

TRI1 pairing (ItsNotRexed#3315) pairs triangle children of one node; the build records
each element's tree pointer so a paired sibling finds its TRI1 slot. The
node count depends on the keys: the layout reserves (3N - 2) / 4 nodes, the
header counts the nodes written (plus the BOX16 spare unit after the last
one), so compaction gives the rest back. Refit copies a source by its
header size. check-build reports traversal steps per ray.

Steps per ray: 5,000 random triangles 42.0 -> 23.0, BOX16 43.9 -> 23.7,
paired 7,200-triangle grid 37.6 -> 19.5. Build 1M triangles: RTX 5090
5.50 -> 5.99 ms, Radeon gfx1036 iGPU 133 -> 180 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tunczzz

tunczzz commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested ba288b5b on an NVIDIA GeForce RTX 5070 Ti (Blackwell, driver 616.56), Windows 11 10.0.26300, MSVC 19.44 Build Tools, Ninja RelWithDebInfo, Vulkan headers fetched, glslangValidator 16.2: pass. This is the first NVIDIA run here, and the bottom-up pass leans on device-scope atomics, so it seemed worth one.

  • ctest: 153/153 passed. Only the game-data tests are skipped, plus vk_sync_validation (no validation layer installed), d3d12_rgb9e5_rtv, d3d12_first_light and the d3d12_m5_mesh* set.
  • xdxr_build_check: all cases match, 0 validation errors, and 0 of 1000 rays differ in every case. Steps per ray: blas_transform 4.6, blas_two_geometries 4.3, blas_three_sort_tiles 23.0 (200 rays), tlas 18.1, tlas_refit 16.3, tlas_refit_clone 15.8, blas_refit_into_other 8.8.
  • d3d12_xdxr_rt_check: all cases match, 0 of 1000 rays differ. d3d12_blas 12.3 steps per ray, d3d12_blas_box16 15.4, d3d12_blas_paired 12.5 (61 TRI1), d3d12_blas_compacted 16.8, d3d12_blas_update 15.9, d3d12_tlas 15.1. d3d12_xdxr_rt: passed.

Main aa2988cc's checks don't print steps per ray, so I have no before/after step counts from this GPU, only that correctness holds. No game files. AI-assisted (Claude Code).

@troythedecoyx

Copy link
Copy Markdown
Contributor

Tested ba288b5b merged onto main 03b09a08 on an RTX 4060 Ti (Ada), NVIDIA 621.24, Windows 11, MSVC 2022, RelWithDebInfo: pass.

  • ctest 154/154; the five xdxr tests pass (xdxr_build_check 65.6 s, d3d12_xdxr_rt_check 14.7 s).
  • All 28 vk_xdxr_build_test cases and all 7 d3d12_xdxr_rt_test cases: 0 validation errors, 0 rays differ.
  • The steps per ray match the PR's numbers exactly on this card: blas_three_sort_tiles 23.0, blas_box16_sort_tiles 23.7 and blas_paired_sort_tiles 19.5. Others: blas_random 16.0, tlas 18.1, blas_refit_in_place 55.5, blas_box16_refit_in_place 57.7.
  • run_gpu_tests.py matches main in both modes: 164/210 passed, 46 skipped (LEONIDA_W64_EMULATE=0); 195/210 passed, 15 skipped (=1).
  • The semantic suite shows only main's existing failures, with the same names.

AI-assisted (Claude Code); I ran the tests and read the output.

README: main's ray-tracing rows with ItsNotRexed#3315's facts (TRI1 pairing and BOX16 nodes are in).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@lines9686-rgb

Copy link
Copy Markdown
Contributor

Tested 13e65ff (already on main 3faac55) on Windows 11 (26200), RTX 3060 Ti (NVIDIA 610.88), MSVC, Ninja RelWithDebInfo: pass. ctest 177/177, the same list and the same 10 skips as main 3faac55 on this machine (the six package-gated ones incl. bvh_builder, gameinput disabled, vk_sync_validation, d3d12_rgb9e5_rtv, d3d12_first_light). xdxr_build_check and d3d12_xdxr_rt_check print "all cases match" on the branch and on main; on the branch xdxr_build also builds the new BOX16 cases (blas_box16_random, _sort_tiles, _two_geometries, _extremes, blas_paired_grid). Node counts in xdxr_build's log go up as expected for the radix tree (e.g. blas_random 334 -> 749 nodes, 113,536 -> 169,984 bytes FP32; 119,104 bytes as BOX16); I did not measure traversal steps. tests/test_xdxr_bvh.py: 40 OK on the branch; with main's tools/xdxr_bvh.py the same file fails 2 and errors 1. No game files. AI-assisted (Claude Code).

ItsNotRexed added a commit that referenced this pull request Nov 23, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ItsNotRexed added a commit that referenced this pull request Nov 23, 2026
… and xdxr_build_check fails with both

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
gregoirener pushed a commit to gregoirener/Leonida-latest-backup-Monday-23-nov-Japanese-time- that referenced this pull request Nov 23, 2026
…s BLAS index check, not on the builder

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@NiiRoZz

NiiRoZz commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Closing: this landed on main as ba288b5 (reverted in 18151ae, restored in a4d7182 after the xdxr_build_check failure was traced to #2753's BLAS index check), and #3315 is merged too, so there is nothing left to merge here.

@NiiRoZz NiiRoZz closed this Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants