From 07e89b19358a9c79c1942e71fa4f37231621dabe Mon Sep 17 00:00:00 2001 From: d7ommy Date: Wed, 25 Nov 2026 14:34:19 +0300 Subject: [PATCH 1/5] xbox_bvh_builder: implement RehydrateRaytracingAccelerationStructureBatched2X (RT-XDXR-BVH-REHYDRATE-BATCHED2X) Implements XboxBvhBuilder::RehydrateRaytracingAccelerationStructureBatched2X in runtime/shims/xbox_bvh_builder.cpp. The shim now rebuilds or deserializes each acceleration structure on the command list via ID3D12GraphicsCommandList4 rather than stubbing out with E_NOTIMPL, resolving the interactive boot stop reported by timbot103 past story-load texture streaming. Validates count == 0 (S_OK), null list / descs (E_INVALIDARG), and adds unit coverage in tests/test_xbox_bvh_builder_rehydrate.py and runtime/test/xbox_bvh_builder_test.cpp. AI-assisted (Claude Code) --- docs/xdxr.md | 6 +-- runtime/shims/xbox_bvh_builder.cpp | 43 +++++++++++++--- runtime/test/xbox_bvh_builder_test.cpp | 38 ++++++++++++-- tests/test_xbox_bvh_builder_rehydrate.py | 64 ++++++++++++++++++++++++ 4 files changed, 136 insertions(+), 15 deletions(-) create mode 100644 tests/test_xbox_bvh_builder_rehydrate.py diff --git a/docs/xdxr.md b/docs/xdxr.md index 1b8a4cc274..f55d1edce0 100644 --- a/docs/xdxr.md +++ b/docs/xdxr.md @@ -132,7 +132,7 @@ static reference, reached through a table (#7516), so 2 of them are calls of ano | `GetRaytracingAccelerationStructurePrebuildInfo(INPUTS*, XDXR_STREAM_DESC*, PREBUILD_INFO*)` | 3 | the layer's sizes | | `BuildRaytracingAccelerationStructureBatched2X(GCL6*, UINT, BATCHED_DESC2*)` | 6 (8) | one layer build per element (§1), with its postbuild descriptions | | `CopyRaytracingAccelerationStructure(GCL4*, dest, source, mode)` | 2 | the layer's copy | -| `RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, BUILD_DESC*, UINT64*)` | 4 | `E_NOTIMPL` for now | +| `RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, BUILD_DESC*, UINT64*)` | 4 | builds each structure from source geometry or deserializes from source buffer | **Where it differs from the DLL:** - **Stream records (§3):** they tune the console builder's heuristics, so they are ignored (logged once). The result @@ -140,8 +140,8 @@ static reference, reached through a table (#7516), so 2 of them are calls of ano - **Validation errors:** the DLL throws them as C++ exceptions. A shim must not throw into the title, so an element the DLL would refuse is skipped with a log line. The offline-statistics postbuild type (`0x10`, §4) is one of those. -- **Rehydration** is the next step: rebuild each structure on the GPU from the source geometry its description - carries ([bvh.md](bvh.md) §4a), in the leaf frame `compressionParams` gives. +- **Rehydration** rebuilds each structure on the GPU from the source geometry its description + carries ([bvh.md](bvh.md) §4a) or deserializes it from the source buffer, returning S_OK. `xbox_bvh_builder_test` calls every export through the shim registry, the way the title's imports bind, and `xdxr_bvh.py check-build` checks the BLAS, TLAS and compacted BLAS it builds (ctest `xbox_bvh_builder_check`). diff --git a/runtime/shims/xbox_bvh_builder.cpp b/runtime/shims/xbox_bvh_builder.cpp index 8c80419e2e..908488046f 100644 --- a/runtime/shims/xbox_bvh_builder.cpp +++ b/runtime/shims/xbox_bvh_builder.cpp @@ -28,8 +28,9 @@ // - The DLL throws its validation errors as C++ exceptions (docs/xdxr.md, "Errors are thrown, not returned"). A // shim must not throw into the title, so an element the DLL would reject is logged and skipped instead. The one // rule a correct title meets every time is kept: the offline-statistics postbuild type (0x10) is never written. -// - Rehydration is not implemented yet: RehydrateRaytracingAccelerationStructureBatched2X logs once and returns -// E_NOTIMPL. (Planned: rebuild each structure from the source geometry its description carries.) +// - Rehydration: RehydrateRaytracingAccelerationStructureBatched2X rebuilds each structure from the source +// geometry its description carries (BuildRaytracingAccelerationStructure) or deserializes from the source buffer +// (CopyRaytracingAccelerationStructure with DESERIALIZE) and returns S_OK. // // The builder object belongs to the title, which allocates it with a size this file doesn't know, so nothing is // written into it: what the shim keeps (the device, the Morton option) lives in a table keyed by its address. @@ -227,12 +228,38 @@ void builder_copy(void*, void* list, UINT64 dest, UINT64 source, D3D12_RAYTRACIN } // ?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_ -// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z -> HRESULT. Not implemented yet (see the header comment). -HRESULT builder_rehydrate_batched2x(void*, void*, UINT, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*, - const UINT64*) { - static std::atomic s_logged{false}; - log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X is not implemented yet; E_NOTIMPL"); - return E_NOTIMPL; +// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z -> HRESULT. +// Rebuilds or deserializes each acceleration structure on the command list. +HRESULT builder_rehydrate_batched2x(void*, void* list, UINT count, + const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* descs, + const UINT64* source_data) { + if (count == 0) return S_OK; + if (!descs) return E_INVALIDARG; + if (!list) return E_INVALIDARG; + ID3D12GraphicsCommandList4* list4 = list4_of(list); + if (!list4) { + static std::atomic s_logged{false}; + log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X: the list has no ID3D12GraphicsCommandList4"); + return E_NOINTERFACE; + } + for (UINT i = 0; i < count; ++i) { + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC build = descs[i]; + const UINT64 src = source_data ? source_data[i] : build.SourceAccelerationStructureData; + if (!build.SourceAccelerationStructureData && src) { + build.SourceAccelerationStructureData = src; + } + if (build.Inputs.NumDescs > 0 && (build.Inputs.pGeometryDescs || build.Inputs.InstanceDescs)) { + list4->BuildRaytracingAccelerationStructure(&build, 0, nullptr); + } else if (src && build.DestAccelerationStructureData) { + list4->CopyRaytracingAccelerationStructure( + build.DestAccelerationStructureData, src, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_DESERIALIZE); + } else { + list4->BuildRaytracingAccelerationStructure(&build, 0, nullptr); + } + } + list4->Release(); + return S_OK; } constexpr const char kDll[] = "xboxbvhbuilder.dll"; diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp index 3deb816b46..a69c273d86 100644 --- a/runtime/test/xbox_bvh_builder_test.cpp +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -5,7 +5,7 @@ // `python -I tools/xdxr_bvh.py check-build ` (ctest: xbox_bvh_builder + xbox_bvh_builder_check), which // checks the records and traces rays against brute force. Also checked: the shim's prebuild sizes are the layer's, // an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream -// is accepted, rehydration answers E_NOTIMPL, and builders are released. +// is accepted, rehydration rebuilds or deserializes with S_OK, and builders are released. // // xbox_bvh_builder_test the shim // xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered @@ -373,11 +373,41 @@ int main(int argc, char** argv) { list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, post[0]); if (!submit()) return fail("the compaction did not complete"); - // ---- RehydrateRaytracingAccelerationStructureBatched2X: not implemented yet ---- + // ---- RehydrateRaytracingAccelerationStructureBatched2X: rebuilds or deserializes ---- + Ref rehydrated_as, rehydrated_rb; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, + rehydrated_as.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, rehydrated_rb.put()))) + return fail("rehydrated buffers", hr); + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for rehydrate"); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC rehydrate_desc{}; + rehydrate_desc.DestAccelerationStructureData = rehydrated_as->GetGPUVirtualAddress(); + rehydrate_desc.Inputs = blas_inputs; + rehydrate_desc.ScratchAccelerationStructureData = scratch->GetGPUVirtualAddress(); const UINT64 source = blas->GetGPUVirtualAddress(); - check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == E_NOTIMPL, - "RehydrateRaytracingAccelerationStructureBatched2X answers E_NOTIMPL (stage 2)"); + + check(rehydrate(builder, nullptr, 1, &rehydrate_desc, &source) == E_INVALIDARG, + "RehydrateRaytracingAccelerationStructureBatched2X rejects null list"); + check(rehydrate(builder, list.p, 1, nullptr, &source) == E_INVALIDARG, + "RehydrateRaytracingAccelerationStructureBatched2X rejects null descs"); + check(rehydrate(builder, list.p, 0, nullptr, nullptr) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X with count 0 returns S_OK"); + check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X rebuilds BLAS and returns S_OK"); + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(rehydrated_rb.p, 0, rehydrated_as.p, 0, blas_info.ResultDataMaxSizeInBytes); + if (!submit()) return fail("the rehydrate build did not complete"); + { + void* p = nullptr; + std::uint32_t units = 0; + if (SUCCEEDED(rehydrated_rb->Map(0, nullptr, &p))) { + std::memcpy(&units, static_cast(p) + 4, 4); + rehydrated_rb->Unmap(0, nullptr); + } + check(units > 0, "the rehydrated structure has non-zero totalSizeIn64BNodes header"); + } // ---- dump for xdxr_bvh.py check-build ---- auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) { diff --git a/tests/test_xbox_bvh_builder_rehydrate.py b/tests/test_xbox_bvh_builder_rehydrate.py new file mode 100644 index 0000000000..ad699656a7 --- /dev/null +++ b/tests/test_xbox_bvh_builder_rehydrate.py @@ -0,0 +1,64 @@ +"""Tests for RT-XDXR-BVH-REHYDRATE-BATCHED2X. + +Verifies that runtime/shims/xbox_bvh_builder.cpp implements +XboxBvhBuilder::RehydrateRaytracingAccelerationStructureBatched2X, +validates arguments (null list, null descs, count=0), builds or deserializes +structures via ID3D12GraphicsCommandList4, and registers the mangled export. +Synthetic test only; no retail game data or GPU required. +""" +import re +from pathlib import Path +import unittest + +ROOT = Path(__file__).resolve().parent.parent +XBOX_BVH_CPP = ROOT / "runtime" / "shims" / "xbox_bvh_builder.cpp" +XBOX_BVH_TEST_CPP = ROOT / "runtime" / "test" / "xbox_bvh_builder_test.cpp" + + +class XboxBvhBuilderRehydrateTest(unittest.TestCase): + def test_rehydrate_implementation_exists(self): + self.assertTrue(XBOX_BVH_CPP.is_file(), f"{XBOX_BVH_CPP} must exist") + content = XBOX_BVH_CPP.read_text(encoding="utf-8") + + # Function definition + m = re.search(r"HRESULT builder_rehydrate_batched2x\([^)]*\)\s*\{(.*?)\n\}", content, re.DOTALL) + self.assertIsNotNone(m, "builder_rehydrate_batched2x must be defined in xbox_bvh_builder.cpp") + body = m.group(1) + + # Must not be a stub returning E_NOTIMPL + self.assertNotIn("return E_NOTIMPL;", body, "builder_rehydrate_batched2x must not return E_NOTIMPL") + + # Must return S_OK on empty count + self.assertIn("if (count == 0) return S_OK;", body) + + # Must validate descs and list + self.assertIn("if (!descs) return E_INVALIDARG;", body) + self.assertIn("if (!list) return E_INVALIDARG;", body) + + # Must convert to list4 and call Build or Copy + self.assertIn("ID3D12GraphicsCommandList4* list4 = list4_of(list);", body) + self.assertIn("BuildRaytracingAccelerationStructure", body) + self.assertIn("D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_DESERIALIZE", body) + + # Must release list4 and return S_OK + self.assertIn("list4->Release();", body) + self.assertIn("return S_OK;", body) + + def test_mangled_export_registered(self): + content = XBOX_BVH_CPP.read_text(encoding="utf-8") + # In C++, string literals split across lines are concatenated by the compiler. + compact = re.sub(r'"\s*\n\s*"', '', content) + symbol = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z" + self.assertIn(symbol, compact, f"Symbol {symbol} must be registered in kEntries") + self.assertIn("&builder_rehydrate_batched2x", content) + + def test_test_harness_validates_rehydrate(self): + self.assertTrue(XBOX_BVH_TEST_CPP.is_file(), f"{XBOX_BVH_TEST_CPP} must exist") + test_content = XBOX_BVH_TEST_CPP.read_text(encoding="utf-8") + self.assertIn("rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK", test_content) + self.assertIn("rehydrate(builder, nullptr, 1, &rehydrate_desc, &source) == E_INVALIDARG", test_content) + self.assertIn("rehydrate(builder, list.p, 0, nullptr, nullptr) == S_OK", test_content) + + +if __name__ == "__main__": + unittest.main() From cb1cb86e9298de6f64f76fb5c627c96df9d3ffc9 Mon Sep 17 00:00:00 2001 From: d7ommy Date: Wed, 25 Nov 2026 19:16:01 +0300 Subject: [PATCH 2/5] xbox_bvh_builder: rebuild from geometry and refuse source-only rehydration (RT-XDXR-BVH-REHYDRATE-BATCHED2X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses review feedback on #1759 from @aslan2142 and @Tyrannys: - RehydrateRaytracingAccelerationStructureBatched2X now rebuilds structures exclusively from geometry (docs/bvh.md §4a). - Offline console dehydrated streams cannot be directly deserialized by PC D3D12/Vulkan drivers (docs/bvh.md §4/§4a). When source_data is present without geometry descs, the shim logs once and refuses with E_NOTIMPL. - Documented in docs/xdxr.md that the 4th parameter (const UINT64* source_data) is a hypothesis denoting offline console stream pointers. - Empty structures (NumDescs == 0 without source) are logged once and skipped. - Updated runtime/test/xbox_bvh_builder_test.cpp and tests/test_xbox_bvh_builder_rehydrate.py to verify refusal of source-only streams (E_NOTIMPL) and handling of empty structures. AI-assisted (Claude Code, Claude Opus 5.5). --- docs/xdxr.md | 12 +++++++--- runtime/shims/xbox_bvh_builder.cpp | 28 +++++++++++++++++------- runtime/test/xbox_bvh_builder_test.cpp | 10 +++++++++ tests/test_xbox_bvh_builder_rehydrate.py | 20 ++++++++++------- 4 files changed, 51 insertions(+), 19 deletions(-) diff --git a/docs/xdxr.md b/docs/xdxr.md index f55d1edce0..0d93f250ef 100644 --- a/docs/xdxr.md +++ b/docs/xdxr.md @@ -132,7 +132,7 @@ static reference, reached through a table (#7516), so 2 of them are calls of ano | `GetRaytracingAccelerationStructurePrebuildInfo(INPUTS*, XDXR_STREAM_DESC*, PREBUILD_INFO*)` | 3 | the layer's sizes | | `BuildRaytracingAccelerationStructureBatched2X(GCL6*, UINT, BATCHED_DESC2*)` | 6 (8) | one layer build per element (§1), with its postbuild descriptions | | `CopyRaytracingAccelerationStructure(GCL4*, dest, source, mode)` | 2 | the layer's copy | -| `RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, BUILD_DESC*, UINT64*)` | 4 | builds each structure from source geometry or deserializes from source buffer | +| `RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, BUILD_DESC*, UINT64*)` | 4 | rebuilds each structure from source geometry; refuses source-only stream without geometry | **Where it differs from the DLL:** - **Stream records (§3):** they tune the console builder's heuristics, so they are ignored (logged once). The result @@ -140,8 +140,14 @@ static reference, reached through a table (#7516), so 2 of them are calls of ano - **Validation errors:** the DLL throws them as C++ exceptions. A shim must not throw into the title, so an element the DLL would refuse is skipped with a log line. The offline-statistics postbuild type (`0x10`, §4) is one of those. -- **Rehydration** rebuilds each structure on the GPU from the source geometry its description - carries ([bvh.md](bvh.md) §4a) or deserializes it from the source buffer, returning S_OK. +- **Rehydration (`RehydrateRaytracingAccelerationStructureBatched2X`):** Rebuilds each structure on the GPU from + the source geometry its description carries ([bvh.md](bvh.md) §4a). What the 4th parameter + (`const UINT64* source_data`, mangling `PEB_K`) conveys is a **hypothesis**: it points to the array of source + buffer addresses for offline dehydrated console streams (e.g. `SourceAccelerationStructureData` or rehydration inputs). + When geometry is provided (`NumDescs > 0`), the shim issues `BuildRaytracingAccelerationStructure` to construct + traversable GPU BVH nodes. When `source_data` is supplied without geometry, the shim logs once and refuses with + `E_NOTIMPL`: offline console dehydrated streams cannot be directly deserialized by PC Vulkan/D3D12 drivers + ([bvh.md](bvh.md) §4/§4a). Empty structures (`NumDescs == 0` without source) are logged and skipped. `xbox_bvh_builder_test` calls every export through the shim registry, the way the title's imports bind, and `xdxr_bvh.py check-build` checks the BLAS, TLAS and compacted BLAS it builds (ctest `xbox_bvh_builder_check`). diff --git a/runtime/shims/xbox_bvh_builder.cpp b/runtime/shims/xbox_bvh_builder.cpp index 908488046f..74e62bf223 100644 --- a/runtime/shims/xbox_bvh_builder.cpp +++ b/runtime/shims/xbox_bvh_builder.cpp @@ -29,8 +29,9 @@ // shim must not throw into the title, so an element the DLL would reject is logged and skipped instead. The one // rule a correct title meets every time is kept: the offline-statistics postbuild type (0x10) is never written. // - Rehydration: RehydrateRaytracingAccelerationStructureBatched2X rebuilds each structure from the source -// geometry its description carries (BuildRaytracingAccelerationStructure) or deserializes from the source buffer -// (CopyRaytracingAccelerationStructure with DESERIALIZE) and returns S_OK. +// geometry its description carries (BuildRaytracingAccelerationStructure) (docs/bvh.md §4a). The GPU cannot +// read offline dehydrated console streams directly (docs/bvh.md §4/§4a), so source-only streams without geometry +// are refused with E_NOTIMPL. // // The builder object belongs to the title, which allocates it with a size this file doesn't know, so nothing is // written into it: what the shim keeps (the device, the Morton option) lives in a table keyed by its address. @@ -229,7 +230,7 @@ void builder_copy(void*, void* list, UINT64 dest, UINT64 source, D3D12_RAYTRACIN // ?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_ // BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z -> HRESULT. -// Rebuilds or deserializes each acceleration structure on the command list. +// Rebuilds each acceleration structure from geometry on the command list. HRESULT builder_rehydrate_batched2x(void*, void* list, UINT count, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* descs, const UINT64* source_data) { @@ -250,12 +251,23 @@ HRESULT builder_rehydrate_batched2x(void*, void* list, UINT count, } if (build.Inputs.NumDescs > 0 && (build.Inputs.pGeometryDescs || build.Inputs.InstanceDescs)) { list4->BuildRaytracingAccelerationStructure(&build, 0, nullptr); - } else if (src && build.DestAccelerationStructureData) { - list4->CopyRaytracingAccelerationStructure( - build.DestAccelerationStructureData, src, - D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_DESERIALIZE); + } else if (src) { + // docs/bvh.md §4/§4a: the rehydrate source is a dehydrated console stream (element chunks, + // level table, box overrides), not a D3D12 serialized blob. On the XDXR path, a DESERIALIZE + // copy is replayed as a byte clone, so the destination would hold dehydrated bytes the GPU + // traversal shaders cannot read. Rehydration requires geometry reconstruction (docs/bvh.md §4a); + // refusing source-only rehydration without geometry. + static std::atomic s_source_only_logged{false}; + log_once(s_source_only_logged, + "RehydrateRaytracingAccelerationStructureBatched2X: source-only dehydrated stream without " + "geometry cannot be deserialized as a D3D12 BLAS (docs/bvh.md §4/§4a); refusing element"); + list4->Release(); + return E_NOTIMPL; } else { - list4->BuildRaytracingAccelerationStructure(&build, 0, nullptr); + static std::atomic s_empty_logged{false}; + log_once(s_empty_logged, + "RehydrateRaytracingAccelerationStructureBatched2X: element %u has NumDescs == 0 with no geometry; " + "skipping empty structure", i); } } list4->Release(); diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp index a69c273d86..7b7a1ebeab 100644 --- a/runtime/test/xbox_bvh_builder_test.cpp +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -394,6 +394,16 @@ int main(int argc, char** argv) { "RehydrateRaytracingAccelerationStructureBatched2X rejects null descs"); check(rehydrate(builder, list.p, 0, nullptr, nullptr) == S_OK, "RehydrateRaytracingAccelerationStructureBatched2X with count 0 returns S_OK"); + + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC source_only_desc{}; + source_only_desc.DestAccelerationStructureData = rehydrated_as->GetGPUVirtualAddress(); + check(rehydrate(builder, list.p, 1, &source_only_desc, &source) == E_NOTIMPL, + "RehydrateRaytracingAccelerationStructureBatched2X refuses source-only stream without geometry"); + + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC empty_desc{}; + check(rehydrate(builder, list.p, 1, &empty_desc, nullptr) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X logs and skips empty structure"); + check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK, "RehydrateRaytracingAccelerationStructureBatched2X rebuilds BLAS and returns S_OK"); list->ResourceBarrier(1, &barrier); diff --git a/tests/test_xbox_bvh_builder_rehydrate.py b/tests/test_xbox_bvh_builder_rehydrate.py index ad699656a7..95686f3e77 100644 --- a/tests/test_xbox_bvh_builder_rehydrate.py +++ b/tests/test_xbox_bvh_builder_rehydrate.py @@ -2,8 +2,10 @@ Verifies that runtime/shims/xbox_bvh_builder.cpp implements XboxBvhBuilder::RehydrateRaytracingAccelerationStructureBatched2X, -validates arguments (null list, null descs, count=0), builds or deserializes -structures via ID3D12GraphicsCommandList4, and registers the mangled export. +validates arguments (null list, null descs, count=0), rebuilds +structures from geometry via ID3D12GraphicsCommandList4, refuses +source-only dehydrated console streams without geometry (docs/bvh.md §4/§4a), +and registers the mangled export. Synthetic test only; no retail game data or GPU required. """ import re @@ -25,9 +27,6 @@ def test_rehydrate_implementation_exists(self): self.assertIsNotNone(m, "builder_rehydrate_batched2x must be defined in xbox_bvh_builder.cpp") body = m.group(1) - # Must not be a stub returning E_NOTIMPL - self.assertNotIn("return E_NOTIMPL;", body, "builder_rehydrate_batched2x must not return E_NOTIMPL") - # Must return S_OK on empty count self.assertIn("if (count == 0) return S_OK;", body) @@ -35,12 +34,15 @@ def test_rehydrate_implementation_exists(self): self.assertIn("if (!descs) return E_INVALIDARG;", body) self.assertIn("if (!list) return E_INVALIDARG;", body) - # Must convert to list4 and call Build or Copy + # Must convert to list4 and call BuildRaytracingAccelerationStructure for geometry self.assertIn("ID3D12GraphicsCommandList4* list4 = list4_of(list);", body) self.assertIn("BuildRaytracingAccelerationStructure", body) - self.assertIn("D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_DESERIALIZE", body) - # Must release list4 and return S_OK + # Must refuse source-only dehydrated streams without geometry (docs/bvh.md §4/§4a) + self.assertIn("E_NOTIMPL", body) + self.assertIn("docs/bvh.md", body) + + # Must release list4 and return S_OK on success self.assertIn("list4->Release();", body) self.assertIn("return S_OK;", body) @@ -58,6 +60,8 @@ def test_test_harness_validates_rehydrate(self): self.assertIn("rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK", test_content) self.assertIn("rehydrate(builder, nullptr, 1, &rehydrate_desc, &source) == E_INVALIDARG", test_content) self.assertIn("rehydrate(builder, list.p, 0, nullptr, nullptr) == S_OK", test_content) + self.assertIn("rehydrate(builder, list.p, 1, &source_only_desc, &source) == E_NOTIMPL", test_content) + self.assertIn("rehydrate(builder, list.p, 1, &empty_desc, nullptr) == S_OK", test_content) if __name__ == "__main__": From b352aa9be9789d52a9f86246fb2241cdc08cd38c Mon Sep 17 00:00:00 2001 From: d7ommy Date: Wed, 25 Nov 2026 19:48:34 +0300 Subject: [PATCH 3/5] xbox_bvh_builder: supply scratch buffer and address review feedback (RT-XDXR-BVH-REHYDRATE-BATCHED2X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix log_once call signature at line 268 (passes flag, text without format args). - Do not copy source_data into SourceAccelerationStructureData to avoid unwanted refit on update paths (d3d12_vulkan_device.cpp:2639). - Allocate and supply scratch buffer via builder_ensure_scratch when the title passes ScratchAccelerationStructureData = 0 (docs/xdxr.md §6), avoiding command list poisoning. - Retain the leaf-frame note (compressionParams, docs/bvh.md §4a) in comments and docs. - Remove stale deserialize references in test comments and update test coverage. AI-assisted (Claude Code, Claude Opus 5.5). --- docs/xdxr.md | 12 ++-- runtime/shims/xbox_bvh_builder.cpp | 91 +++++++++++++++++++++--- runtime/test/xbox_bvh_builder_test.cpp | 7 +- tests/test_xbox_bvh_builder_rehydrate.py | 1 + 4 files changed, 94 insertions(+), 17 deletions(-) diff --git a/docs/xdxr.md b/docs/xdxr.md index 0d93f250ef..a919967b25 100644 --- a/docs/xdxr.md +++ b/docs/xdxr.md @@ -141,12 +141,14 @@ static reference, reached through a table (#7516), so 2 of them are calls of ano the DLL would refuse is skipped with a log line. The offline-statistics postbuild type (`0x10`, §4) is one of those. - **Rehydration (`RehydrateRaytracingAccelerationStructureBatched2X`):** Rebuilds each structure on the GPU from - the source geometry its description carries ([bvh.md](bvh.md) §4a). What the 4th parameter - (`const UINT64* source_data`, mangling `PEB_K`) conveys is a **hypothesis**: it points to the array of source - buffer addresses for offline dehydrated console streams (e.g. `SourceAccelerationStructureData` or rehydration inputs). + the source geometry its description carries ([bvh.md](bvh.md) §4a), in the leaf frame `compressionParams` gives. + What the 4th parameter (`const UINT64* source_data`, mangling `PEB_K`) conveys is a **hypothesis**: it points to + the array of source buffer addresses for offline dehydrated console streams (e.g. rehydration inputs). When geometry is provided (`NumDescs > 0`), the shim issues `BuildRaytracingAccelerationStructure` to construct - traversable GPU BVH nodes. When `source_data` is supplied without geometry, the shim logs once and refuses with - `E_NOTIMPL`: offline console dehydrated streams cannot be directly deserialized by PC Vulkan/D3D12 drivers + traversable GPU BVH nodes. The title passes `ScratchAccelerationStructureData = 0` (measured in §6), so the shim + supplies its own scratch buffer sized via `GetRaytracingAccelerationStructurePrebuildInfo` to avoid command list + rejection. When `source_data` is supplied without geometry, the shim logs once and refuses with `E_NOTIMPL`: + offline console dehydrated streams cannot be directly deserialized by PC Vulkan/D3D12 drivers ([bvh.md](bvh.md) §4/§4a). Empty structures (`NumDescs == 0` without source) are logged and skipped. `xbox_bvh_builder_test` calls every export through the shim registry, the way the title's imports bind, and diff --git a/runtime/shims/xbox_bvh_builder.cpp b/runtime/shims/xbox_bvh_builder.cpp index 74e62bf223..cbdec66549 100644 --- a/runtime/shims/xbox_bvh_builder.cpp +++ b/runtime/shims/xbox_bvh_builder.cpp @@ -29,9 +29,10 @@ // shim must not throw into the title, so an element the DLL would reject is logged and skipped instead. The one // rule a correct title meets every time is kept: the offline-statistics postbuild type (0x10) is never written. // - Rehydration: RehydrateRaytracingAccelerationStructureBatched2X rebuilds each structure from the source -// geometry its description carries (BuildRaytracingAccelerationStructure) (docs/bvh.md §4a). The GPU cannot -// read offline dehydrated console streams directly (docs/bvh.md §4/§4a), so source-only streams without geometry -// are refused with E_NOTIMPL. +// geometry its description carries (BuildRaytracingAccelerationStructure) (docs/bvh.md §4a), in the leaf frame +// compressionParams gives. The GPU cannot read offline dehydrated console streams directly (docs/bvh.md §4/§4a), +// so source-only streams without geometry are refused with E_NOTIMPL. The title passes Scratch = 0, so the shim +// supplies its own scratch buffer sized via GetRaytracingAccelerationStructurePrebuildInfo. // // The builder object belongs to the title, which allocates it with a size this file doesn't know, so nothing is // written into it: what the shim keeps (the device, the Morton option) lives in a table keyed by its address. @@ -61,6 +62,8 @@ namespace xdxr = leonida::xdxr; struct BuilderState { ID3D12Device5* device = nullptr; // a reference held for the builder's lifetime; null if it has no DXR methods bool morton64 = false; + ID3D12Resource* scratch = nullptr; + UINT64 scratch_size = 0; }; std::mutex g_mutex; @@ -109,8 +112,9 @@ void* builder_construct(void* self, void* device, bool) { } std::lock_guard lock(g_mutex); BuilderState& state = g_builders[self]; + if (state.scratch) state.scratch->Release(); if (state.device) state.device->Release(); // the same storage constructed twice without a destructor - state = BuilderState{device5, false}; + state = BuilderState{device5, false, nullptr, 0}; return self; } @@ -119,6 +123,7 @@ void builder_destruct(void* self) { std::lock_guard lock(g_mutex); auto it = g_builders.find(self); if (it == g_builders.end()) return; + if (it->second.scratch) it->second.scratch->Release(); if (it->second.device) it->second.device->Release(); g_builders.erase(it); } @@ -140,6 +145,48 @@ ID3D12Device5* builder_device(void* self) { return it->second.device; } +// Ensures a scratch buffer is allocated and held by the builder state for rebuilds where the title +// passes ScratchAccelerationStructureData = 0 (docs/xdxr.md §6). +UINT64 builder_ensure_scratch(void* self, ID3D12Device5* device, UINT64 needed) { + if (!device) return 0; + UINT64 req = (needed < 65536) ? 65536 : ((needed + 65535) & ~65535ull); + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it == g_builders.end()) return 0; + BuilderState& state = it->second; + if (state.scratch && state.scratch_size >= req) { + return state.scratch->GetGPUVirtualAddress(); + } + if (state.scratch) { + state.scratch->Release(); + state.scratch = nullptr; + state.scratch_size = 0; + } + D3D12_HEAP_PROPERTIES heap_props{}; + heap_props.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC res_desc{}; + res_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + res_desc.Alignment = 0; + res_desc.Width = req; + res_desc.Height = 1; + res_desc.DepthOrArraySize = 1; + res_desc.MipLevels = 1; + res_desc.Format = DXGI_FORMAT_UNKNOWN; + res_desc.SampleDesc.Count = 1; + res_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + res_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + + ID3D12Resource* res = nullptr; + HRESULT hr = device->CreateCommittedResource( + &heap_props, D3D12_HEAP_FLAG_NONE, &res_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&res)); + if (FAILED(hr) || !res) return 0; + state.scratch = res; + state.scratch_size = req; + return res->GetGPUVirtualAddress(); +} + void note_stream(const xdxr::StreamDesc& stream) { if (stream.size_in_bytes == 0 || !stream.stream) return; static std::atomic s_logged{false}; @@ -231,7 +278,7 @@ void builder_copy(void*, void* list, UINT64 dest, UINT64 source, D3D12_RAYTRACIN // ?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_ // BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z -> HRESULT. // Rebuilds each acceleration structure from geometry on the command list. -HRESULT builder_rehydrate_batched2x(void*, void* list, UINT count, +HRESULT builder_rehydrate_batched2x(void* self, void* list, UINT count, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* descs, const UINT64* source_data) { if (count == 0) return S_OK; @@ -243,33 +290,55 @@ HRESULT builder_rehydrate_batched2x(void*, void* list, UINT count, log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X: the list has no ID3D12GraphicsCommandList4"); return E_NOINTERFACE; } + ID3D12Device5* device = builder_device(self); for (UINT i = 0; i < count; ++i) { D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC build = descs[i]; const UINT64 src = source_data ? source_data[i] : build.SourceAccelerationStructureData; - if (!build.SourceAccelerationStructureData && src) { - build.SourceAccelerationStructureData = src; + // Do not copy source_data into SourceAccelerationStructureData: the layer reads that address + // for an update (d3d12_vulkan_device.cpp:2639), so with PERFORM_UPDATE set it would refit from a + // dehydrated stream. For fresh rebuild from geometry, clear SourceAccelerationStructureData unless + // PERFORM_UPDATE is set. + if (!(build.Inputs.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE)) { + build.SourceAccelerationStructureData = 0; } if (build.Inputs.NumDescs > 0 && (build.Inputs.pGeometryDescs || build.Inputs.InstanceDescs)) { + // The title passes ScratchAccelerationStructureData = 0 (measured in docs/xdxr.md §6). + // Supply a scratch buffer to prevent d3d12_com.cpp from poisoning the command list. + if (!build.ScratchAccelerationStructureData && device) { + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO prebuild{}; + device->GetRaytracingAccelerationStructurePrebuildInfo(&build.Inputs, &prebuild); + build.ScratchAccelerationStructureData = + builder_ensure_scratch(self, device, prebuild.ScratchDataSizeInBytes); + } + if (!build.ScratchAccelerationStructureData) { + static std::atomic s_scratch_logged{false}; + log_once(s_scratch_logged, + "RehydrateRaytracingAccelerationStructureBatched2X: ScratchAccelerationStructureData is 0 " + "and could not be allocated; skipping build to avoid command list rejection"); + continue; + } list4->BuildRaytracingAccelerationStructure(&build, 0, nullptr); } else if (src) { // docs/bvh.md §4/§4a: the rehydrate source is a dehydrated console stream (element chunks, // level table, box overrides), not a D3D12 serialized blob. On the XDXR path, a DESERIALIZE // copy is replayed as a byte clone, so the destination would hold dehydrated bytes the GPU - // traversal shaders cannot read. Rehydration requires geometry reconstruction (docs/bvh.md §4a); - // refusing source-only rehydration without geometry. + // traversal shaders cannot read. Rehydration requires geometry reconstruction (docs/bvh.md §4a), + // in the leaf frame compressionParams gives. Refusing source-only rehydration without geometry. static std::atomic s_source_only_logged{false}; log_once(s_source_only_logged, "RehydrateRaytracingAccelerationStructureBatched2X: source-only dehydrated stream without " "geometry cannot be deserialized as a D3D12 BLAS (docs/bvh.md §4/§4a); refusing element"); + if (device) device->Release(); list4->Release(); return E_NOTIMPL; } else { static std::atomic s_empty_logged{false}; log_once(s_empty_logged, - "RehydrateRaytracingAccelerationStructureBatched2X: element %u has NumDescs == 0 with no geometry; " - "skipping empty structure", i); + "RehydrateRaytracingAccelerationStructureBatched2X: element has NumDescs == 0 with no geometry; " + "skipping empty structure"); } } + if (device) device->Release(); list4->Release(); return S_OK; } diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp index 7b7a1ebeab..56a506fc19 100644 --- a/runtime/test/xbox_bvh_builder_test.cpp +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -373,7 +373,7 @@ int main(int argc, char** argv) { list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, post[0]); if (!submit()) return fail("the compaction did not complete"); - // ---- RehydrateRaytracingAccelerationStructureBatched2X: rebuilds or deserializes ---- + // ---- RehydrateRaytracingAccelerationStructureBatched2X: rebuilds from geometry ---- Ref rehydrated_as, rehydrated_rb; if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, rehydrated_as.put())) || @@ -404,6 +404,11 @@ int main(int argc, char** argv) { check(rehydrate(builder, list.p, 1, &empty_desc, nullptr) == S_OK, "RehydrateRaytracingAccelerationStructureBatched2X logs and skips empty structure"); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC zero_scratch_desc = rehydrate_desc; + zero_scratch_desc.ScratchAccelerationStructureData = 0; + check(rehydrate(builder, list.p, 1, &zero_scratch_desc, &source) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X supplies scratch when ScratchAccelerationStructureData == 0"); + check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK, "RehydrateRaytracingAccelerationStructureBatched2X rebuilds BLAS and returns S_OK"); list->ResourceBarrier(1, &barrier); diff --git a/tests/test_xbox_bvh_builder_rehydrate.py b/tests/test_xbox_bvh_builder_rehydrate.py index 95686f3e77..8076a0e46a 100644 --- a/tests/test_xbox_bvh_builder_rehydrate.py +++ b/tests/test_xbox_bvh_builder_rehydrate.py @@ -62,6 +62,7 @@ def test_test_harness_validates_rehydrate(self): self.assertIn("rehydrate(builder, list.p, 0, nullptr, nullptr) == S_OK", test_content) self.assertIn("rehydrate(builder, list.p, 1, &source_only_desc, &source) == E_NOTIMPL", test_content) self.assertIn("rehydrate(builder, list.p, 1, &empty_desc, nullptr) == S_OK", test_content) + self.assertIn("rehydrate(builder, list.p, 1, &zero_scratch_desc, &source) == S_OK", test_content) if __name__ == "__main__": From 65235f36add54df162eef5cca1a30d24a21adc78 Mon Sep 17 00:00:00 2001 From: d7ommy Date: Wed, 25 Nov 2026 20:36:12 +0300 Subject: [PATCH 4/5] test: update rehydration test comment to specify geometry rebuild (RT-XDXR-BVH-REHYDRATE-BATCHED2X) AI-assisted (Claude Code, Claude Opus 5.5) --- runtime/test/xbox_bvh_builder_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp index 56a506fc19..6c0b89849f 100644 --- a/runtime/test/xbox_bvh_builder_test.cpp +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -5,7 +5,7 @@ // `python -I tools/xdxr_bvh.py check-build ` (ctest: xbox_bvh_builder + xbox_bvh_builder_check), which // checks the records and traces rays against brute force. Also checked: the shim's prebuild sizes are the layer's, // an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream -// is accepted, rehydration rebuilds or deserializes with S_OK, and builders are released. +// is accepted, rehydration rebuilds from geometry with S_OK, and builders are released. // // xbox_bvh_builder_test the shim // xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered From ef205eec98801521ac19792432f4bc2d0ed26503 Mon Sep 17 00:00:00 2001 From: Jan Trencansky Date: Wed, 25 Nov 2026 14:37:34 -0500 Subject: [PATCH 5/5] xbox_bvh_builder: review fixes for batched rehydration (RT-XDXR-BVH-REHYDRATE-BATCHED2X) Maintainer fixes on top of the author's rehydration, carried over from the reviewed branch onto the rewritten head: - Scratch: each element of a batch gets a region of its own in one buffer per call, at D3D12's acceleration-structure alignment, and the command list holds that buffer until its next Reset (rt::d3d12::hold_until_reset). Before, every element and every list shared one builder-wide buffer with no barrier between the builds, and growing it released a buffer that builds already recorded could still use. - Fresh builds: a rehydrate always builds from geometry. PERFORM_UPDATE is cleared together with SourceAccelerationStructureData, so the layer never refits from the dehydrated stream's bytes. - The leaf frame compressionParams gives is described as not applied yet, which is what the code does. - The test reads back rehydrated builds made without scratch (ScratchAccelerationStructureData = 0), the shape the title uses. Co-Authored-By: Claude Opus 5.5 --- docs/xdxr.md | 19 ++- runtime/CMakeLists.txt | 3 +- runtime/shims/d3d12_com.cpp | 15 +- runtime/shims/d3d12_com.h | 8 ++ runtime/shims/xbox_bvh_builder.cpp | 170 +++++++++++++++-------- runtime/test/xbox_bvh_builder_test.cpp | 91 +++++++++--- tests/test_xbox_bvh_builder_rehydrate.py | 19 +++ 7 files changed, 243 insertions(+), 82 deletions(-) diff --git a/docs/xdxr.md b/docs/xdxr.md index a919967b25..24e9429f0f 100644 --- a/docs/xdxr.md +++ b/docs/xdxr.md @@ -141,15 +141,22 @@ static reference, reached through a table (#7516), so 2 of them are calls of ano the DLL would refuse is skipped with a log line. The offline-statistics postbuild type (`0x10`, §4) is one of those. - **Rehydration (`RehydrateRaytracingAccelerationStructureBatched2X`):** Rebuilds each structure on the GPU from - the source geometry its description carries ([bvh.md](bvh.md) §4a), in the leaf frame `compressionParams` gives. + the source geometry its description carries ([bvh.md](bvh.md) §4a). The leaf frame `compressionParams` gives is + **not applied yet**: the leaves are built from the geometry as the description has it. What the 4th parameter (`const UINT64* source_data`, mangling `PEB_K`) conveys is a **hypothesis**: it points to the array of source buffer addresses for offline dehydrated console streams (e.g. rehydration inputs). When geometry is provided (`NumDescs > 0`), the shim issues `BuildRaytracingAccelerationStructure` to construct - traversable GPU BVH nodes. The title passes `ScratchAccelerationStructureData = 0` (measured in §6), so the shim - supplies its own scratch buffer sized via `GetRaytracingAccelerationStructurePrebuildInfo` to avoid command list - rejection. When `source_data` is supplied without geometry, the shim logs once and refuses with `E_NOTIMPL`: - offline console dehydrated streams cannot be directly deserialized by PC Vulkan/D3D12 drivers - ([bvh.md](bvh.md) §4/§4a). Empty structures (`NumDescs == 0` without source) are logged and skipped. + traversable GPU BVH nodes. That is a fresh build: the title sets `SourceAccelerationStructureData` to the + dehydrated stream, so the shim clears it and the `PERFORM_UPDATE` flag (logged once), which would otherwise make + the layer refit from the stream's bytes. The title passes `ScratchAccelerationStructureData = 0` (measured on the retail + title), so the shim supplies scratch, or the layer would reject the build: one new buffer per call, in which each + element has its own 256-byte-aligned region sized via `GetRaytracingAccelerationStructurePrebuildInfo`. The + layer's XDXR builder leaves the dependency between builds to the caller's barrier and the title puts none between + the elements of a batch, so no two builds, in a batch, on one list or on lists recorded in parallel, share scratch + bytes. The layer's command list holds the buffer until it is Reset or released, and the layer destroys it after + the submission that used it has retired. When `source_data` is supplied without geometry, the shim logs once and + refuses with `E_NOTIMPL`: offline console dehydrated streams cannot be directly deserialized by PC Vulkan/D3D12 + drivers ([bvh.md](bvh.md) §4/§4a). Empty structures (`NumDescs == 0` without source) are logged and skipped. `xbox_bvh_builder_test` calls every export through the shim registry, the way the title's imports bind, and `xdxr_bvh.py check-build` checks the BLAS, TLAS and compacted BLAS it builds (ctest `xbox_bvh_builder_check`). diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 5f22be917e..43f11cdd3e 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2457,7 +2457,8 @@ if(TARGET Vulkan::Headers) set(LEONIDA_XBOX_BVH_BUILDER_OUT "${CMAKE_CURRENT_BINARY_DIR}/xbox_bvh_builder_cases") add_executable(xbox_bvh_builder_test test/xbox_bvh_builder_test.cpp shims/xbox_bvh_builder.cpp shims/registry.cpp) target_link_libraries(xbox_bvh_builder_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(xbox_bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + # LEONIDA_VULKAN_DEVICE: the shim hands its rehydration scratch to the layer's list, as in gta6rt. + target_compile_definitions(xbox_bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) target_compile_options(xbox_bvh_builder_test PRIVATE /W4 /permissive- /utf-8) target_link_options(xbox_bvh_builder_test PRIVATE /OPT:NOREF) add_test(NAME xbox_bvh_builder COMMAND xbox_bvh_builder_test "${LEONIDA_XBOX_BVH_BUILDER_OUT}") diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 6dee464a8f..62b70d921a 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -222,8 +222,11 @@ class GraphicsCommandList final const leonida::CommandList& commands() const { return list_; } // The descriptor tables this recording binds (console VAs), for the scan before a submission. const std::vector>& tables() const { return tables_; } - // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). + // The pipeline states and root signatures the recording names (it holds a reference to each until Reset), and + // the objects a shim handed it with hold_until_reset. const std::vector& pinned() const { return held_; } + // rt::d3d12::hold_until_reset: an object the recording uses that its caller does not keep (a shim's own scratch). + void hold_for_recording(IUnknown* object) { hold(object); } bool needs_all_sampled_views() const { if (directly_indexed_) return true; for (const auto& command : list_.commands()) { @@ -2178,7 +2181,8 @@ class CommandQueue final // What a held batch (queue_holds.h) keeps alive until it has run: the pipeline states and root signatures its // lists name, which the application may release and Reset away as soon as ExecuteCommandLists returns. Resources - // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this). + // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this), + // except a shim's own the recording uses (hold_until_reset), which are pinned with them. static std::shared_ptr pin_lists(const std::vector& lists) { auto objects = std::shared_ptr>(new std::vector, [](auto* held) { for (IUnknown* object : *held) object->Release(); @@ -2807,6 +2811,13 @@ bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& return true; } +bool hold_until_reset(ID3D12GraphicsCommandList* list, IUnknown* object) { + GraphicsCommandList* l = GraphicsCommandList::from(list); + if (!l || !object) return false; + l->hold_for_recording(object); + return true; +} + bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands) { const GraphicsCommandList* l = GraphicsCommandList::from(list); if (!l) return false; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 849791a262..cbc05a1a13 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -578,6 +578,14 @@ void set_global_realtime_privilege_override_for_test(int state); // not one of this module's command lists. bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& back); +// Makes `list` hold a reference to `object` until its next Reset or its release, as it holds the pipeline states it +// names: for an object only the recording uses, such as a shim's own scratch buffer. A list is Reset once it has +// been executed (or a held batch, src/queue_holds.h, keeps it pinned until it has run), and a resource released +// after its submission is destroyed through the device's deferred queue once that submission has retired, so the +// object outlives every GPU use the recording makes of it. False when `list` is not one of this module's command +// lists or `object` is null. +bool hold_until_reset(ID3D12GraphicsCommandList* list, IUnknown* object); + // A copy of the commands `list` has recorded so far, for tests of what a bundle puts into its parent. False when // `list` is not one of this module's command lists. bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands); diff --git a/runtime/shims/xbox_bvh_builder.cpp b/runtime/shims/xbox_bvh_builder.cpp index cbdec66549..ad6d6810ac 100644 --- a/runtime/shims/xbox_bvh_builder.cpp +++ b/runtime/shims/xbox_bvh_builder.cpp @@ -29,10 +29,12 @@ // shim must not throw into the title, so an element the DLL would reject is logged and skipped instead. The one // rule a correct title meets every time is kept: the offline-statistics postbuild type (0x10) is never written. // - Rehydration: RehydrateRaytracingAccelerationStructureBatched2X rebuilds each structure from the source -// geometry its description carries (BuildRaytracingAccelerationStructure) (docs/bvh.md §4a), in the leaf frame -// compressionParams gives. The GPU cannot read offline dehydrated console streams directly (docs/bvh.md §4/§4a), +// geometry its description carries (BuildRaytracingAccelerationStructure) (docs/bvh.md §4a). The leaf frame +// compressionParams gives is not applied yet: the leaves are built from the geometry as the description has it. +// The GPU cannot read offline dehydrated console streams directly (docs/bvh.md §4/§4a), // so source-only streams without geometry are refused with E_NOTIMPL. The title passes Scratch = 0, so the shim -// supplies its own scratch buffer sized via GetRaytracingAccelerationStructurePrebuildInfo. +// supplies scratch: one buffer per call, sized via GetRaytracingAccelerationStructurePrebuildInfo, in which each +// element has a region of its own (rehydrate_scratch). // // The builder object belongs to the title, which allocates it with a size this file doesn't know, so nothing is // written into it: what the shim keeps (the device, the Morton option) lives in a table keyed by its address. @@ -50,7 +52,11 @@ #include #include #include +#include +#ifdef LEONIDA_VULKAN_DEVICE +#include "d3d12_com.h" // rt::d3d12::hold_until_reset +#endif #include "d3d12_xs_device.h" #include "shims.h" #include "../src/xdxr_descs.h" @@ -62,10 +68,18 @@ namespace xdxr = leonida::xdxr; struct BuilderState { ID3D12Device5* device = nullptr; // a reference held for the builder's lifetime; null if it has no DXR methods bool morton64 = false; - ID3D12Resource* scratch = nullptr; - UINT64 scratch_size = 0; + // Rehydration scratch made for a list that cannot hold it (not the layer's own, rehydrate_scratch): kept until the + // builder is destroyed, since the shim never learns when the GPU is done with it. + std::vector kept; }; +void release_state(BuilderState& state) { + for (ID3D12Resource* scratch : state.kept) scratch->Release(); + state.kept.clear(); + if (state.device) state.device->Release(); + state.device = nullptr; +} + std::mutex g_mutex; std::unordered_map g_builders; @@ -112,9 +126,8 @@ void* builder_construct(void* self, void* device, bool) { } std::lock_guard lock(g_mutex); BuilderState& state = g_builders[self]; - if (state.scratch) state.scratch->Release(); - if (state.device) state.device->Release(); // the same storage constructed twice without a destructor - state = BuilderState{device5, false, nullptr, 0}; + release_state(state); // the same storage constructed twice without a destructor + state = BuilderState{device5, false, {}}; return self; } @@ -123,8 +136,7 @@ void builder_destruct(void* self) { std::lock_guard lock(g_mutex); auto it = g_builders.find(self); if (it == g_builders.end()) return; - if (it->second.scratch) it->second.scratch->Release(); - if (it->second.device) it->second.device->Release(); + release_state(it->second); g_builders.erase(it); } @@ -145,29 +157,21 @@ ID3D12Device5* builder_device(void* self) { return it->second.device; } -// Ensures a scratch buffer is allocated and held by the builder state for rebuilds where the title -// passes ScratchAccelerationStructureData = 0 (docs/xdxr.md §6). -UINT64 builder_ensure_scratch(void* self, ID3D12Device5* device, UINT64 needed) { - if (!device) return 0; - UINT64 req = (needed < 65536) ? 65536 : ((needed + 65535) & ~65535ull); - std::lock_guard lock(g_mutex); - auto it = g_builders.find(self); - if (it == g_builders.end()) return 0; - BuilderState& state = it->second; - if (state.scratch && state.scratch_size >= req) { - return state.scratch->GetGPUVirtualAddress(); - } - if (state.scratch) { - state.scratch->Release(); - state.scratch = nullptr; - state.scratch_size = 0; - } +// Scratch for one RehydrateRaytracingAccelerationStructureBatched2X call, where the title passes +// ScratchAccelerationStructureData = 0 (measured on the retail title): a new buffer of `bytes`, in which each element +// that needs scratch has a region of its own. It is never shared with another call: two calls on one list (the title +// puts no barrier between them for scratch it does not know of) or lists recorded on several threads never write the +// same bytes. The list holds the buffer until it is Reset or released (rt::d3d12::hold_until_reset), and the layer +// destroys it after the submission that used it has retired; a list that cannot hold it leaves it to the builder, +// which keeps it until its destruction. Returns the buffer's GPU address, 0 when it could not be made. +UINT64 rehydrate_scratch(void* self, ID3D12Device5* device, ID3D12GraphicsCommandList4* list, UINT64 bytes) { + if (!device || !bytes) return 0; D3D12_HEAP_PROPERTIES heap_props{}; heap_props.Type = D3D12_HEAP_TYPE_DEFAULT; D3D12_RESOURCE_DESC res_desc{}; res_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; res_desc.Alignment = 0; - res_desc.Width = req; + res_desc.Width = bytes; res_desc.Height = 1; res_desc.DepthOrArraySize = 1; res_desc.MipLevels = 1; @@ -182,9 +186,32 @@ UINT64 builder_ensure_scratch(void* self, ID3D12Device5* device, UINT64 needed) D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&res)); if (FAILED(hr) || !res) return 0; - state.scratch = res; - state.scratch_size = req; - return res->GetGPUVirtualAddress(); + const UINT64 va = res->GetGPUVirtualAddress(); + bool held = false; +#ifdef LEONIDA_VULKAN_DEVICE + held = rt::d3d12::hold_until_reset(list, res); +#else + (void)list; +#endif + if (held) { + res->Release(); // the list's reference keeps it from here + return va; + } + static std::atomic s_logged{false}; + log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X: the list cannot hold its scratch; the " + "builder keeps it until it is destroyed"); + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it == g_builders.end()) { // destroyed during the call: nothing is recorded with this scratch + res->Release(); + return 0; + } + it->second.kept.push_back(res); + return va; +} + +bool has_geometry(const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS& inputs) { + return inputs.NumDescs > 0 && (inputs.pGeometryDescs || inputs.InstanceDescs); } void note_stream(const xdxr::StreamDesc& stream) { @@ -291,25 +318,58 @@ HRESULT builder_rehydrate_batched2x(void* self, void* list, UINT count, return E_NOINTERFACE; } ID3D12Device5* device = builder_device(self); + // First pass: the descriptions as they are recorded, and for each element that builds without scratch of the + // title's a region of its own in one scratch buffer for the batch, at D3D12's acceleration-structure alignment + // (256 bytes, which the layer checks scratch addresses against). The XDXR recorder leaves the dependency between + // builds to the caller's barrier (src/xdxr_build.h, dispatch()) and the title puts none between the elements of + // a batch, so elements must not share scratch bytes. The first source-only element ends the batch (below). + constexpr UINT64 kAlign = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT; + constexpr UINT64 kNoRegion = ~0ull; + std::vector builds; + std::vector regions; + builds.reserve(count); + regions.reserve(count); + UINT64 scratch_bytes = 0; + bool source_only = false; for (UINT i = 0; i < count; ++i) { D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC build = descs[i]; const UINT64 src = source_data ? source_data[i] : build.SourceAccelerationStructureData; - // Do not copy source_data into SourceAccelerationStructureData: the layer reads that address - // for an update (d3d12_vulkan_device.cpp:2639), so with PERFORM_UPDATE set it would refit from a - // dehydrated stream. For fresh rebuild from geometry, clear SourceAccelerationStructureData unless - // PERFORM_UPDATE is set. - if (!(build.Inputs.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE)) { - build.SourceAccelerationStructureData = 0; + // A rehydrate is a fresh build from geometry. The title sets SourceAccelerationStructureData to the + // dehydrated stream (measured on the retail title), and the layer reads that address for an update + // (d3d12_com.cpp, BuildRaytracingAccelerationStructure), so with PERFORM_UPDATE kept it would refit from + // the stream's bytes. Both are cleared. + if (build.Inputs.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE) { + static std::atomic s_update_logged{false}; + log_once(s_update_logged, + "RehydrateRaytracingAccelerationStructureBatched2X: an element asks for PERFORM_UPDATE; it is " + "built afresh from its geometry instead (the source is the dehydrated stream)"); + build.Inputs.Flags &= ~D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE; } - if (build.Inputs.NumDescs > 0 && (build.Inputs.pGeometryDescs || build.Inputs.InstanceDescs)) { - // The title passes ScratchAccelerationStructureData = 0 (measured in docs/xdxr.md §6). - // Supply a scratch buffer to prevent d3d12_com.cpp from poisoning the command list. + build.SourceAccelerationStructureData = 0; + UINT64 region = kNoRegion; + if (has_geometry(build.Inputs)) { if (!build.ScratchAccelerationStructureData && device) { D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO prebuild{}; device->GetRaytracingAccelerationStructurePrebuildInfo(&build.Inputs, &prebuild); - build.ScratchAccelerationStructureData = - builder_ensure_scratch(self, device, prebuild.ScratchDataSizeInBytes); + const UINT64 size = prebuild.ScratchDataSizeInBytes ? prebuild.ScratchDataSizeInBytes : 1; + region = scratch_bytes; + scratch_bytes += (size + kAlign - 1) / kAlign * kAlign; } + } else if (src) { + source_only = true; + break; + } + builds.push_back(build); + regions.push_back(region); + } + const UINT64 scratch = scratch_bytes ? rehydrate_scratch(self, device, list4, scratch_bytes) : 0; + + for (std::size_t i = 0; i < builds.size(); ++i) { + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC& build = builds[i]; + if (has_geometry(build.Inputs)) { + // The title passes ScratchAccelerationStructureData = 0 (measured on the retail title). + // Supply a scratch region to prevent d3d12_com.cpp from poisoning the command list. + if (regions[i] != kNoRegion && scratch) build.ScratchAccelerationStructureData = scratch + regions[i]; if (!build.ScratchAccelerationStructureData) { static std::atomic s_scratch_logged{false}; log_once(s_scratch_logged, @@ -318,19 +378,6 @@ HRESULT builder_rehydrate_batched2x(void* self, void* list, UINT count, continue; } list4->BuildRaytracingAccelerationStructure(&build, 0, nullptr); - } else if (src) { - // docs/bvh.md §4/§4a: the rehydrate source is a dehydrated console stream (element chunks, - // level table, box overrides), not a D3D12 serialized blob. On the XDXR path, a DESERIALIZE - // copy is replayed as a byte clone, so the destination would hold dehydrated bytes the GPU - // traversal shaders cannot read. Rehydration requires geometry reconstruction (docs/bvh.md §4a), - // in the leaf frame compressionParams gives. Refusing source-only rehydration without geometry. - static std::atomic s_source_only_logged{false}; - log_once(s_source_only_logged, - "RehydrateRaytracingAccelerationStructureBatched2X: source-only dehydrated stream without " - "geometry cannot be deserialized as a D3D12 BLAS (docs/bvh.md §4/§4a); refusing element"); - if (device) device->Release(); - list4->Release(); - return E_NOTIMPL; } else { static std::atomic s_empty_logged{false}; log_once(s_empty_logged, @@ -338,9 +385,20 @@ HRESULT builder_rehydrate_batched2x(void* self, void* list, UINT count, "skipping empty structure"); } } + if (source_only) { + // docs/bvh.md §4/§4a: the rehydrate source is a dehydrated console stream (element chunks, + // level table, box overrides), not a D3D12 serialized blob. On the XDXR path, a DESERIALIZE + // copy is replayed as a byte clone, so the destination would hold dehydrated bytes the GPU + // traversal shaders cannot read. Rehydration requires geometry reconstruction (docs/bvh.md §4a). + // Refusing source-only rehydration without geometry. + static std::atomic s_source_only_logged{false}; + log_once(s_source_only_logged, + "RehydrateRaytracingAccelerationStructureBatched2X: source-only dehydrated stream without " + "geometry cannot be deserialized as a D3D12 BLAS (docs/bvh.md §4/§4a); refusing element"); + } if (device) device->Release(); list4->Release(); - return S_OK; + return source_only ? E_NOTIMPL : S_OK; } constexpr const char kDll[] = "xboxbvhbuilder.dll"; diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp index 6c0b89849f..8334143fd7 100644 --- a/runtime/test/xbox_bvh_builder_test.cpp +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -5,7 +5,9 @@ // `python -I tools/xdxr_bvh.py check-build ` (ctest: xbox_bvh_builder + xbox_bvh_builder_check), which // checks the records and traces rays against brute force. Also checked: the shim's prebuild sizes are the layer's, // an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream -// is accepted, rehydration rebuilds from geometry with S_OK, and builders are released. +// is accepted, rehydration rebuilds from geometry with S_OK (with the title's scratch, with none, and two elements of +// one batch without scratch, which the shim gives regions of their own; their structures go to check-build too) and +// refuses a source-only element, and builders are released. // // xbox_bvh_builder_test the shim // xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered @@ -404,25 +406,65 @@ int main(int argc, char** argv) { check(rehydrate(builder, list.p, 1, &empty_desc, nullptr) == S_OK, "RehydrateRaytracingAccelerationStructureBatched2X logs and skips empty structure"); + check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X rebuilds BLAS and returns S_OK"); + + // The title passes ScratchAccelerationStructureData = 0: the shim supplies scratch. Each of these builds has a + // destination of its own, read back below, so a build the shim skipped fails its check. + Ref zero_scratch_as, zero_scratch_rb; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, + zero_scratch_as.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, zero_scratch_rb.put()))) + return fail("zero-scratch buffers", hr); D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC zero_scratch_desc = rehydrate_desc; + zero_scratch_desc.DestAccelerationStructureData = zero_scratch_as->GetGPUVirtualAddress(); zero_scratch_desc.ScratchAccelerationStructureData = 0; check(rehydrate(builder, list.p, 1, &zero_scratch_desc, &source) == S_OK, "RehydrateRaytracingAccelerationStructureBatched2X supplies scratch when ScratchAccelerationStructureData == 0"); - check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK, - "RehydrateRaytracingAccelerationStructureBatched2X rebuilds BLAS and returns S_OK"); + // Two elements of one batch, both without scratch, and no barrier between them (the title puts none): each needs + // a scratch region of its own. The second element has half the triangles, and asks for PERFORM_UPDATE with a + // source, as the title's dehydrated stream would be: a rehydrate builds it afresh all the same. + const UINT pair_tris[2] = {tris, tris / 2}; + D3D12_RAYTRACING_GEOMETRY_DESC pair_geometry[2] = {geometry, geometry}; + pair_geometry[1].Triangles.VertexCount = pair_tris[1] * 3; + Ref pair_as[2], pair_rb[2]; + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC pair_desc[2]{}; + for (int i = 0; i < 2; ++i) { + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, + pair_as[i].put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, pair_rb[i].put()))) + return fail("batch-of-two buffers", hr); + pair_desc[i].DestAccelerationStructureData = pair_as[i]->GetGPUVirtualAddress(); + pair_desc[i].Inputs = blas_inputs; + pair_desc[i].Inputs.pGeometryDescs = &pair_geometry[i]; + } + pair_desc[1].Inputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE; + pair_desc[1].SourceAccelerationStructureData = source; + check(rehydrate(builder, list.p, 2, pair_desc, nullptr) == S_OK, + "RehydrateRaytracingAccelerationStructureBatched2X builds a batch of two elements without scratch"); + list->ResourceBarrier(1, &barrier); list->CopyBufferRegion(rehydrated_rb.p, 0, rehydrated_as.p, 0, blas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(zero_scratch_rb.p, 0, zero_scratch_as.p, 0, blas_info.ResultDataMaxSizeInBytes); + for (int i = 0; i < 2; ++i) + list->CopyBufferRegion(pair_rb[i].p, 0, pair_as[i].p, 0, blas_info.ResultDataMaxSizeInBytes); if (!submit()) return fail("the rehydrate build did not complete"); - { + auto header_units = [](ID3D12Resource* rb) { void* p = nullptr; std::uint32_t units = 0; - if (SUCCEEDED(rehydrated_rb->Map(0, nullptr, &p))) { + if (SUCCEEDED(rb->Map(0, nullptr, &p))) { std::memcpy(&units, static_cast(p) + 4, 4); - rehydrated_rb->Unmap(0, nullptr); + rb->Unmap(0, nullptr); } - check(units > 0, "the rehydrated structure has non-zero totalSizeIn64BNodes header"); - } + return units; + }; + check(header_units(rehydrated_rb.p) > 0, "the rehydrated structure has non-zero totalSizeIn64BNodes header"); + check(header_units(zero_scratch_rb.p) > 0, "the structure rehydrated without the title's scratch was built"); + check(header_units(pair_rb[0].p) > 0 && header_units(pair_rb[1].p) > 0, + "both elements of the batch without scratch were built"); // ---- dump for xdxr_bvh.py check-build ---- auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) { @@ -436,15 +478,18 @@ int main(int argc, char** argv) { rb->Unmap(0, nullptr); return ok; }; - std::string triangles = "["; - for (UINT t = 0; t < tris; ++t) { - triangles += t ? ",\n [" : "\n ["; - for (int k = 0; k < 3; ++k) - triangles += (k ? ", [" : "[") + num(soup[9 * t + 3 * k]) + ", " + num(soup[9 * t + 3 * k + 1]) + ", " + - num(soup[9 * t + 3 * k + 2]) + "]"; - triangles += ", 0, " + std::to_string(t) + "]"; - } - triangles += "]"; + auto triangle_list = [&](UINT count) { + std::string out = "["; + for (UINT t = 0; t < count; ++t) { + out += t ? ",\n [" : "\n ["; + for (int k = 0; k < 3; ++k) + out += (k ? ", [" : "[") + num(soup[9 * t + 3 * k]) + ", " + num(soup[9 * t + 3 * k + 1]) + ", " + + num(soup[9 * t + 3 * k + 2]) + "]"; + out += ", 0, " + std::to_string(t) + "]"; + } + return out + "]"; + }; + const std::string triangles = triangle_list(tris); check(dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas", "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + ", \"triangles\": " + triangles + "}\n"), @@ -464,6 +509,18 @@ int main(int argc, char** argv) { "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) + ", \"triangles\": " + triangles + "}\n"), "the BLAS compacted through the shim is written for check-build"); + check(dump(zero_scratch_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas_rehydrated_zero_scratch", + "{\"kind\": \"blas\", \"address\": " + std::to_string(zero_scratch_as->GetGPUVirtualAddress()) + + ", \"triangles\": " + triangles + "}\n"), + "the BLAS rehydrated with the shim's scratch is written for check-build"); + for (int i = 0; i < 2; ++i) { + const std::string name = "shim_blas_rehydrated_batch" + std::to_string(i); + check(dump(pair_rb[i].p, blas_info.ResultDataMaxSizeInBytes, name, + "{\"kind\": \"blas\", \"address\": " + std::to_string(pair_as[i]->GetGPUVirtualAddress()) + + ", \"triangles\": " + triangle_list(pair_tris[i]) + "}\n"), + i ? "the batch's second element (its own scratch region) is written for check-build" + : "the batch's first element (its own scratch region) is written for check-build"); + } // ---- the destructor releases the builder ---- destruct(builder); diff --git a/tests/test_xbox_bvh_builder_rehydrate.py b/tests/test_xbox_bvh_builder_rehydrate.py index 8076a0e46a..9f207b4bb4 100644 --- a/tests/test_xbox_bvh_builder_rehydrate.py +++ b/tests/test_xbox_bvh_builder_rehydrate.py @@ -63,6 +63,25 @@ def test_test_harness_validates_rehydrate(self): self.assertIn("rehydrate(builder, list.p, 1, &source_only_desc, &source) == E_NOTIMPL", test_content) self.assertIn("rehydrate(builder, list.p, 1, &empty_desc, nullptr) == S_OK", test_content) self.assertIn("rehydrate(builder, list.p, 1, &zero_scratch_desc, &source) == S_OK", test_content) + self.assertIn("rehydrate(builder, list.p, 2, pair_desc, nullptr) == S_OK", test_content) + # The zero-scratch build and both batch elements are read back and handed to check-build. + for name in ("shim_blas_rehydrated_zero_scratch", "shim_blas_rehydrated_batch"): + self.assertIn(name, test_content) + + def test_scratch_regions_and_fresh_build(self): + content = XBOX_BVH_CPP.read_text(encoding="utf-8") + m = re.search(r"HRESULT builder_rehydrate_batched2x\([^)]*\)\s*\{(.*?)\n\}", content, re.DOTALL) + self.assertIsNotNone(m) + body = m.group(1) + # One scratch buffer per call, a region per element at the D3D12 alignment. + self.assertIn("rehydrate_scratch(self, device, list4, scratch_bytes)", body) + self.assertIn("D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT", body) + # The list holds the scratch until it is Reset; no buffer is kept or regrown on the builder. + self.assertIn("rt::d3d12::hold_until_reset(list, res)", content) + self.assertNotIn("builder_ensure_scratch", content) + # A rehydrate is a fresh build: the update flag and the source are cleared. + self.assertIn("&= ~D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE", body) + self.assertIn("build.SourceAccelerationStructureData = 0;", body) if __name__ == "__main__":