Bin view froxel candidates conservatively

This commit is contained in:
Meta Vens 2026-05-09 21:41:57 +01:00
commit e2a63b8e6d
4 changed files with 176 additions and 16 deletions

View file

@ -107,6 +107,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
private readonly FieldInstanceGpu[] fieldInstances = new FieldInstanceGpu[FieldInstanceCount];
private Int4[] transparentSurfaceIds = [];
private readonly TransparentSurfaceGpu[] transparentSurfaces = new TransparentSurfaceGpu[TransparentSurfaceCount];
private readonly GridHeightBrushCpu[] gridHeightBrushes = new GridHeightBrushCpu[GridHeightBrushCount];
private Viewport viewport;
private RawRect scissorRect;
private int width;
@ -1183,6 +1184,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
var shape = new Vector4(power, amplitude, 0.0f, 0.0f);
var wave = new Vector4(waveAmplitude, waveFrequency, waveSpeed, 0.0f);
gridHeightBrushConstants.Set(index, centerRadius, shape, wave);
gridHeightBrushes[index] = new GridHeightBrushCpu(center, radius, power, amplitude, waveAmplitude, waveFrequency, waveSpeed);
}
private void BuildFroxelPrimitiveTable(AquariumFrame frame)
@ -1203,12 +1205,19 @@ public sealed class D3D12Renderer : IAquariumRenderer
private void AddPrimitiveToFroxels(AquariumFrame frame, int primitiveId, Vector3 center, float boundRadius)
{
_ = frame;
_ = center;
_ = boundRadius;
for (var viewFroxelIndex = 0; viewFroxelIndex < ViewFroxelCount; viewFroxelIndex++)
var farDistance = FrameFarDistance(frame);
for (var slice = 0; slice < MediumFroxelSliceCount; slice++)
{
AddPrimitiveToViewFroxel(viewFroxelIndex, primitiveId);
for (var y = 0; y < mediumFroxelHeight; y++)
{
for (var x = 0; x < mediumFroxelWidth; x++)
{
if (ViewFroxelIntersectsSphere(frame, x, y, slice, farDistance, center, boundRadius))
{
AddPrimitiveToViewFroxel(ViewFroxelIndex(x, y, slice), primitiveId);
}
}
}
}
}
@ -1294,9 +1303,19 @@ 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));
for (var viewFroxelIndex = 0; viewFroxelIndex < ViewFroxelCount; viewFroxelIndex++)
var farDistance = FrameFarDistance(frame);
for (var slice = 0; slice < MediumFroxelSliceCount; slice++)
{
AddTransparentSurfaceToViewFroxel(viewFroxelIndex, 0);
for (var y = 0; y < mediumFroxelHeight; y++)
{
for (var x = 0; x < mediumFroxelWidth; x++)
{
if (ViewFroxelCrossesGrid(frame, x, y, slice, farDistance))
{
AddTransparentSurfaceToViewFroxel(ViewFroxelIndex(x, y, slice), 0);
}
}
}
}
}
@ -1305,6 +1324,139 @@ public sealed class D3D12Renderer : IAquariumRenderer
AddIdToInt4Slots(transparentSurfaceIds, viewFroxelIndex, 1, surfaceId);
}
private bool ViewFroxelCrossesGrid(AquariumFrame frame, int x, int y, int slice, float farDistance)
{
Span<Vector3> corners = stackalloc Vector3[8];
FillViewFroxelCorners(frame, x, y, slice, farDistance, corners);
var sawPositive = false;
var sawNegative = false;
const float epsilon = 0.025f;
foreach (var corner in corners)
{
var signedDistance = EvaluateGridHeight(frame, new Vector2(corner.X, corner.Y)) - corner.Z;
sawPositive |= signedDistance >= -epsilon;
sawNegative |= signedDistance <= epsilon;
if (sawPositive && sawNegative)
{
return true;
}
}
return false;
}
private bool ViewFroxelIntersectsSphere(AquariumFrame frame, int x, int y, int slice, float farDistance, Vector3 center, float radius)
{
Span<Vector3> corners = stackalloc Vector3[8];
FillViewFroxelCorners(frame, x, y, slice, farDistance, corners);
var inside = Vector3.Zero;
foreach (var corner in corners)
{
inside += corner;
}
inside /= corners.Length;
return SphereInsidePlane(corners[0], corners[1], corners[3], inside, center, radius)
&& SphereInsidePlane(corners[4], corners[7], corners[5], inside, center, radius)
&& SphereInsidePlane(corners[0], corners[4], corners[1], inside, center, radius)
&& SphereInsidePlane(corners[2], corners[3], corners[6], inside, center, radius)
&& SphereInsidePlane(corners[0], corners[2], corners[4], inside, center, radius)
&& SphereInsidePlane(corners[1], corners[5], corners[3], inside, center, radius);
}
private static bool SphereInsidePlane(Vector3 a, Vector3 b, Vector3 c, Vector3 inside, Vector3 center, float radius)
{
var normal = Vector3.Cross(b - a, c - a);
var length = normal.Length();
if (length <= 0.000001f)
{
return true;
}
normal /= length;
if (Vector3.Dot(normal, inside - a) < 0.0f)
{
normal = -normal;
}
return Vector3.Dot(normal, center - a) >= -radius;
}
private void FillViewFroxelCorners(AquariumFrame frame, int x, int y, int slice, float farDistance, Span<Vector3> corners)
{
var nearTravel = (slice / (float)MediumFroxelSliceCount) * farDistance;
var farTravel = ((slice + 1.0f) / MediumFroxelSliceCount) * farDistance;
var px0 = x * MediumFroxelDownscale;
var px1 = Math.Min((x + 1) * MediumFroxelDownscale, width - 1);
var py0 = y * MediumFroxelDownscale;
var py1 = Math.Min((y + 1) * MediumFroxelDownscale, height - 1);
var d00 = RayDirectionForPixel(new Vector2(px0, py0), frame.CameraPosition, frame.Grid.Center);
var d10 = RayDirectionForPixel(new Vector2(px1, py0), frame.CameraPosition, frame.Grid.Center);
var d01 = RayDirectionForPixel(new Vector2(px0, py1), frame.CameraPosition, frame.Grid.Center);
var d11 = RayDirectionForPixel(new Vector2(px1, py1), frame.CameraPosition, frame.Grid.Center);
corners[0] = frame.CameraPosition + d00 * nearTravel;
corners[1] = frame.CameraPosition + d10 * nearTravel;
corners[2] = frame.CameraPosition + d01 * nearTravel;
corners[3] = frame.CameraPosition + d11 * nearTravel;
corners[4] = frame.CameraPosition + d00 * farTravel;
corners[5] = frame.CameraPosition + d10 * farTravel;
corners[6] = frame.CameraPosition + d01 * farTravel;
corners[7] = frame.CameraPosition + d11 * farTravel;
}
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 float FrameFarDistance(AquariumFrame frame)
{
var gridOrigin = new Vector3(frame.Grid.Center.X, frame.Grid.Center.Y, 0.0f);
return Vector3.Distance(frame.CameraPosition, gridOrigin) + MathF.Max(frame.Grid.Radius, 0.001f);
}
private float EvaluateGridHeight(AquariumFrame frame, Vector2 world)
{
var slow = MathF.Sin((world.X * 0.08f + world.Y * 0.06f) + frame.TimeSeconds * 0.27f)
* MathF.Sin((world.X * -0.04f + world.Y * 0.07f) - frame.TimeSeconds * 0.19f)
* 0.035f;
var height = slow;
for (var index = 0; index < GridHeightBrushCount; index++)
{
var brush = gridHeightBrushes[index];
var distanceValue = Vector2.Distance(world, brush.Center);
if (distanceValue > brush.Radius)
{
continue;
}
var well = PowerPulse(distanceValue, brush.Radius, brush.Power);
var ripple = MathF.Sin(distanceValue * brush.WaveFrequency - frame.TimeSeconds * brush.WaveSpeed);
height += brush.Amplitude * well + ripple * well * brush.WaveAmplitude;
}
return height;
}
private static float PowerPulse(float distanceValue, float radius, float power)
{
var normalized = Math.Clamp(distanceValue / MathF.Max(radius, 0.001f), 0.0f, 1.0f);
var shaped = MathF.Pow(1.0f - normalized, power);
return shaped * shaped * (3.0f - 2.0f * shaped);
}
private int ViewFroxelIndex(int x, int y, int slice)
{
return x + y * mediumFroxelWidth + slice * mediumFroxelWidth * mediumFroxelHeight;
}
private static void AddIdToInt4Slots(Int4[] ids, int baseElement, int slotCount, int id)
{
for (var slot = 0; slot < slotCount; slot++)
@ -1989,7 +2141,14 @@ public sealed class D3D12Renderer : IAquariumRenderer
}
}
private readonly record struct FroxelCell(int X, int Y, int Z);
private readonly record struct GridHeightBrushCpu(
Vector2 Center,
float Radius,
float Power,
float Amplitude,
float WaveAmplitude,
float WaveFrequency,
float WaveSpeed);
[StructLayout(LayoutKind.Sequential)]
private readonly record struct Int4(int X, int Y, int Z, int W);

View file

@ -95,3 +95,4 @@
{"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"]}
{"timestamp":"2026-05-09T21:38:12.8491911+01:00","topic":"d3d12-view-froxel-cpu-binning","lesson":"View-froxel CPU bootstrap binning now follows the intended conservative tests: Grid candidates require a sign crossing from heightfield-minus-worldZ over all eight cell corners, and sphere candidates use the froxel face planes expanded by radius. This removes the all-cells hammer while avoiding representative-ray chopping.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json","state/scratch.md"]}

View file

@ -21,7 +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.",
"CPU view-froxel binning must be conservative until the real GPU/raster producer exists. The bootstrap bins the Grid by evaluating signed heightfield distance at the eight view-froxel corners and requiring a sign crossing, and bins spheres by testing the sphere center against the view-froxel face planes expanded by radius. Representative center/corner rays alone can miss sub-cell silhouettes and chop solids/Grid lines.",
"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.",

View file

@ -11,13 +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 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. 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.
volume. CPU bootstrap code now bins sphere primitives by the view-froxel cell
face planes expanded by sphere radius, and bins the Grid by evaluating signed
heightfield distance at all eight view-froxel corners and requiring a crossing.
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.
## Hot Context