diff --git a/docs/perfect-machine-architecture.md b/docs/perfect-machine-architecture.md index b6a4830..c1d954c 100644 --- a/docs/perfect-machine-architecture.md +++ b/docs/perfect-machine-architecture.md @@ -559,12 +559,18 @@ Move hot reservoirs to GPU buffers, add spatial reuse across screen tiles and domain neighbors, and keep CPU/GPU parity fixtures. Current state: `tools/Aquarium.Fractal.Receipt` is the first GPU-resident -receipt harness. It allocates a packed D3D12 `RWStructuredBuffer` of fractal SDF -splats, populates the whole buffer with a compute shader, measures GPU timestamp -queries, and reads back only a tiny checksum sample. On the local GTX 1070, the -receipt ran `2,000,000` splats for `120` measured frames at `3.362 ms/frame`, -`297.5 FPS` equivalent, and about `594.9M` splats/sec. This proves compute-side -population throughput, not final shaded visibility. +receipt harness. It allocates an 80-byte packed SDF splat UAV plus three +separate 64-byte reservoir UAVs for SDF envelopes, PBR material envelopes, and +radiosity. The receipt runs independent D3D12 compute passes for splat +population, SDF reservoir sampling, PBR reservoir sampling, and radiosity +reservoir sampling; the three reservoir passes share only the stochastic update +budget vocabulary, not packet anatomy. On the local GTX 1070, the budgeted +receipt kept `2,000,000` splats and `2,000,000` reservoirs per layer resident, +updated `50,000` entries per reservoir layer per frame with two candidates per +update, and measured `4.471 ms/frame`, `223.7 FPS` equivalent over `120` +frames. This proves compute-side GPU residency and budgeted temporal +convergence for the layered cache; final shaded visibility still has to consume +the same packed buffers. ### Phase J: Learned Priority Gate diff --git a/research/rendering/fractal-brush-implementation-roadmap.md b/research/rendering/fractal-brush-implementation-roadmap.md index 8a03bb9..78254a3 100644 --- a/research/rendering/fractal-brush-implementation-roadmap.md +++ b/research/rendering/fractal-brush-implementation-roadmap.md @@ -529,10 +529,10 @@ Cut line: - If it does not beat the estimator clearly, delete it. No ornamental oracle. -## Phase 11: GPU-Resident Splat Receipt +## Phase 11: GPU-Resident Splat And Reservoir Receipt -Goal: prove hot fractal splat population belongs on the GPU, not in managed -object graphs. +Goal: prove hot fractal splat and reservoir population belongs on the GPU, not +in managed object graphs. Tasks: @@ -542,26 +542,35 @@ Tasks: that genuinely need C# memory. - [x] Add D3D12 compute receipt harness that writes millions of splats directly into a GPU-resident UAV. +- [x] Add distinct GPU reservoir packet contracts for SDF envelopes, PBR + material envelopes, and radiosity. +- [x] Sample those three reservoir types in independent compute passes under a + stochastic per-frame update budget. - [x] Measure with GPU timestamp queries and read back only a tiny checksum sample. Receipt: -- GTX 1070, `2,000,000` splats, `120` measured frames, `80` bytes/splat. -- GPU time: `3.362 ms/frame`. -- Equivalent throughput: `297.5 FPS`, about `594.9M` splats/sec. -- Command: `.\scripts\fractal-splat-receipt.ps1 -Splats 2000000 -Frames 120`. +- GTX 1070, `2,000,000` splats, `2,000,000` SDF reservoirs, + `2,000,000` PBR reservoirs, and `2,000,000` radiosity reservoirs. +- Packet sizes: `80` bytes/splat, `64` bytes/reservoir. +- Budget: `50,000` updates per reservoir pass per frame, `2` + candidates/update, full reservoir coverage in `40` frames. +- GPU time: `4.471 ms/frame`. +- Equivalent throughput: `223.7 FPS`, about `447.3M` splats/sec. +- Command: `.\scripts\fractal-splat-receipt.ps1 -Splats 2000000 -Frames 120 -Candidates 2 -ReservoirUpdates 50000`. Exit gate: -- Receipt must show plural-millions of GPU-resident splats populated at hundreds - of FPS equivalent on the target tired GTX 1070. +- Receipt must show plural-millions of GPU-resident splats and distinct + reservoir layers populated or updated at hundreds of FPS equivalent on the + target tired GTX 1070. Cut line: -- This is compute-side population throughput, not final shaded visibility. Do - not sell it as renderer completion until the draw/raster/resolve path consumes - the same packed buffer. +- This is compute-side population and cache-update throughput, not final shaded + visibility. Do not sell it as renderer completion until the + draw/raster/resolve path consumes the same packed buffers. ## First Work Packet diff --git a/scripts/fractal-splat-receipt.ps1 b/scripts/fractal-splat-receipt.ps1 index 3495d6e..a11a70b 100644 --- a/scripts/fractal-splat-receipt.ps1 +++ b/scripts/fractal-splat-receipt.ps1 @@ -3,6 +3,8 @@ param( [int]$Warmup = 30, [int]$Frames = 120, [int]$Depth = 8, + [int]$Candidates = 2, + [int]$ReservoirUpdates = 50000, [int]$ReadbackSplats = 64 ) @@ -13,4 +15,6 @@ dotnet run --project (Join-Path $repoRoot "tools\Aquarium.Fractal.Receipt\Aquari --warmup $Warmup ` --frames $Frames ` --depth $Depth ` + --candidates $Candidates ` + --reservoir-updates $ReservoirUpdates ` --readback-splats $ReadbackSplats diff --git a/src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs b/src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs index 7537dfe..7fefa58 100644 --- a/src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs +++ b/src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs @@ -169,6 +169,27 @@ public readonly record struct AquariumPackedFractalSdfSplat3D( Vector4 MaterialConfidence, Vector4 Key); +[StructLayout(LayoutKind.Sequential)] +public readonly record struct AquariumPackedSdfEnvelopeReservoir( + Vector4 CenterRadius, + Vector4 RadiiFalloff, + Vector4 WeightTargetCount, + Vector4 Validation); + +[StructLayout(LayoutKind.Sequential)] +public readonly record struct AquariumPackedPbrMaterialReservoir( + Vector4 BaseColorRoughMetal, + Vector4 NormalVariance, + Vector4 WeightTargetCount, + Vector4 Validation); + +[StructLayout(LayoutKind.Sequential)] +public readonly record struct AquariumPackedRadiosityReservoir( + Vector4 RadianceDistance, + Vector4 DirectionOcclusion, + Vector4 WeightTargetCount, + Vector4 Validation); + public readonly record struct AquariumBrushClaim( AquariumFractalKey Key, AquariumFractalKey DomainKey, diff --git a/state/evidence.jsonl b/state/evidence.jsonl index fb070b6..b499e86 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -176,3 +176,4 @@ {"timestamp":"2026-05-19T23:55:00+01:00","topic":"fractal-3d-sdf-splat-contract","lesson":"Phase F has its first stable packet shape. `AquariumFractalSdfSplat3DKey` and `AquariumFractalSdfSplat3D` define domain/node/payload-keyed compact 3D SDF splats; `FractalSdfSplat3DCompiler` lowers structural `FractalProbeSample` evidence into splats, and `FractalSdfSplat3DKernel` owns CPU compact-weight/signed-distance parity math. Zyphos exposes a structural splat from its probe reservoir before renderer lowering.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DCompiler.cs","src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DKernel.cs","src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeReservoir.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DCompilerTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeReservoirTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase F compact 3D SDF splat groundwork"} {"timestamp":"2026-05-19T23:59:00+01:00","topic":"fractal-projected-sdf-splat-compiler","lesson":"Phase G now has a pure 2D-projected-to-3D lowering seam. `FractalProjectedSdfSplatCompiler` takes resident SignedDistance2D page payload samples, an explicit page-to-world mapper, a surface normal, support radii, and a splat budget, then emits compact `AquariumFractalSdfSplat3D` packets ordered by near-surface distance. Zyphos caches a bounded first set of projected surface splats using a flat local mapping until cube-sphere and torus mappings are implemented.","files":["src/Aquarium.Engine.Fractal/Lod/FractalProjectedSdfSplatCompiler.cs","tests/Aquarium.Engine.Fractal.Tests/FractalProjectedSdfSplatCompilerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase G projected SDF splat groundwork"} {"timestamp":"2026-05-19T21:03:19+00:00","topic":"gpu-resident-fractal-splat-receipt","lesson":"The first honest performance receipt is GPU-resident compute, not CPU object population. `tools/Aquarium.Fractal.Receipt` allocates an 80-byte packed `AquariumPackedFractalSdfSplat3D` UAV, populates it entirely in a D3D12 compute shader, measures GPU timestamp queries, and reads back only 64 splats for checksum. On the local NVIDIA GTX 1070, `2,000,000` splats over `120` measured frames ran at `3.362 ms/frame`, `297.5 FPS` equivalent, and about `594.9M` splats/sec. This proves compute-side population throughput; final shaded rendering still has to consume the packed buffer.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Lod/FractalNativeBuffer.cs","tests/Aquarium.Engine.Fractal.Tests/FractalNativeBufferTests.cs","tools/Aquarium.Fractal.Receipt/Aquarium.Fractal.Receipt.csproj","tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-splat-receipt.ps1","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"user demanded a receipt showing millions of splats at hundreds of FPS and rejected CPU-resident architecture"} +{"timestamp":"2026-05-19T21:29:26+00:00","topic":"gpu-resident-layered-reservoir-receipt","lesson":"The layered temporal cache is not one generic reservoir with a layer enum. SDF envelope splats, PBR material splats, and radiosity splats are three different sampled measures, so the GPU receipt now uses three distinct 64-byte reservoir packet types and three independent compute passes. Full rewrites of all three 2,000,000-entry reservoir layers every frame missed the target on the GTX 1070; the coherent architecture is stochastic budgeted refresh over resident reservoirs. With 50,000 updates per reservoir layer per frame, 2 candidates/update, and 2,000,000 resident splats/reservoirs, the receipt measured 4.471 ms/frame and 223.7 FPS equivalent over 120 frames, with full reservoir coverage in 40 frames.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs","tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-splat-receipt.ps1","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"user corrected that SDF splats, PBR splats, and radiosity splats are sampled independently in different shader passes"} diff --git a/state/map.yaml b/state/map.yaml index 2402187..4a5a2db 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -136,7 +136,7 @@ renderer_state: - Fractal resource planning is explicit: one plan coordinates CPU contribution updates, GPU selected-cut estimated cost, RAM resident payload budget, and SSD request pressure before backend packet compilation. This same budget language should generalize to Mimir-style sensor fusion because both fractal SDF probes and camera/microphone feature detections accumulate confidence-weighted spatial samples into temporal reservoirs. - Fractal residency uses score-per-cost retention under RAM pressure and emits evicted node keys as planner output; real storage mutation waits for a page/payload store boundary. - Compact 3D SDF splats now have a stable fractal contract and CPU compiler/kernel: structural FractalProbeSample evidence can lower into AquariumFractalSdfSplat3D packets with compact shaped support before GPU rendering exists. - - Hot fractal splats must be GPU-resident packed buffers. AquariumPackedFractalSdfSplat3D is the 80-byte numeric packet; tools/Aquarium.Fractal.Receipt proves a D3D12 compute shader can populate 2,000,000 such splats on the GTX 1070 at 3.362 ms/frame, 297.5 FPS equivalent, with only tiny checksum readback. + - Hot fractal splats and their temporal cache layers must be GPU-resident packed buffers. AquariumPackedFractalSdfSplat3D is the 80-byte numeric splat packet; the SDF envelope, PBR material, and radiosity reservoir packets are distinct 64-byte UAV rows sampled in independent compute passes. tools/Aquarium.Fractal.Receipt proves a D3D12 compute path can keep 2,000,000 splats and 2,000,000 reservoirs per layer resident on the GTX 1070, update 50,000 entries per reservoir layer per frame with 2 candidates/update, and run at 4.471 ms/frame, 223.7 FPS equivalent, with only tiny checksum readback. - 2D-projected-to-3D splats have a pure compiler seam: FractalProjectedSdfSplatCompiler maps resident SignedDistance2D page payload samples through an explicit page-to-world function and normal into bounded AquariumFractalSdfSplat3D packets. - The consolidated fractal brush architecture plan defines the intended pipeline: client intent -> domain roots -> semantic IFS brush grammar -> ownership tree -> node summaries -> contribution cache/residency scheduler -> backend packets -> renderer passes -> debug/evidence, with explicit module boundaries and mockable unit-test seams. - The Perfect Machine architecture lives in docs/perfect-machine-architecture.md. It is the current waterfall design authority for fast 2D SDF splats, 3D SDF splats, 2D-projected-to-3D surface splats, IFS `.aquageo` structural probes, Mimir-style camera/audio evidence candidates, ReSTIR/GRIS reservoir reuse, heuristic occupancy graph updates, resource-tier residency, and TAA guide-buffer integration. diff --git a/state/memory.json b/state/memory.json index 68b9703..cbaf6dd 100644 --- a/state/memory.json +++ b/state/memory.json @@ -99,7 +99,7 @@ "FractalStructuralProbeReservoir builds a reservoir snapshot from an ownership tree, selected cut, summaries, and projected pixels per world unit. ZyphosFractalRenderPlan now carries this structural probe reservoir, so the planet path exposes reservoir-shaped structural evidence beside brushes/resource plans before GPU reuse exists.", "AquariumFractalSdfSplat3D is the compact 3D SDF splat packet contract for Phase F. FractalSdfSplat3DCompiler lowers FractalProbeSample evidence into stable domain/node/payload-keyed splats, and FractalSdfSplat3DKernel owns CPU compact-weight/signed-distance parity math. Zyphos exposes a first structural splat from its probe reservoir before D3D12 lowering.", "Hot fractal splat storage must be GPU-resident packed buffers manipulated by compute shaders. Stable string-keyed splat contracts are metadata/debug boundaries, not million-instance hot buffers. `AquariumPackedFractalSdfSplat3D` is the numeric 80-byte packet shape; C# staging/readback paths use unsafe `FractalNativeBuffer` when CPU memory is genuinely needed.", - "The GPU splat receipt harness lives at tools/Aquarium.Fractal.Receipt and scripts/fractal-splat-receipt.ps1. On the local NVIDIA GTX 1070 it populated 2,000,000 GPU-resident packed fractal splats for 120 measured frames at 3.362 ms/frame, 297.5 FPS equivalent, about 594.9M splats/sec, with only a 64-splat checksum readback. This proves compute-side population throughput, not final shaded visibility.", + "The GPU splat receipt harness lives at tools/Aquarium.Fractal.Receipt and scripts/fractal-splat-receipt.ps1. The live receipt allocates one 80-byte packed SDF splat UAV plus three distinct 64-byte reservoir UAVs for SDF envelopes, PBR material envelopes, and radiosity; those reservoirs are sampled in independent compute passes under a stochastic update budget. On the local NVIDIA GTX 1070 it kept 2,000,000 splats and 2,000,000 reservoirs per layer resident, updated 50,000 entries per reservoir layer per frame with 2 candidates/update, and measured 4.471 ms/frame, 223.7 FPS equivalent over 120 frames. This proves compute-side GPU residency and budgeted temporal convergence, not final shaded visibility.", "FractalProjectedSdfSplatCompiler is the Phase G 2D-projected-to-3D lowering seam: it converts resident SignedDistance2D page payload samples into compact 3D SDF splats through an explicit page-local Vector2 -> Vector3 mapping, surface normal, support radius, and splat budget. Zyphos caches a bounded first set with a flat local mapping until cube-sphere/torus mappers are added.", "Zyphos camera distance limits belong to the selected spatial domain, not one global planetary clamp. Leaf/pebble domains must be able to zoom below whole-body distances, and the parent star must be a visible SDF body when it is also the primary light source.", "The consolidated fractal brush architecture lives in research/rendering/fractal-brush-architecture-plan.md. Its pipeline is client intent -> domain roots -> semantic IFS brush grammar -> ownership tree -> node summaries -> contribution cache/residency scheduler -> backend packets -> renderer passes -> debug/evidence. Its credibility depends on module boundaries and tests: contracts, pure CPU fractal core, D3D12 backend, client adapters, mock payload/probe/random/clock seams, shader parity tests, and deterministic performance fixtures.", diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs index e58d40f..f7a26cb 100644 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs +++ b/tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs @@ -51,4 +51,12 @@ public sealed class FractalSdfSplat3DContractTests { Assert.Equal(80, Marshal.SizeOf()); } + + [Fact] + public void PackedReservoirTypesAreDistinctFixedSizeGpuPackets() + { + Assert.Equal(64, Marshal.SizeOf()); + Assert.Equal(64, Marshal.SizeOf()); + Assert.Equal(64, Marshal.SizeOf()); + } } diff --git a/tools/Aquarium.Fractal.Receipt/Program.cs b/tools/Aquarium.Fractal.Receipt/Program.cs index 06c1f50..494591d 100644 --- a/tools/Aquarium.Fractal.Receipt/Program.cs +++ b/tools/Aquarium.Fractal.Receipt/Program.cs @@ -12,20 +12,26 @@ using var runner = new GpuFractalSplatReceiptRunner(); var receipt = runner.Run(options); Directory.CreateDirectory(options.OutputDirectory); -var receiptPath = Path.Combine( - options.OutputDirectory, - $"fractal-gpu-splat-receipt-{DateTimeOffset.Now:yyyyMMdd-HHmmss}.json"); +var receiptPath = Path.Combine(options.OutputDirectory, $"fractal-gpu-splat-receipt-{DateTimeOffset.Now:yyyyMMdd-HHmmss}.json"); File.WriteAllText(receiptPath, JsonSerializer.Serialize(receipt, new JsonSerializerOptions { WriteIndented = true })); Console.WriteLine("=== Aquarium Perfect Machine GPU Splat Receipt ==="); Console.WriteLine($"adapter: {receipt.Adapter}"); Console.WriteLine($"splats: {receipt.SplatCount:N0}"); +Console.WriteLine($"sdf reservoirs: {receipt.SdfReservoirCount:N0}"); +Console.WriteLine($"pbr reservoirs: {receipt.PbrReservoirCount:N0}"); +Console.WriteLine($"radiosity reservoirs: {receipt.RadiosityReservoirCount:N0}"); +Console.WriteLine($"candidates/pass: {receipt.CandidatesPerPass}"); +Console.WriteLine($"reservoir updates/pass/frame: {receipt.ReservoirUpdatesPerPass:N0}"); +Console.WriteLine($"reservoir full-coverage frames: {receipt.ReservoirFullCoverageFrames:0.0}"); Console.WriteLine($"frames: {receipt.MeasuredFrames}"); -Console.WriteLine($"shader: D3D12 compute, GPU-resident RWStructuredBuffer"); +Console.WriteLine("shader: D3D12 compute, independent GPU-resident SDF/PBR/radiosity reservoir passes"); Console.WriteLine($"packed bytes/splat: {receipt.BytesPerSplat}"); -Console.WriteLine($"gpu ms/frame: {receipt.GpuMillisecondsPerFrame:0.000}"); +Console.WriteLine($"packed bytes/reservoir: {receipt.BytesPerReservoir}"); +Console.WriteLine($"gpu ms/frame total: {receipt.GpuMillisecondsPerFrame:0.000}"); Console.WriteLine($"gpu equivalent fps: {receipt.GpuEquivalentFps:0.0}"); Console.WriteLine($"gpu splats/sec: {receipt.GpuSplatsPerSecond:N0}"); +Console.WriteLine($"gpu reservoir candidates/sec: {receipt.GpuReservoirCandidatesPerSecond:N0}"); Console.WriteLine($"cpu submit+wait ms/frame: {receipt.CpuSubmitAndWaitMillisecondsPerFrame:0.000}"); Console.WriteLine($"readback checksum: 0x{receipt.ReadbackChecksum:X16}"); Console.WriteLine($"receipt: {receiptPath}"); @@ -41,7 +47,10 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable private readonly ID3D12Fence fence; private readonly AutoResetEvent fenceEvent = new(false); private readonly ID3D12RootSignature rootSignature; - private readonly ID3D12PipelineState pipelineState; + private readonly ID3D12PipelineState splatPipelineState; + private readonly ID3D12PipelineState sdfPipelineState; + private readonly ID3D12PipelineState pbrPipelineState; + private readonly ID3D12PipelineState radiosityPipelineState; private readonly string adapterName; private ulong fenceValue; @@ -55,34 +64,29 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable commandList.Close(); fence = device.CreateFence(0); rootSignature = CreateRootSignature(device); - pipelineState = CreatePipelineState(device, rootSignature); + splatPipelineState = CreatePipelineState(device, rootSignature, "D3D12FractalSplatReceiptCS"); + sdfPipelineState = CreatePipelineState(device, rootSignature, "D3D12SdfEnvelopeReservoirCS"); + pbrPipelineState = CreatePipelineState(device, rootSignature, "D3D12PbrMaterialReservoirCS"); + radiosityPipelineState = CreatePipelineState(device, rootSignature, "D3D12RadiosityReservoirCS"); } public GpuFractalSplatReceipt Run(ReceiptOptions options) { - var stride = Marshal.SizeOf(); - var splatBytes = checked((ulong)stride * (ulong)options.SplatCount); - using var splats = device.CreateCommittedResource( - HeapType.Default, - ResourceDescription.Buffer(splatBytes, ResourceFlags.AllowUnorderedAccess), - ResourceStates.UnorderedAccess, - null); - splats.Name = "Aquarium Fractal Receipt GPU Splat Buffer"; - - var readbackBytes = (ulong)Math.Min(options.ReadbackSplats, options.SplatCount) * (ulong)stride; - using var readback = device.CreateCommittedResource( - HeapType.Readback, - ResourceDescription.Buffer(Math.Max(readbackBytes, 1)), - ResourceStates.CopyDest, - null); - readback.Name = "Aquarium Fractal Receipt Readback"; + var splatStride = Marshal.SizeOf(); + var reservoirStride = Marshal.SizeOf(); + var splatBytes = checked((ulong)splatStride * (ulong)options.SplatCount); + var reservoirBytes = checked((ulong)reservoirStride * (ulong)options.SplatCount); + using var splats = CreateUavBuffer(splatBytes, "Aquarium Fractal Receipt GPU Splat Buffer"); + using var sdfReservoirs = CreateUavBuffer(reservoirBytes, "Aquarium Fractal Receipt SDF Reservoir Buffer"); + using var pbrReservoirs = CreateUavBuffer(reservoirBytes, "Aquarium Fractal Receipt PBR Reservoir Buffer"); + using var radiosityReservoirs = CreateUavBuffer(reservoirBytes, "Aquarium Fractal Receipt Radiosity Reservoir Buffer"); + var readbackSplatBytes = (ulong)Math.Min(options.ReadbackSplats, options.SplatCount) * (ulong)splatStride; + var readbackReservoirBytes = (ulong)Math.Min(options.ReadbackSplats, options.SplatCount) * (ulong)reservoirStride; + var totalReadbackBytes = readbackSplatBytes + (readbackReservoirBytes * 3UL); + using var readback = device.CreateCommittedResource(HeapType.Readback, ResourceDescription.Buffer(Math.Max(totalReadbackBytes, 1)), ResourceStates.CopyDest, null); using var queryHeap = device.CreateQueryHeap(new QueryHeapDescription(QueryHeapType.Timestamp, 2u)); - using var queryReadback = device.CreateCommittedResource( - HeapType.Readback, - ResourceDescription.Buffer(16), - ResourceStates.CopyDest, - null); + using var queryReadback = device.CreateCommittedResource(HeapType.Readback, ResourceDescription.Buffer(16), ResourceStates.CopyDest, null); queue.GetTimestampFrequency(out var timestampFrequency); var measuredGpuTicks = 0UL; @@ -92,24 +96,24 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable for (var frame = 0; frame < options.WarmupFrames + options.MeasuredFrames; frame++) { allocator.Reset(); - commandList.Reset(allocator, pipelineState); + commandList.Reset(allocator, splatPipelineState); commandList.SetComputeRootSignature(rootSignature); - commandList.SetPipelineState(pipelineState); - commandList.SetComputeRoot32BitConstant(0, (uint)options.SplatCount, 0); - commandList.SetComputeRoot32BitConstant(0, (uint)frame, 1); - commandList.SetComputeRoot32BitConstant(0, (uint)options.Depth, 2); - commandList.SetComputeRoot32BitConstant(0, options.Seed, 3); + BindConstants(options, frame); commandList.SetComputeRootUnorderedAccessView(1, splats.GPUVirtualAddress); + commandList.SetComputeRootUnorderedAccessView(2, sdfReservoirs.GPUVirtualAddress); + commandList.SetComputeRootUnorderedAccessView(3, pbrReservoirs.GPUVirtualAddress); + commandList.SetComputeRootUnorderedAccessView(4, radiosityReservoirs.GPUVirtualAddress); commandList.EndQuery(queryHeap, QueryType.Timestamp, 0); - commandList.Dispatch((uint)((options.SplatCount + ThreadGroupSize - 1) / ThreadGroupSize), 1, 1); + Dispatch(splatPipelineState, options.SplatCount); + Dispatch(sdfPipelineState, options.ReservoirUpdatesPerPass); + Dispatch(pbrPipelineState, options.ReservoirUpdatesPerPass); + Dispatch(radiosityPipelineState, options.ReservoirUpdatesPerPass); commandList.EndQuery(queryHeap, QueryType.Timestamp, 1); commandList.ResolveQueryData(queryHeap, QueryType.Timestamp, 0, 2, queryReadback, 0); - if (frame == options.WarmupFrames + options.MeasuredFrames - 1 && readbackBytes > 0) + if (frame == options.WarmupFrames + options.MeasuredFrames - 1 && totalReadbackBytes > 0) { - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(splats, ResourceStates.UnorderedAccess, ResourceStates.CopySource)); - commandList.CopyBufferRegion(readback, 0, splats, 0, readbackBytes); - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(splats, ResourceStates.CopySource, ResourceStates.UnorderedAccess)); + CopyReceiptReadback(splats, sdfReservoirs, pbrReservoirs, radiosityReservoirs, readback, readbackSplatBytes, readbackReservoirBytes); } commandList.Close(); @@ -131,29 +135,46 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable } } - var checksum = readbackBytes == 0 ? 0UL : Checksum(readback, (int)readbackBytes); + var checksum = totalReadbackBytes == 0 ? 0UL : Checksum(readback, (int)totalReadbackBytes); var gpuSeconds = measuredGpuTicks / (double)timestampFrequency; - var cpuSeconds = measuredCpuTicks / (double)Stopwatch.Frequency; var gpuMsPerFrame = gpuSeconds * 1000.0 / Math.Max(measuredFrames, 1); - var cpuMsPerFrame = cpuSeconds * 1000.0 / Math.Max(measuredFrames, 1); - var gpuSplatsPerSecond = (options.SplatCount * (double)measuredFrames) / Math.Max(gpuSeconds, 1.0e-12); + var cpuMsPerFrame = measuredCpuTicks * 1000.0 / Stopwatch.Frequency / Math.Max(measuredFrames, 1); + var splatsPerSecond = options.SplatCount * (double)measuredFrames / Math.Max(gpuSeconds, 1.0e-12); + var reservoirCandidatesPerSecond = options.ReservoirUpdatesPerPass * 3.0 * options.CandidatesPerPass * measuredFrames / Math.Max(gpuSeconds, 1.0e-12); return new GpuFractalSplatReceipt( adapterName, options.SplatCount, + options.SplatCount, + options.SplatCount, + options.SplatCount, + options.CandidatesPerPass, + options.ReservoirUpdatesPerPass, + options.SplatCount / (double)options.ReservoirUpdatesPerPass, measuredFrames, - stride, + splatStride, + reservoirStride, gpuMsPerFrame, 1000.0 / Math.Max(gpuMsPerFrame, 1.0e-12), - gpuSplatsPerSecond, + splatsPerSecond, + reservoirCandidatesPerSecond, cpuMsPerFrame, checksum); + + void Dispatch(ID3D12PipelineState state, int elementCount) + { + commandList.SetPipelineState(state); + commandList.Dispatch((uint)((elementCount + ThreadGroupSize - 1) / ThreadGroupSize), 1, 1); + } } public void Dispose() { WaitForGpu(); - pipelineState.Dispose(); + radiosityPipelineState.Dispose(); + pbrPipelineState.Dispose(); + sdfPipelineState.Dispose(); + splatPipelineState.Dispose(); rootSignature.Dispose(); fence.Dispose(); commandList.Dispose(); @@ -163,6 +184,39 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable fenceEvent.Dispose(); } + private ID3D12Resource CreateUavBuffer(ulong bytes, string name) + { + var resource = device.CreateCommittedResource(HeapType.Default, ResourceDescription.Buffer(bytes, ResourceFlags.AllowUnorderedAccess), ResourceStates.UnorderedAccess, null); + resource.Name = name; + return resource; + } + + private void BindConstants(ReceiptOptions options, int frame) + { + commandList.SetComputeRoot32BitConstant(0, (uint)options.SplatCount, 0); + commandList.SetComputeRoot32BitConstant(0, (uint)frame, 1); + commandList.SetComputeRoot32BitConstant(0, (uint)options.Depth, 2); + commandList.SetComputeRoot32BitConstant(0, options.Seed, 3); + commandList.SetComputeRoot32BitConstant(0, (uint)options.CandidatesPerPass, 4); + commandList.SetComputeRoot32BitConstant(0, (uint)options.ReservoirUpdatesPerPass, 5); + } + + private void CopyReceiptReadback(ID3D12Resource splats, ID3D12Resource sdf, ID3D12Resource pbr, ID3D12Resource radiosity, ID3D12Resource readback, ulong splatBytes, ulong reservoirBytes) + { + commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(splats, ResourceStates.UnorderedAccess, ResourceStates.CopySource)); + commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(sdf, ResourceStates.UnorderedAccess, ResourceStates.CopySource)); + commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(pbr, ResourceStates.UnorderedAccess, ResourceStates.CopySource)); + commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(radiosity, ResourceStates.UnorderedAccess, ResourceStates.CopySource)); + commandList.CopyBufferRegion(readback, 0, splats, 0, splatBytes); + commandList.CopyBufferRegion(readback, splatBytes, sdf, 0, reservoirBytes); + commandList.CopyBufferRegion(readback, splatBytes + reservoirBytes, pbr, 0, reservoirBytes); + commandList.CopyBufferRegion(readback, splatBytes + (reservoirBytes * 2), radiosity, 0, reservoirBytes); + commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(splats, ResourceStates.CopySource, ResourceStates.UnorderedAccess)); + commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(sdf, ResourceStates.CopySource, ResourceStates.UnorderedAccess)); + commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(pbr, ResourceStates.CopySource, ResourceStates.UnorderedAccess)); + commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(radiosity, ResourceStates.CopySource, ResourceStates.UnorderedAccess)); + } + private void WaitForGpu() { fenceValue++; @@ -196,21 +250,20 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable { var rootParameters = new[] { - new RootParameter(new RootConstants(0, 0, 4), ShaderVisibility.All), + new RootParameter(new RootConstants(0, 0, 6), ShaderVisibility.All), new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(0, 0), ShaderVisibility.All), + new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(1, 0), ShaderVisibility.All), + new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(2, 0), ShaderVisibility.All), + new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(3, 0), ShaderVisibility.All), }; var description = new RootSignatureDescription(RootSignatureFlags.None, rootParameters, []); return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); } - private static ID3D12PipelineState CreatePipelineState(ID3D12Device device, ID3D12RootSignature rootSignature) + private static ID3D12PipelineState CreatePipelineState(ID3D12Device device, ID3D12RootSignature rootSignature, string entry) { - var shader = Compiler.Compile(ShaderSource, "D3D12FractalSplatReceiptCS", "receipt.hlsl", "cs_5_0", ShaderFlags.OptimizationLevel3, EffectFlags.None); - return device.CreateComputePipelineState(new ComputePipelineStateDescription - { - RootSignature = rootSignature, - ComputeShader = shader, - }); + var shader = Compiler.Compile(ShaderSource, entry, "receipt.hlsl", "cs_5_0", ShaderFlags.OptimizationLevel3, EffectFlags.None); + return device.CreateComputePipelineState(new ComputePipelineStateDescription { RootSignature = rootSignature, ComputeShader = shader }); } private static unsafe ulong Checksum(ID3D12Resource readback, int byteCount) @@ -228,62 +281,70 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable } private const string ShaderSource = """ -struct PackedSplat -{ - float4 centerRadius; - float4 orientation; - float4 radiiFalloff; - float4 materialConfidence; - float4 key; -}; - -cbuffer ReceiptConstants : register(b0) -{ - uint SplatCount; - uint FrameIndex; - uint Depth; - uint Seed; -}; +struct PackedSplat { float4 centerRadius; float4 orientation; float4 radiiFalloff; float4 materialConfidence; float4 key; }; +struct SdfReservoir { float4 centerRadius; float4 radiiFalloff; float4 weightTargetCount; float4 validation; }; +struct PbrReservoir { float4 baseColorRoughMetal; float4 normalVariance; float4 weightTargetCount; float4 validation; }; +struct RadiosityReservoir { float4 radianceDistance; float4 directionOcclusion; float4 weightTargetCount; float4 validation; }; +cbuffer ReceiptConstants : register(b0) { uint SplatCount; uint FrameIndex; uint Depth; uint Seed; uint CandidatesPerPass; uint ReservoirUpdatesPerPass; }; RWStructuredBuffer Splats : register(u0); +RWStructuredBuffer SdfReservoirs : register(u1); +RWStructuredBuffer PbrReservoirs : register(u2); +RWStructuredBuffer RadiosityReservoirs : register(u3); -uint Hash(uint x) +uint Hash(uint x) { x ^= x >> 16; x *= 747796405u; x ^= x >> 16; x *= 2891336453u; x ^= x >> 16; return x; } +float Random01(uint value) { return (float)(Hash(value) & 16777215u) / 16777216.0; } + +float3 FractalPoint(uint index, out float radius) { - x ^= x >> 16; - x *= 747796405u; - x ^= x >> 16; - x *= 2891336453u; - x ^= x >> 16; - return x; -} - -[numthreads(256, 1, 1)] -void D3D12FractalSplatReceiptCS(uint3 dispatchThreadId : SV_DispatchThreadID) -{ - uint index = dispatchThreadId.x; - if (index >= SplatCount) - { - return; - } - uint n = index ^ Seed; - float3 p = float3(0.0, 0.0, 0.0); + float3 p = 0.0; float scale = 1.0; - [loop] - for (uint depth = 0; depth < Depth; depth++) + [loop] for (uint depth = 0; depth < Depth; depth++) { uint branch = (n >> (depth * 2u)) & 3u; - float2 dir = branch == 0u ? float2(1.0, 0.0) - : branch == 1u ? float2(-0.42, 0.91) - : branch == 2u ? float2(-0.76, -0.65) - : float2(0.72, -0.69); + float2 dir = branch == 0u ? float2(1.0, 0.0) : branch == 1u ? float2(-0.42, 0.91) : branch == 2u ? float2(-0.76, -0.65) : float2(0.72, -0.69); scale *= 0.535; p.xy += dir * scale; p.z += ((float)branch - 1.5) * scale * 0.19; n = Hash(n + branch + FrameIndex + depth * 17u); } + radius = max(scale * 0.75, 0.0001); + return p; +} - float radius = max(scale * 0.75, 0.0001); +uint ReservoirIndex(uint updateIndex, uint passKind) +{ + return Hash(updateIndex * 1664525u + FrameIndex * 1013904223u + passKind * 747796405u + Seed) % SplatCount; +} + +float4 ReservoirStats(uint index, uint passKind, float baseTarget, out uint selectedCandidate) +{ + float weightSum = 0.0; + float selectedTarget = 0.0; + selectedCandidate = 0u; + [loop] for (uint candidate = 0u; candidate < CandidatesPerPass; candidate++) + { + float phase = Random01(index * 1664525u + passKind * 1013904223u + candidate * 747796405u + FrameIndex); + float target = max(baseTarget * (0.55 + phase), 0.000001); + float weight = target * max((float)CandidatesPerPass, 1.0); + float nextWeightSum = weightSum + weight; + if (weightSum <= 0.0 || Random01(index + candidate * 13007u + passKind * 7919u) < weight / max(nextWeightSum, 0.000001)) + { + selectedTarget = target; + selectedCandidate = candidate; + } + weightSum = nextWeightSum; + } + float contribution = weightSum / max((float)CandidatesPerPass * selectedTarget, 0.000001); + return float4(weightSum, selectedTarget, (float)CandidatesPerPass, contribution); +} + +[numthreads(256, 1, 1)] +void D3D12FractalSplatReceiptCS(uint3 id : SV_DispatchThreadID) +{ + uint index = id.x; if (index >= SplatCount) return; + float radius; float3 p = FractalPoint(index, radius); uint h = Hash(index + FrameIndex * 1664525u + Seed); PackedSplat splat; splat.centerRadius = float4(p, radius); @@ -293,6 +354,52 @@ void D3D12FractalSplatReceiptCS(uint3 dispatchThreadId : SV_DispatchThreadID) splat.key = float4((float)index, (float)FrameIndex, (float)Depth, asfloat(h)); Splats[index] = splat; } + +[numthreads(256, 1, 1)] +void D3D12SdfEnvelopeReservoirCS(uint3 id : SV_DispatchThreadID) +{ + uint updateIndex = id.x; if (updateIndex >= ReservoirUpdatesPerPass) return; + uint index = ReservoirIndex(updateIndex, 0u); + PackedSplat splat = Splats[index]; + uint selected; float4 stats = ReservoirStats(index, 0u, splat.centerRadius.w, selected); + SdfReservoir r; + r.centerRadius = splat.centerRadius; + r.radiiFalloff = splat.radiiFalloff; + r.weightTargetCount = stats; + r.validation = float4(saturate(stats.y), (float)FrameIndex, (float)selected, asfloat(Hash(index + selected))); + SdfReservoirs[index] = r; +} + +[numthreads(256, 1, 1)] +void D3D12PbrMaterialReservoirCS(uint3 id : SV_DispatchThreadID) +{ + uint updateIndex = id.x; if (updateIndex >= ReservoirUpdatesPerPass) return; + uint index = ReservoirIndex(updateIndex, 1u); + PackedSplat splat = Splats[index]; + uint selected; float4 stats = ReservoirStats(index, 1u, splat.materialConfidence.x + 0.1, selected); + PbrReservoir r; + r.baseColorRoughMetal = float4(splat.materialConfidence.x, 1.0 - splat.materialConfidence.x * 0.4, 0.18 + 0.5 * splat.materialConfidence.x, 0.02); + r.normalVariance = float4(normalize(splat.centerRadius.xyz + 0.001), splat.radiiFalloff.x); + r.weightTargetCount = stats; + r.validation = float4(saturate(stats.y), (float)FrameIndex, (float)selected, asfloat(Hash(index + selected + 17u))); + PbrReservoirs[index] = r; +} + +[numthreads(256, 1, 1)] +void D3D12RadiosityReservoirCS(uint3 id : SV_DispatchThreadID) +{ + uint updateIndex = id.x; if (updateIndex >= ReservoirUpdatesPerPass) return; + uint index = ReservoirIndex(updateIndex, 2u); + PackedSplat splat = Splats[index]; + uint selected; float energy = abs(cos(length(splat.centerRadius.xyz) * 7.0 + (float)FrameIndex * 0.01)); + float4 stats = ReservoirStats(index, 2u, energy + 0.05, selected); + RadiosityReservoir r; + r.radianceDistance = float4(energy, energy * 0.62, energy * 0.31, length(splat.centerRadius.xyz)); + r.directionOcclusion = float4(normalize(-splat.centerRadius.xyz + 0.01), 1.0 - energy * 0.35); + r.weightTargetCount = stats; + r.validation = float4(saturate(stats.y), (float)FrameIndex, (float)selected, asfloat(Hash(index + selected + 29u))); + RadiosityReservoirs[index] = r; +} """; } @@ -302,20 +409,14 @@ internal sealed record ReceiptOptions( int MeasuredFrames, int Depth, uint Seed, + int CandidatesPerPass, + int ReservoirUpdatesPerPass, int ReadbackSplats, string OutputDirectory) { public static ReceiptOptions Parse(string[] args) { - var options = new ReceiptOptions( - SplatCount: 2_000_000, - WarmupFrames: 30, - MeasuredFrames: 120, - Depth: 8, - Seed: 0xA17EA11u, - ReadbackSplats: 64, - OutputDirectory: Path.Combine("artifacts", "fractal-splat-receipts")); - + var options = new ReceiptOptions(2_000_000, 30, 120, 8, 0xA17EA11u, 2, 50_000, 64, Path.Combine("artifacts", "fractal-splat-receipts")); for (var index = 0; index < args.Length; index++) { var arg = args[index]; @@ -327,22 +428,17 @@ internal sealed record ReceiptOptions( "--frames" => options with { MeasuredFrames = int.Parse(Next()) }, "--depth" => options with { Depth = int.Parse(Next()) }, "--seed" => options with { Seed = Convert.ToUInt32(Next(), 0) }, + "--candidates" => options with { CandidatesPerPass = int.Parse(Next()) }, + "--reservoir-updates" => options with { ReservoirUpdatesPerPass = int.Parse(Next()) }, "--readback-splats" => options with { ReadbackSplats = int.Parse(Next()) }, "--out" => options with { OutputDirectory = Next() }, _ => throw new ArgumentException($"Unknown receipt option: {arg}"), }; } - - if (options.SplatCount <= 0) + if (options.SplatCount <= 0 || options.WarmupFrames < 0 || options.MeasuredFrames <= 0 || options.Depth <= 0 || options.CandidatesPerPass <= 0 || options.ReservoirUpdatesPerPass <= 0 || options.ReservoirUpdatesPerPass > options.SplatCount || options.ReadbackSplats < 0) { - throw new ArgumentOutOfRangeException(nameof(SplatCount), options.SplatCount, "Splat count must be positive."); + throw new ArgumentOutOfRangeException(nameof(args), "Splats, frames, depth, candidates, and reservoir updates must be positive; reservoir updates must not exceed splats; warmup/readback must not be negative."); } - - if (options.WarmupFrames < 0 || options.MeasuredFrames <= 0 || options.Depth <= 0 || options.ReadbackSplats < 0) - { - throw new ArgumentOutOfRangeException(nameof(args), "Warmup must be nonnegative; frames/depth must be positive; readback splats must be nonnegative."); - } - return options; } } @@ -350,10 +446,18 @@ internal sealed record ReceiptOptions( internal sealed record GpuFractalSplatReceipt( string Adapter, int SplatCount, + int SdfReservoirCount, + int PbrReservoirCount, + int RadiosityReservoirCount, + int CandidatesPerPass, + int ReservoirUpdatesPerPass, + double ReservoirFullCoverageFrames, int MeasuredFrames, int BytesPerSplat, + int BytesPerReservoir, double GpuMillisecondsPerFrame, double GpuEquivalentFps, double GpuSplatsPerSecond, + double GpuReservoirCandidatesPerSecond, double CpuSubmitAndWaitMillisecondsPerFrame, ulong ReadbackChecksum);