From a2411b9971c321a520b8c4f1e7c1dfcd39ab5de3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 30 May 2026 21:54:58 +0100 Subject: [PATCH] Add packed Leap stereo depth kernel --- docs/perfect-fensalir-machine-roadmap.md | 8 +- src/Aquarium.Engine/Render/D3D12Renderer.cs | 84 ++++++++++++++++++- .../Render/Shaders/D3D12StereoDepth.hlsl | 68 +++++++++++++++ state/evidence.jsonl | 1 + state/map.yaml | 14 ++-- 5 files changed, 166 insertions(+), 9 deletions(-) create mode 100644 src/Aquarium.Engine/Render/Shaders/D3D12StereoDepth.hlsl diff --git a/docs/perfect-fensalir-machine-roadmap.md b/docs/perfect-fensalir-machine-roadmap.md index ec71763..e23337d 100644 --- a/docs/perfect-fensalir-machine-roadmap.md +++ b/docs/perfect-fensalir-machine-roadmap.md @@ -394,8 +394,12 @@ Add contributors in this order: levels, aggregation path count, census radius, and P1/P2 smoothness penalties. The D3D12 renderer now accounts for dispatch-ready stereo lowerings only when the planned Height claim and all three resolved resources - are present; it reports that readiness separately from the not-yet-installed - SGM kernel. + are present. The first installed compute lane is `D3D12StereoDepth.hlsl`, + which handles the immediate Leap shape where left and right observations are + packed into the R/G channels of one Texture2D and writes a crude R16F + disparity by local SAD/block matching. This is a socket-owning live depth + proof, not the final libSGM-style census/aggregation SGM kernel and not + calibrated metric depth. Exit gate: diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 6cdb517..562e948 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -182,6 +182,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private ID3D12PipelineState? temporalGaussianPipelineState; private ID3D12PipelineState? splinePipelineState; private ID3D12PipelineState? gpuSensorFusionPipelineState; + private ID3D12PipelineState? stereoDepthPipelineState; private ID3D12PipelineState? fractalSurfaceSplatRenderPipelineState; private ID3D12PipelineState? fractalTransparentSplatRenderPipelineState; private ID3D12PipelineState? fractalSplatPipelineState; @@ -310,6 +311,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private int activeTubeFieldUnplannedLowerings; private int activeTubeFieldInvalidColumns; private int activeStereoDepthDispatchReadyLowerings; + private int activeStereoDepthDispatchedLowerings; private int activeStereoDepthUnplannedLowerings; private int activeStereoDepthUnresolvedLowerings; private int activeFieldResourceUploadCount; @@ -1026,6 +1028,7 @@ public sealed class D3D12Renderer : IAquariumRenderer commandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); UploadSceneStructuredResources(commandList, frameResources); DispatchGpuSensorFusion(commandList, frameResources); + DispatchStereoDepth(commandList, frameResources); DispatchFractalReservoirs(commandList, frameResources); DispatchTubeFields(commandList, frameResources); RenderHeightField(commandList, frameResources); @@ -1160,6 +1163,7 @@ public sealed class D3D12Renderer : IAquariumRenderer && splinePipelineState is not null && temporalGaussianPipelineState is not null && gpuSensorFusionPipelineState is not null + && stereoDepthPipelineState is not null && fractalSurfaceSplatRenderPipelineState is not null && fractalTransparentSplatRenderPipelineState is not null && fractalSplatPipelineState is not null @@ -1838,6 +1842,8 @@ public sealed class D3D12Renderer : IAquariumRenderer temporalGaussian.Name = "Aquarium D3D12 Temporal Gaussian Pipeline"; var gpuSensorFusion = CreateGpuSensorFusionPipelineState(paths.GpuSensorFusion); gpuSensorFusion.Name = "Aquarium D3D12 GPU Sensor Fusion Compute Pipeline"; + var stereoDepth = CreateStereoDepthPipelineState(paths.StereoDepth); + stereoDepth.Name = "Aquarium D3D12 Packed Stereo Depth Compute Pipeline"; var fractalSurfaceSplatRender = CreateFractalSurfaceSplatRenderPipelineState(paths.FractalSplatRender); fractalSurfaceSplatRender.Name = "Aquarium D3D12 Fractal Surface Splat Render Pipeline"; var fractalTransparentSplatRender = CreateFractalTransparentSplatRenderPipelineState(paths.FractalSplatRender); @@ -1883,6 +1889,7 @@ public sealed class D3D12Renderer : IAquariumRenderer spline, temporalGaussian, gpuSensorFusion, + stereoDepth, fractalSurfaceSplatRender, fractalTransparentSplatRender, fractalSplat, @@ -3358,6 +3365,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private void EvaluateStereoDepthLowerings() { activeStereoDepthDispatchReadyLowerings = 0; + activeStereoDepthDispatchedLowerings = 0; activeStereoDepthUnplannedLowerings = 0; activeStereoDepthUnresolvedLowerings = 0; if (activeFieldEvidenceFrame.StereoDepthLowerings.Count == 0) @@ -3403,6 +3411,53 @@ public sealed class D3D12Renderer : IAquariumRenderer return planned; } + private void DispatchStereoDepth(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) + { + activeStereoDepthDispatchedLowerings = 0; + if (stereoDepthPipelineState is null || activeFieldEvidenceFrame.StereoDepthLowerings.Count == 0) + { + return; + } + + var plannedClaims = PlannedStereoDepthClaimKeys(); + foreach (var lowering in activeFieldEvidenceFrame.StereoDepthLowerings) + { + var normalized = lowering.Normalized(); + if (!plannedClaims.Contains(normalized.ClaimKey) || + !string.Equals(normalized.LeftResourceKey, normalized.RightResourceKey, StringComparison.Ordinal) || + !fieldResourceRegistry.TryGetTexture2D(normalized.LeftResourceKey, out var packedInput) || + !fieldResourceRegistry.TryGetSurfacePage(normalized.DisparityResourceKey, out var disparityOutput) || + !disparityOutput.AllowsUnorderedAccess) + { + continue; + } + + packedInput.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + disparityOutput.Transition(activeCommandList, ResourceStates.UnorderedAccess); + var inputDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + packedInput.CreateShaderResourceView(device, inputDescriptor); + var outputDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + if (!disparityOutput.TryCreateUnorderedAccessView(device, outputDescriptor)) + { + continue; + } + + var constants = new D3D12StereoDepthConstants( + new Vector4(normalized.Width, normalized.Height, normalized.MinDisparity, normalized.DisparityLevels), + new Vector4(normalized.CensusRadius, normalized.AggregationPathCount, normalized.SmoothnessPenaltySmall, normalized.SmoothnessPenaltyLarge), + new Vector4(1.0f / MathF.Max(1.0f, normalized.DisparityLevels), 0.0f, 0.0f, 0.0f)); + var constantsUpload = frameResources.UploadRing.WriteConstant(constants); + activeCommandList.SetComputeRootSignature(gpuSensorFusionRootSignature); + activeCommandList.SetPipelineState(stereoDepthPipelineState); + activeCommandList.SetComputeRootConstantBufferView(RootFusionFrameConstants, constantsUpload.GpuVirtualAddress); + activeCommandList.SetComputeRootDescriptorTable(RootFusionSensorTextures, inputDescriptor.Gpu); + activeCommandList.SetComputeRootDescriptorTable(RootFusionOutput, outputDescriptor.Gpu); + activeCommandList.Dispatch((uint)((normalized.Width + 7) / 8), (uint)((normalized.Height + 7) / 8), 1); + activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(disparityOutput.Resource)); + activeStereoDepthDispatchedLowerings++; + } + } + private void UploadFieldResourceData(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { foreach (var upload in activeFieldEvidenceFrame.ResourceUploads) @@ -4131,9 +4186,10 @@ public sealed class D3D12Renderer : IAquariumRenderer Console.WriteLine( $"D3D12 stereo depth: lowerings {activeFieldEvidenceFrame.StereoDepthLowerings.Count:N0}; " + $"dispatch-ready {activeStereoDepthDispatchReadyLowerings:N0}; " + + $"dispatched {activeStereoDepthDispatchedLowerings:N0}; " + $"unplanned {activeStereoDepthUnplannedLowerings:N0}; " + $"unresolved {activeStereoDepthUnresolvedLowerings:N0}; " + - "kernel not installed"); + "kernel packed-block-match"); } if (accumulatedTimingFrames > 0) @@ -4326,6 +4382,7 @@ public sealed class D3D12Renderer : IAquariumRenderer splinePipelineState!, temporalGaussianPipelineState!, gpuSensorFusionPipelineState!, + stereoDepthPipelineState!, fractalSurfaceSplatRenderPipelineState!, fractalTransparentSplatRenderPipelineState!, fractalSplatPipelineState!, @@ -4353,6 +4410,7 @@ public sealed class D3D12Renderer : IAquariumRenderer splinePipelineState = pipelines.Spline; temporalGaussianPipelineState = pipelines.TemporalGaussian; gpuSensorFusionPipelineState = pipelines.GpuSensorFusion; + stereoDepthPipelineState = pipelines.StereoDepth; fractalSurfaceSplatRenderPipelineState = pipelines.FractalSurfaceSplatRender; fractalTransparentSplatRenderPipelineState = pipelines.FractalTransparentSplatRender; fractalSplatPipelineState = pipelines.FractalSplat; @@ -4382,6 +4440,7 @@ public sealed class D3D12Renderer : IAquariumRenderer scenePipelineState = null; temporalGaussianPipelineState = null; gpuSensorFusionPipelineState = null; + stereoDepthPipelineState = null; fractalSurfaceSplatRenderPipelineState = null; fractalTransparentSplatRenderPipelineState = null; fractalSplatPipelineState = null; @@ -4925,6 +4984,17 @@ public sealed class D3D12Renderer : IAquariumRenderer return device.CreateComputePipelineState(description); } + private ID3D12PipelineState CreateStereoDepthPipelineState(string path) + { + var computeShader = CompileShader(path, "D3D12PackedStereoDepthCS", "cs_5_0"); + var description = new ComputePipelineStateDescription + { + RootSignature = gpuSensorFusionRootSignature, + ComputeShader = computeShader, + }; + return device.CreateComputePipelineState(description); + } + private ID3D12PipelineState CreateFractalReservoirPipelineState(string path, string entryPoint) { var computeShader = CompileShader(path, entryPoint, "cs_5_0"); @@ -5372,12 +5442,19 @@ public sealed class D3D12Renderer : IAquariumRenderer } } + [StructLayout(LayoutKind.Sequential)] + private readonly record struct D3D12StereoDepthConstants( + Vector4 Shape, + Vector4 Match, + Vector4 Output); + private sealed record D3D12ShaderPaths( string HeightField, string Scene, string Spline, string TemporalGaussian, string GpuSensorFusion, + string StereoDepth, string TubeField, string FractalReservoir, string FractalSplatRender, @@ -5388,7 +5465,7 @@ public sealed class D3D12Renderer : IAquariumRenderer IReadOnlyList Includes, string Post) { - public IReadOnlyList All { get; } = [HeightField, Scene, Spline, TemporalGaussian, GpuSensorFusion, TubeField, FractalReservoir, FractalSplatRender, SdfCommon, SdfProxy, ..SdfShaders, SdfMath, ..Includes, Post]; + public IReadOnlyList All { get; } = [HeightField, Scene, Spline, TemporalGaussian, GpuSensorFusion, StereoDepth, TubeField, FractalReservoir, FractalSplatRender, SdfCommon, SdfProxy, ..SdfShaders, SdfMath, ..Includes, Post]; public static D3D12ShaderPaths FromManifest(string root, AquariumShaderManifest manifest) { @@ -5402,6 +5479,7 @@ public sealed class D3D12Renderer : IAquariumRenderer shaderPath("D3D12Scene.hlsl"), shaderPath(manifest.TemporalGaussianShader), shaderPath(manifest.GpuSensorFusionShader), + shaderPath("D3D12StereoDepth.hlsl"), shaderPath("D3D12TubeField.hlsl"), shaderPath(manifest.FractalReservoirShader), shaderPath(manifest.FractalSplatRenderShader), @@ -5421,6 +5499,7 @@ public sealed class D3D12Renderer : IAquariumRenderer ID3D12PipelineState Spline, ID3D12PipelineState TemporalGaussian, ID3D12PipelineState GpuSensorFusion, + ID3D12PipelineState StereoDepth, ID3D12PipelineState FractalSurfaceSplatRender, ID3D12PipelineState FractalTransparentSplatRender, ID3D12PipelineState FractalSplat, @@ -5450,6 +5529,7 @@ public sealed class D3D12Renderer : IAquariumRenderer FractalRadiosityReservoir.Dispose(); TubeFieldRender.Dispose(); TubeFieldCompute.Dispose(); + StereoDepth.Dispose(); FractalPbrReservoir.Dispose(); FractalSdfReservoir.Dispose(); FractalSplat.Dispose(); diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12StereoDepth.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12StereoDepth.hlsl new file mode 100644 index 0000000..d22eaf3 --- /dev/null +++ b/src/Aquarium.Engine/Render/Shaders/D3D12StereoDepth.hlsl @@ -0,0 +1,68 @@ +cbuffer D3D12StereoDepthConstants : register(b0) +{ + float4 Shape; // width, height, minDisparity, disparityLevels + float4 Match; // censusRadius, aggregationPathCount, p1, p2 + float4 Output; // invDisparityScale, reserved +}; + +Texture2D PackedStereoIr : register(t28); +RWTexture2D DisparityOut : register(u0); + +float PackedLeft(uint2 pixel) +{ + return PackedStereoIr.Load(int3(pixel, 0)).r; +} + +float PackedRight(uint2 pixel) +{ + return PackedStereoIr.Load(int3(pixel, 0)).g; +} + +[numthreads(8, 8, 1)] +void D3D12PackedStereoDepthCS(uint3 dispatchThreadId : SV_DispatchThreadID) +{ + const uint width = max(1u, (uint)Shape.x); + const uint height = max(1u, (uint)Shape.y); + const uint2 pixel = dispatchThreadId.xy; + if (pixel.x >= width || pixel.y >= height) + { + return; + } + + const int minDisparity = max(0, (int)Shape.z); + const int disparityLevels = max(1, min(256, (int)Shape.w)); + const int radius = max(1, min(4, (int)Match.x)); + const int maxDisparity = min(disparityLevels - 1, (int)pixel.x - radius - minDisparity); + if (maxDisparity <= 0 || pixel.y < (uint)radius || pixel.y + (uint)radius >= height) + { + DisparityOut[pixel] = 0.0f; + return; + } + + float bestCost = 1.0e20f; + int bestDisparity = 0; + [loop] + for (int disparity = minDisparity; disparity <= maxDisparity; disparity++) + { + float cost = 0.0f; + [loop] + for (int y = -radius; y <= radius; y++) + { + [loop] + for (int x = -radius; x <= radius; x++) + { + const uint2 leftPixel = uint2((uint)((int)pixel.x + x), (uint)((int)pixel.y + y)); + const uint2 rightPixel = uint2((uint)((int)pixel.x + x - disparity), (uint)((int)pixel.y + y)); + cost += abs(PackedLeft(leftPixel) - PackedRight(rightPixel)); + } + } + + if (cost < bestCost) + { + bestCost = cost; + bestDisparity = disparity; + } + } + + DisparityOut[pixel] = (float)bestDisparity; +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 5b1268f..bb34d92 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -309,3 +309,4 @@ {"timestamp":"2026-05-30T00:37:29+01:00","topic":"stereo-depth-lowering-contract","lesson":"FieldEvidence now carries typed stereo-depth lowering metadata for future D3D12 SGM dispatch. AquariumFieldStereoDepthLowering binds a Height claim to shader-readable left/right texture resources, profile/calibration/camera-pair identity, depth range/disparity settings, and a compute-writable UAV disparity SurfacePage. Validation rejects claim encoding mismatches, payload/resource mismatches, non-UAV disparity outputs, and missing/non-readable inputs. This keeps Mimir libSGM-provenance depth inside Fensalir resource authority rather than a private texture, CPU readback, CUDA, or TensorRT path.","files":["src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs","tests/Aquarium.Engine.Tests/FieldEvidenceContractTests.cs","docs/perfect-fensalir-machine-roadmap.md","state/map.yaml"],"source":"dotnet test tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj --filter StereoDepth"} {"timestamp":"2026-05-30T00:43:53+01:00","topic":"stereo-depth-dispatch-readiness","lesson":"D3D12Renderer now evaluates stereo-depth lowerings for dispatch readiness without installing a fake depth kernel. A lowering is counted ready only when the SurfacePage Height claim is planned, left/right input Texture2D resources resolve through the field resource registry, and the disparity SurfacePage resolves with UAV capability. Capacity logs report ready/unplanned/unresolved counts and explicitly say the kernel is not installed.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","docs/perfect-fensalir-machine-roadmap.md","state/map.yaml"],"source":"dotnet build src/Aquarium.Engine/Aquarium.Engine.csproj --no-restore"} {"timestamp":"2026-05-30T00:45:50+01:00","topic":"stereo-depth-sgm-kernel-constants","lesson":"AquariumFieldStereoDepthLowering now carries SGM-shaped kernel constants instead of leaving the future D3D12 shader to infer policy: min disparity, disparity levels, aggregation path count, census radius, and P1/P2 smoothness penalties. Validation requires positive census/P1/P2 values and P2 \u003e= P1. This preserves libSGM-style provenance as typed dispatch data before the HLSL kernel exists.","files":["src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs","tests/Aquarium.Engine.Tests/FieldEvidenceContractTests.cs","docs/perfect-fensalir-machine-roadmap.md","state/map.yaml"],"source":"dotnet test tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj --filter StereoDepth"} +{"timestamp":"2026-05-30T21:59:00+01:00","topic":"packed-leap-stereo-depth-kernel","lesson":"D3D12Renderer now installs and dispatches the first stereo-depth compute lane for the live Mimir Leap shape. D3D12StereoDepth.hlsl samples a packed R8G8 Texture2D as left/right IR lanes, performs a small local SAD/block match over the lowering's disparity/radius constants, and writes R16F disparity to the planned UAV SurfacePage. The dispatch only runs for planned Height claims whose left/right keys are the same packed texture and whose input/output resources resolve. This is a live depth proof and provenance-bearing socket for the later libSGM-style SGM rebuild, not calibrated metric depth or full SGM.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12StereoDepth.hlsl","docs/perfect-fensalir-machine-roadmap.md","state/map.yaml"],"source":"dotnet build src/Aquarium.Engine/Aquarium.Engine.csproj --no-restore; temp Vortice.D3DCompiler probe compiled D3D12PackedStereoDepthCS bytes=2168; full headless host compile attempted but hung before capture"} diff --git a/state/map.yaml b/state/map.yaml index 2258fa5..2faf486 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -250,17 +250,21 @@ next_actions: compute-writable UAV-backed pages. Empty SurfacePage version is content freshness, not texture identity, so compute outputs can update without reallocating when shape/format/access are unchanged. FieldEvidence now has - an explicit `AquariumFieldStereoDepthLowering` sidecar for future calibrated + an explicit `AquariumFieldStereoDepthLowering` sidecar for calibrated stereo compute dispatch: validation requires a Height claim whose payload is the compute-writable disparity SurfacePage, shader-readable left/right Texture2D or RollingTexture resources, profile/calibration/camera-pair identity, and coherent output shape/range. This keeps Mimir's libSGM-shaped D3D12 depth path inside typed field/resource authority instead of a private texture or CUDA/TensorRT dependency. The D3D12 renderer now evaluates - stereo-depth dispatch readiness without writing fake depth: a lowering is - ready only when its Height claim is planned and left/right input textures - plus UAV disparity SurfacePage resolve through the field resource registry; - capacity logs still state that the kernel is not installed. The lowering + stereo-depth dispatch readiness and runs the first packed-Leap compute + kernel: a lowering is eligible only when its Height claim is planned and + left/right input textures plus UAV disparity SurfacePage resolve through + the field resource registry. The first `D3D12StereoDepth.hlsl` lane handles + the immediate Mimir Leap shape where left and right observations are packed + into the R/G channels of one Texture2D, then writes crude R16F disparity by + local SAD/block matching. This is a live depth proof, not final + libSGM-style SGM or calibrated metric depth. The lowering sidecar now carries the first SGM-shaped kernel constants too: min disparity, disparity levels, aggregation paths, census radius, and P1/P2 smoothness penalties. VolumeTexture