From f30525cc68c1c6ce9c3e2bf94df63834f655e8b2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 9 May 2026 21:26:36 +0100 Subject: [PATCH] Make view froxel bootstrap conservative --- src/Aquarium.Engine/Render/D3D12Renderer.cs | 320 +++--------------- .../Render/Shaders/D3D12Scene.hlsl | 15 +- state/evidence.jsonl | 1 + state/memory.json | 1 + state/scratch.md | 11 +- 5 files changed, 62 insertions(+), 286 deletions(-) diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index eafdb1d..469d457 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -27,6 +27,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private const int MediumFroxelAtlasColumns = 8; private const int MediumFroxelAtlasRows = 4; private const int MediumFroxelSliceCount = MediumFroxelAtlasColumns * MediumFroxelAtlasRows; + private const int ViewFroxelPrimitiveSlotCount = 2; private const Format MediumVolumeFormat = Format.R16G16B16A16_Float; private const Format GridHeightFormat = Format.R16_Float; private const int PlanetCount = 5; @@ -593,10 +594,10 @@ public sealed class D3D12Renderer : IAquariumRenderer private D3D12StructuredBuffer CreateViewFroxelPrimitiveBuffer() { - froxelPrimitiveIds = new Int4[ViewFroxelCount]; + froxelPrimitiveIds = new Int4[ViewFroxelCount * ViewFroxelPrimitiveSlotCount]; return new D3D12StructuredBuffer( device, - ViewFroxelCount, + froxelPrimitiveIds.Length, Marshal.SizeOf(), "Aquarium D3D12 View-Froxel Primitive Buffer"); } @@ -1202,77 +1203,18 @@ public sealed class D3D12Renderer : IAquariumRenderer private void AddPrimitiveToFroxels(AquariumFrame frame, int primitiveId, Vector3 center, float boundRadius) { - var gridOrigin = new Vector3(frame.Grid.Center.X, frame.Grid.Center.Y, 0.0f); - var farDistance = Vector3.Distance(frame.CameraPosition, gridOrigin) + MathF.Max(frame.Grid.Radius, 0.001f); - for (var y = 0; y < mediumFroxelHeight; y++) + _ = frame; + _ = center; + _ = boundRadius; + for (var viewFroxelIndex = 0; viewFroxelIndex < ViewFroxelCount; viewFroxelIndex++) { - for (var x = 0; x < mediumFroxelWidth; x++) - { - if (!TraceViewFroxelSphere( - frame.CameraPosition, - frame.Grid.Center, - x, - y, - center, - boundRadius, - out var enterTravel, - out var exitTravel)) - { - continue; - } - - enterTravel = Math.Clamp(enterTravel, 0.0f, farDistance); - exitTravel = Math.Clamp(exitTravel, 0.0f, farDistance); - if (exitTravel <= enterTravel) - { - continue; - } - - var firstSlice = ClampCell(enterTravel / farDistance, MediumFroxelSliceCount); - var lastSlice = ClampCell(exitTravel / farDistance, MediumFroxelSliceCount); - for (var slice = firstSlice; slice <= lastSlice; slice++) - { - AddPrimitiveToViewFroxel(ViewFroxelIndex(x, y, slice), primitiveId); - } - } + AddPrimitiveToViewFroxel(viewFroxelIndex, primitiveId); } } private void AddPrimitiveToViewFroxel(int viewFroxelIndex, int primitiveId) { - var element = froxelPrimitiveIds[viewFroxelIndex]; - if (element.X == primitiveId || element.Y == primitiveId || element.Z == primitiveId || element.W == primitiveId) - { - return; - } - - if (element.X == -1) - { - froxelPrimitiveIds[viewFroxelIndex] = element with { X = primitiveId }; - return; - } - - if (element.Y == -1) - { - froxelPrimitiveIds[viewFroxelIndex] = element with { Y = primitiveId }; - return; - } - - if (element.Z == -1) - { - froxelPrimitiveIds[viewFroxelIndex] = element with { Z = primitiveId }; - return; - } - - if (element.W == -1) - { - froxelPrimitiveIds[viewFroxelIndex] = element with { W = primitiveId }; - } - } - - private static int ClampCell(float normalized, int count) - { - return Math.Clamp((int)MathF.Floor(normalized * count), 0, count - 1); + AddIdToInt4Slots(froxelPrimitiveIds, viewFroxelIndex * ViewFroxelPrimitiveSlotCount, ViewFroxelPrimitiveSlotCount, primitiveId); } private void BuildFieldInstanceTable(AquariumFrame frame) @@ -1352,225 +1294,51 @@ public sealed class D3D12Renderer : IAquariumRenderer new Vector4(2.0f, 10.0f, 0.055f, 0.090f), new Vector4(0.30f, 0.90f, 0.82f, 0.24f)); - var min = new Vector3( - frame.Grid.Center.X - frame.Grid.Radius, - frame.Grid.Center.Y - frame.Grid.Radius, - GridTransparentMinZ); - var max = new Vector3( - frame.Grid.Center.X + frame.Grid.Radius, - frame.Grid.Center.Y + frame.Grid.Radius, - GridTransparentMaxZ); - var gridOrigin = new Vector3(frame.Grid.Center.X, frame.Grid.Center.Y, 0.0f); - var farDistance = Vector3.Distance(frame.CameraPosition, gridOrigin) + MathF.Max(frame.Grid.Radius, 0.001f); - for (var y = 0; y < mediumFroxelHeight; y++) + for (var viewFroxelIndex = 0; viewFroxelIndex < ViewFroxelCount; viewFroxelIndex++) { - for (var x = 0; x < mediumFroxelWidth; x++) - { - if (!TraceViewFroxelSlab( - frame.CameraPosition, - frame.Grid.Center, - x, - y, - min, - max, - out var enterTravel, - out var exitTravel)) - { - continue; - } - - enterTravel = Math.Clamp(enterTravel, 0.0f, farDistance); - exitTravel = Math.Clamp(exitTravel, 0.0f, farDistance); - if (exitTravel <= enterTravel) - { - continue; - } - - var firstSlice = ClampCell(enterTravel / farDistance, MediumFroxelSliceCount); - var lastSlice = ClampCell(exitTravel / farDistance, MediumFroxelSliceCount); - for (var slice = firstSlice; slice <= lastSlice; slice++) - { - AddTransparentSurfaceToViewFroxel(ViewFroxelIndex(x, y, slice), 0); - } - } + AddTransparentSurfaceToViewFroxel(viewFroxelIndex, 0); } } - private bool TraceViewFroxelSlab( - Vector3 cameraPosition, - Vector2 gridCenter, - int x, - int y, - Vector3 min, - Vector3 max, - out float enterTravel, - out float exitTravel) - { - enterTravel = float.PositiveInfinity; - exitTravel = 0.0f; - Span samples = - [ - new Vector2(x * MediumFroxelDownscale, y * MediumFroxelDownscale), - new Vector2((x + 1) * MediumFroxelDownscale, y * MediumFroxelDownscale), - new Vector2(x * MediumFroxelDownscale, (y + 1) * MediumFroxelDownscale), - new Vector2((x + 1) * MediumFroxelDownscale, (y + 1) * MediumFroxelDownscale), - new Vector2((x + 0.5f) * MediumFroxelDownscale, (y + 0.5f) * MediumFroxelDownscale), - ]; - - var hit = false; - foreach (var pixel in samples) - { - var clampedPixel = new Vector2( - Math.Clamp(pixel.X, 0.0f, MathF.Max(width - 1.0f, 0.0f)), - Math.Clamp(pixel.Y, 0.0f, MathF.Max(height - 1.0f, 0.0f))); - var direction = RayDirectionForPixel(clampedPixel, cameraPosition, gridCenter); - if (!TraceAabb(cameraPosition, direction, min, max, out var sampleEnter, out var sampleExit)) - { - continue; - } - - enterTravel = MathF.Min(enterTravel, sampleEnter); - exitTravel = MathF.Max(exitTravel, sampleExit); - hit = true; - } - - return hit; - } - - private bool TraceViewFroxelSphere( - Vector3 cameraPosition, - Vector2 gridCenter, - int x, - int y, - Vector3 center, - float radius, - out float enterTravel, - out float exitTravel) - { - enterTravel = float.PositiveInfinity; - exitTravel = 0.0f; - Span samples = - [ - new Vector2(x * MediumFroxelDownscale, y * MediumFroxelDownscale), - new Vector2((x + 1) * MediumFroxelDownscale, y * MediumFroxelDownscale), - new Vector2(x * MediumFroxelDownscale, (y + 1) * MediumFroxelDownscale), - new Vector2((x + 1) * MediumFroxelDownscale, (y + 1) * MediumFroxelDownscale), - new Vector2((x + 0.5f) * MediumFroxelDownscale, (y + 0.5f) * MediumFroxelDownscale), - ]; - - var hit = false; - foreach (var pixel in samples) - { - var clampedPixel = new Vector2( - Math.Clamp(pixel.X, 0.0f, MathF.Max(width - 1.0f, 0.0f)), - Math.Clamp(pixel.Y, 0.0f, MathF.Max(height - 1.0f, 0.0f))); - var direction = RayDirectionForPixel(clampedPixel, cameraPosition, gridCenter); - if (!TraceSphere(cameraPosition, direction, center, radius, out var sampleEnter, out var sampleExit)) - { - continue; - } - - enterTravel = MathF.Min(enterTravel, sampleEnter); - exitTravel = MathF.Max(exitTravel, sampleExit); - hit = true; - } - - return hit; - } - - private Vector3 RayDirectionForPixel(Vector2 pixel, Vector3 cameraPosition, Vector2 gridCenter) - { - var ndc = ((pixel * 2.0f) - new Vector2(width, height)) / MathF.Max(height, 1.0f); - var target = new Vector3(gridCenter.X, gridCenter.Y, 0.0f); - var forward = Vector3.Normalize(target - cameraPosition); - var right = Vector3.Normalize(Vector3.Cross(forward, Vector3.UnitZ)); - var up = Vector3.Cross(right, forward); - return Vector3.Normalize((forward * 1.6f) + (right * ndc.X) + (up * ndc.Y)); - } - - private static bool TraceAabb(Vector3 origin, Vector3 direction, Vector3 min, Vector3 max, out float enterTravel, out float exitTravel) - { - enterTravel = 0.0f; - exitTravel = float.PositiveInfinity; - return ClipAabbAxis(origin.X, direction.X, min.X, max.X, ref enterTravel, ref exitTravel) - && ClipAabbAxis(origin.Y, direction.Y, min.Y, max.Y, ref enterTravel, ref exitTravel) - && ClipAabbAxis(origin.Z, direction.Z, min.Z, max.Z, ref enterTravel, ref exitTravel) - && exitTravel > enterTravel; - } - - private static bool ClipAabbAxis(float origin, float direction, float min, float max, ref float enterTravel, ref float exitTravel) - { - if (MathF.Abs(direction) < 0.000001f) - { - return origin >= min && origin <= max; - } - - var t0 = (min - origin) / direction; - var t1 = (max - origin) / direction; - enterTravel = MathF.Max(enterTravel, MathF.Min(t0, t1)); - exitTravel = MathF.Min(exitTravel, MathF.Max(t0, t1)); - return exitTravel >= enterTravel; - } - - private static bool TraceSphere(Vector3 origin, Vector3 direction, Vector3 center, float radius, out float enterTravel, out float exitTravel) - { - var oc = origin - center; - var b = Vector3.Dot(oc, direction); - var c = Vector3.Dot(oc, oc) - radius * radius; - var h = b * b - c; - if (h < 0.0f) - { - enterTravel = 0.0f; - exitTravel = 0.0f; - return false; - } - - h = MathF.Sqrt(h); - enterTravel = -b - h; - exitTravel = -b + h; - if (exitTravel <= 0.0f) - { - return false; - } - - enterTravel = MathF.Max(enterTravel, 0.0f); - return exitTravel > enterTravel; - } - - private int ViewFroxelIndex(int x, int y, int slice) - { - return x + y * mediumFroxelWidth + slice * mediumFroxelWidth * mediumFroxelHeight; - } - private void AddTransparentSurfaceToViewFroxel(int viewFroxelIndex, int surfaceId) { - var element = transparentSurfaceIds[viewFroxelIndex]; - if (element.X == surfaceId || element.Y == surfaceId || element.Z == surfaceId || element.W == surfaceId) - { - return; - } + AddIdToInt4Slots(transparentSurfaceIds, viewFroxelIndex, 1, surfaceId); + } - if (element.X == -1) + private static void AddIdToInt4Slots(Int4[] ids, int baseElement, int slotCount, int id) + { + for (var slot = 0; slot < slotCount; slot++) { - transparentSurfaceIds[viewFroxelIndex] = element with { X = surfaceId }; - return; - } + var elementIndex = baseElement + slot; + var element = ids[elementIndex]; + if (element.X == id || element.Y == id || element.Z == id || element.W == id) + { + return; + } - if (element.Y == -1) - { - transparentSurfaceIds[viewFroxelIndex] = element with { Y = surfaceId }; - return; - } + if (element.X == -1) + { + ids[elementIndex] = element with { X = id }; + return; + } - if (element.Z == -1) - { - transparentSurfaceIds[viewFroxelIndex] = element with { Z = surfaceId }; - return; - } + if (element.Y == -1) + { + ids[elementIndex] = element with { Y = id }; + return; + } - if (element.W == -1) - { - transparentSurfaceIds[viewFroxelIndex] = element with { W = surfaceId }; + if (element.Z == -1) + { + ids[elementIndex] = element with { Z = id }; + return; + } + + if (element.W == -1) + { + ids[elementIndex] = element with { W = id }; + return; + } } } @@ -1971,7 +1739,7 @@ public sealed class D3D12Renderer : IAquariumRenderer { var commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); commandAllocator.Name = $"Aquarium D3D12 Frame {index} Command Allocator"; - var uploadRing = new D3D12UploadRing(device, 16 * 1024 * 1024, $"Aquarium D3D12 Frame {index} Upload Ring"); + var uploadRing = new D3D12UploadRing(device, 64 * 1024 * 1024, $"Aquarium D3D12 Frame {index} Upload Ring"); var transientDescriptors = new D3D12DescriptorArena( device, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl index 714c08b..f931ac5 100644 --- a/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl +++ b/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl @@ -50,6 +50,7 @@ static const int MEDIUM_FROXEL_ATLAS_COLUMNS = 8; static const int MEDIUM_FROXEL_ATLAS_ROWS = 4; static const int MEDIUM_FROXEL_DOWNSCALE = 8; static const int MEDIUM_FROXEL_SLICE_COUNT = MEDIUM_FROXEL_ATLAS_COLUMNS * MEDIUM_FROXEL_ATLAS_ROWS; +static const int VIEW_FROXEL_PRIMITIVE_SLOT_COUNT = 2; static const float PI = 3.14159265359; static const float GRID_HEIGHT_TEXEL_COUNT = 128.0; static const float TERRAIN_ISOLINE_SPACING = 0.12; @@ -289,11 +290,15 @@ void considerFroxelPrimitiveHits(float3 origin, float3 direction, int froxelInde return; } - int4 ids = froxelPrimitiveIds[froxelIndex]; - considerPrimitiveHit(origin, direction, ids.x, intervalStart, intervalEnd, nearest); - considerPrimitiveHit(origin, direction, ids.y, intervalStart, intervalEnd, nearest); - considerPrimitiveHit(origin, direction, ids.z, intervalStart, intervalEnd, nearest); - considerPrimitiveHit(origin, direction, ids.w, intervalStart, intervalEnd, nearest); + [unroll] + for (int slot = 0; slot < VIEW_FROXEL_PRIMITIVE_SLOT_COUNT; slot++) + { + int4 ids = froxelPrimitiveIds[froxelIndex * VIEW_FROXEL_PRIMITIVE_SLOT_COUNT + slot]; + considerPrimitiveHit(origin, direction, ids.x, intervalStart, intervalEnd, nearest); + considerPrimitiveHit(origin, direction, ids.y, intervalStart, intervalEnd, nearest); + considerPrimitiveHit(origin, direction, ids.z, intervalStart, intervalEnd, nearest); + considerPrimitiveHit(origin, direction, ids.w, intervalStart, intervalEnd, nearest); + } } float gridSurfaceDistanceAt(float3 origin, float3 direction, float travel) diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 51fd977..2d3159c 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -94,3 +94,4 @@ {"timestamp":"2026-05-09T21:01:42.6014332+01:00","topic":"d3d12-view-froxel-transparent-surfaces","lesson":"Transparent surfaces must be binned into the view-froxel tube marched by the scene ray, not into the coarse 8x8x4 world broadphase. Aquarium now bootstraps this with a CPU-filled candidate buffer indexed by low-res screen cell and depth slice; this proves the topology, but the lasting implementation should be a GPU/raster binning pass to avoid large per-frame uploads.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs","state/memory.json","state/scratch.md"]} {"timestamp":"2026-05-09T21:13:51.8362280+01:00","topic":"d3d12-view-froxel-transparent-lookup","lesson":"View-froxel transparent lookup must not depend on the coarse world broadphase. A ray that misses the legacy 8x8x4 solid broadphase can still have valid transparent/medium candidates in its screen-space tube; only solid lookup should be gated by the world broadphase hit.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl"]} {"timestamp":"2026-05-09T21:19:15.6975837+01:00","topic":"d3d12-view-froxel-all-candidates","lesson":"The D3D12 scene path must not keep a parallel world-space candidate broadphase. Solid primitives and transparent surfaces now both use view-froxel candidate buffers indexed by low-res screen cell and depth slice; the scene ray marches its assigned tube and tests candidates only inside each slice interval. CPU binning is temporary scaffolding until GPU/raster binning owns the producer side.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/memory.json","state/scratch.md"]} +{"timestamp":"2026-05-09T21:26:19.5181030+01:00","topic":"d3d12-conservative-view-froxel-bootstrap","lesson":"Representative-ray CPU binning is not conservative enough for view-froxel candidates; sampling only corners/center missed sub-cell silhouettes and chopped solids/Grid. Until GPU/raster binning owns the producer side, bootstrap candidate buffers should overfill and let exact per-slice intersection reject false positives.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/memory.json","state/scratch.md"]} diff --git a/state/memory.json b/state/memory.json index 3196a9f..fe1e61a 100644 --- a/state/memory.json +++ b/state/memory.json @@ -21,6 +21,7 @@ "D3D12 field data should live in default-heap structured buffers, updated from the per-frame upload ring by CopyBufferRegion, then bound through transient SRV descriptors owned by the consuming pass. Do not make shaders read dynamic field tables straight from upload memory. D3D11 is reference-only during migration; do not pay DRY tax to preserve it.", "Transparent D3D12 surfaces must enter the same froxel/field candidate path as volumetrics, but not as pre-averaged froxel color. Grid line transparency is a scene-traversal transparent event: the CPU bins the Grid only into a conservative height slab, the shader brackets the height-sheet crossing inside the active ray interval, samples the height texture at the hit, evaluates cartesian lines/isolines/field lines there, composites without terminating, and keeps marching. Future transparent particles and billboard surfaces need the same candidate/event pipe with quad intersections and richer per-froxel event lists rather than alpha side channels or medium-atlas summaries.", "D3D12 scene candidate discovery belongs in the view-froxel volume. At 720p the active tube is 160x90x32; primitive and transparent candidate ids are indexed by low-res screen cell and depth slice, then scene rays test exact solid/transparent intersections inside that slice interval. The CPU-filled view-froxel buffers are bootstrap only; the durable path should become GPU/raster binning so per-frame upload bandwidth does not become the next stupid tax.", + "CPU view-froxel binning must be conservative until the real GPU/raster producer exists. Sampling only tube corners/center can miss sub-cell silhouettes and chop solids/Grid lines. The current bootstrap deliberately bins all solids and the Grid into all view-froxel cells, letting exact per-slice intersection reject false positives; this is wasteful scaffolding, not an optimization target.", "D3D12 pixel shader UAV registers share the output namespace. If a shader writes SV_Target0, bind the first manual UAV at u1, not u0.", "D3D12 shader routing derives its editable source directory from --shader-source/AQUARIUM_SHADER_SOURCE, then watches D3D12Grid/Medium/Scene/Post/Smoke HLSL files directly. Shader/PSO builds run on a background task; startup presents a lightweight loading frame until the first pipeline set is ready, and hot reload keeps the previous pipeline set if compilation fails.", "Use Vortice at the graphics API membrane. Keep CultMath as the CPU math grammar. Do not let third-party math opinions leak inward unless the conversion is explicit.", diff --git a/state/scratch.md b/state/scratch.md index 83dd8c5..d52d02a 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -11,12 +11,13 @@ selectable only as temporary reference ballast until visible D3D12 use survives the cut. Current renderer correction: D3D12 scene candidates now live in the view-froxel -volume. CPU bootstrap code intersects each low-res 8x8 pixel tube with solid -sphere bounds and the Grid height slab, marks the overlapping -160x90x32-at-720p depth slices, and the scene shader looks up solid and +volume. CPU bootstrap code currently bins all solid primitives and the Grid into +all 160x90x32-at-720p cells, and the scene shader looks up solid and transparent candidate ids by `(lowX, lowY, slice)` before doing exact -intersection for that slice interval. Next steel-plate step is replacing the -CPU-filled candidate buffers with GPU/raster binning passes. +intersection for that slice interval. This intentionally over-conservative +bootstrap replaced the corner/center sampled tube binning because that missed +sub-cell silhouettes and chopped the frame. Next steel-plate step is replacing +the CPU-filled candidate buffers with GPU/raster binning passes. ## Hot Context