diff --git a/docs/papers/fensalir-native-domain-reservoirs.pdf b/docs/papers/fensalir-native-domain-reservoirs.pdf index 76ce615..02d0217 100644 Binary files a/docs/papers/fensalir-native-domain-reservoirs.pdf and b/docs/papers/fensalir-native-domain-reservoirs.pdf differ diff --git a/docs/papers/fensalir-native-domain-reservoirs.tex b/docs/papers/fensalir-native-domain-reservoirs.tex index c223bce..fc761f8 100644 --- a/docs/papers/fensalir-native-domain-reservoirs.tex +++ b/docs/papers/fensalir-native-domain-reservoirs.tex @@ -370,13 +370,20 @@ and conservative object support. Exact client SDF distance re-evaluation remains producer-owned work rather than a generic postprocess authority. Debug modes expose selected coordinates, support footprint/domain kind, and shift/rejection state from the same row-3 layer consumed by presentation. +The reservoir is also now a budgeted work grid rather than a native-resolution +buffer: \texttt{GraphicsSettings.FieldReservoirScale} clamps scene evidence, +candidate/history rows, reservoir resolve, bloom sources, and match-window graph +targets below final presentation resolution by default. The full-resolution +surface is reserved for presentation reconstruction and diagnostics. The renderer also exposes a field-reservoir mode switch for comparison: native mode enables domain validity, support overlap, and producer replay during temporal reuse, while texel-baseline mode keeps the same rows but disables those native-domain gates. The first paired capture set \texttt{reservoir-compare-20260529-231904-*} changed 10.8208\% of final-frame -pixels between modes. This proves the comparison switch is live; it is not yet -a temporal leakage or ghosting metric. +pixels between modes, and +\texttt{scripts/measure-reservoir-mode-comparison.ps1} now repeats that +measurement. This proves the comparison switch is live; it is not yet a +temporal leakage or ghosting metric. \section{Required Evaluation} diff --git a/docs/papers/fensalir-pipeline.pdf b/docs/papers/fensalir-pipeline.pdf index f7449da..cf1db5d 100644 Binary files a/docs/papers/fensalir-pipeline.pdf and b/docs/papers/fensalir-pipeline.pdf differ diff --git a/docs/papers/fensalir-pipeline.tex b/docs/papers/fensalir-pipeline.tex index 1fa19bf..2b79819 100644 --- a/docs/papers/fensalir-pipeline.tex +++ b/docs/papers/fensalir-pipeline.tex @@ -655,12 +655,19 @@ column/curve coordinates in the current frame, and SDF object-hit replay carries the previous selected hit through object motion before validating current ray/travel/support. The next proof cuts are exact producer SDF replay, measured temporal leakage/ghosting, and measured rejection precision. +The reservoir work itself is no longer allowed to grow to native presentation +resolution by accident: scene evidence targets, reservoir candidate/history +rows, reservoir resolve, bloom sources, and match-window graph targets are tied +to a clamped internal work grid, while the final present buffer owns full +resolution reconstruction and display. Those captures now have an explicit comparison switch: native mode enables the domain validity, support-overlap, and producer-replay gates, while texel-baseline mode uses the same row ABI but disables those native-domain gates during temporal reuse. The first paired Fensalir capture set \texttt{reservoir-compare-20260529-231904-*} produced a 10.8208\% final-frame -pixel delta. That is a live-switch check, not a quality claim. +pixel delta. The repeatable script +\texttt{scripts/measure-reservoir-mode-comparison.ps1} reports that delta; it +is a live-switch check, not a quality claim. The system has cut the false ``nearest-travel-minus-coverage'' priority owner and the side-cache temptation. diff --git a/docs/perfect-fensalir-machine-roadmap.md b/docs/perfect-fensalir-machine-roadmap.md index 40a23af..3012685 100644 --- a/docs/perfect-fensalir-machine-roadmap.md +++ b/docs/perfect-fensalir-machine-roadmap.md @@ -14,10 +14,10 @@ producer intent / DSL / resource / sensor input -> semantic field and radiance claims -> domain binding and conservative summaries -> bounded proposals with target and proposal measure --> native-domain reservoir --> temporal and spatial domain shifts +-> budgeted native-domain reservoir work grid +-> temporal and spatial domain shifts under sampling/update budgets -> TSR-grade rejection and reconstruction --> denoiser-integrated resolved HDR field output +-> denoiser-integrated full-present HDR field output -> contribution/residency feedback ``` @@ -42,6 +42,12 @@ Fensalir already has the first shared GPU field-reservoir spine: final authority have been cut. - Debug modes now inspect the compute-owned reservoir layer rather than stale guide textures. +- The reservoir work grid is now explicitly budgeted below presentation + resolution by default. Scene evidence targets, reservoir candidate/history + rows, reservoir resolve, bloom, and match-window graph targets follow the + internal grid; the full-resolution buffer is the final presentation surface + where reconstruction, denoising, bloom, tone mapping, and debug display spend + their visible-output budget. The surviving flaw has moved one layer downstream: the live ABI now stores selected sample UV, packed producer coordinate, support footprint, domain kind, @@ -65,6 +71,10 @@ native post pass does not pretend to own every client distance function. - Reuse passes own shift mappings, support overlap, and producer re-evaluation. - TSR-style resolve owns rejection, reconstruction, and history trust over the resolved field output. +- Native-domain reservoirs are not native-resolution buffers. Domain cache + updates, proposal injection, temporal/spatial reuse, bloom sources, and graph + intermediate targets run under an explicit work-grid budget; only final + presentation is allowed to be full resolution. - The denoiser consumes reservoir diagnostics and can feed sampling pressure back into future probe selection. - Conservative summaries own safety. Stochastic or learned priority may rank @@ -77,13 +87,16 @@ native post pass does not pretend to own every client distance function. - Inputs: current producer proposals, previous final reservoirs, domain mappings, producer support footprints, current/previous motion, scene/SDF evidence, guide confidence, reconstruction feedback. -- Outputs: current/temporal/spatial/final reservoir stages, resolved HDR field - texture, rejection/debug layers, contribution/residency feedback signals. -- Derived state: pixel rows, MRTs, proxy raster output, debug palettes, and - presentation history are projections or diagnostics. -- Forbidden writers: proxy rasterization, presentation, old TubeField-local - paths, stale history rows, nearest-depth priority, and generic postprocess - history cannot decide final field visibility. +- Outputs: budgeted current/temporal/spatial/final reservoir stages, budgeted + resolved HDR field texture, full-resolution presented frame, + rejection/debug layers, contribution/residency feedback signals. +- Derived state: work-grid pixel rows, MRTs, proxy raster output, debug + palettes, upscaled presentation, and presentation history are projections or + diagnostics. +- Forbidden writers: native-resolution intermediate caches, proxy + rasterization, presentation, old TubeField-local paths, stale history rows, + nearest-depth priority, and generic postprocess history cannot decide final + field visibility. - Shared paths: TubeField, SDF, compact splats, meshes, volumes, fractal probes, and future sensor fields must enter through bounded proposals with target, proposal measure, selected domain coordinates, and support metadata. @@ -211,6 +224,17 @@ Exit gate: Purpose: replace texel history trust with support-aware domain replay. +Budget law: + +- Temporal reuse operates over the internal reservoir work grid, not the final + present grid. +- Work-grid scale is clamped below native presentation scale by engine + settings; present resolution may increase, but cache/update work may not + silently become native resolution. +- Any future adaptive planner may spend more samples on high-pressure regions, + but it must do so by explicit budget allocation, not by allocating another + full-resolution native reservoir buffer. + Algorithm: 1. Reproject or map the current target domain into the previous frame. @@ -499,6 +523,15 @@ Work packet: Native versus baseline changed 10.8208% of final-frame pixels, 0.0165% of rejection-debug pixels, and 0.2976% of shift-debug pixels. That proves the switch is live; it is not yet a quality metric. +9. Done: make the reservoir work grid explicitly budgeted below final + presentation resolution. `GraphicsSettings.FieldReservoirScale` clamps the + internal scene evidence, reservoir candidate/history, resolve, bloom, and + match-window graph targets to 0.25-0.75 of present size, with 0.5 as the + default. Headless capture accepts `--field-reservoir-scale`; debug UI reports + the live work-grid size beside present size. +10. Current: add temporal leakage/ghosting metrics over motion/disocclusion + sequences, then use those metrics to decide where the sampler spends its + bounded update budget. Required verification: diff --git a/scripts/capture-fensalir-frame.ps1 b/scripts/capture-fensalir-frame.ps1 index 99f4811..14f0ee8 100644 --- a/scripts/capture-fensalir-frame.ps1 +++ b/scripts/capture-fensalir-frame.ps1 @@ -6,6 +6,7 @@ param( [int]$RenderDebugMode = -1, [ValidateSet("native", "baseline")] [string]$FieldReservoirMode = "native", + [double]$FieldReservoirScale = 0.5, [int]$RetainSlots = 4, [int]$TimeoutSeconds = 120 ) @@ -60,6 +61,7 @@ if ($RenderDebugMode -ge 0) { if ($FieldReservoirMode -eq "baseline") { $arguments += @("--field-reservoir-mode", "baseline") } +$arguments += @("--field-reservoir-scale", $FieldReservoirScale) $env:AQUARIUM_HEADLESS_READY_FRAMES = [string][Math]::Max(1, $ReadyFrames) $process = Start-Process -FilePath $exePath -ArgumentList $arguments -NoNewWindow -PassThru -RedirectStandardOutput $stdoutLog -RedirectStandardError $stderrLog diff --git a/scripts/measure-reservoir-mode-comparison.ps1 b/scripts/measure-reservoir-mode-comparison.ps1 new file mode 100644 index 0000000..7745276 --- /dev/null +++ b/scripts/measure-reservoir-mode-comparison.ps1 @@ -0,0 +1,151 @@ +param( + [string]$CaptureDirectory = "", + [string]$Stamp, + [string]$Prefix = "reservoir-compare", + [string[]]$Suffixes = @("final", "rejection", "shift"), + [string]$OutputPath = "" +) + +$ErrorActionPreference = "Stop" +Set-StrictMode -Version Latest + +$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..") +if ([string]::IsNullOrWhiteSpace($CaptureDirectory)) { + $CaptureDirectory = Join-Path $repoRoot "artifacts\fensalir-captures" +} + +if ([string]::IsNullOrWhiteSpace($Stamp)) { + throw "Stamp is required, for example: -Stamp 20260529-231904" +} + +$CaptureDirectory = [System.IO.Path]::GetFullPath($CaptureDirectory) +if ([string]::IsNullOrWhiteSpace($OutputPath)) { + $OutputPath = Join-Path $CaptureDirectory "$Prefix-$Stamp-metrics.md" +} +$OutputPath = [System.IO.Path]::GetFullPath($OutputPath) +$csvPath = [System.IO.Path]::ChangeExtension($OutputPath, ".csv") + +Add-Type -AssemblyName System.Drawing + +function Measure-ImageDelta { + param( + [string]$NativePath, + [string]$BaselinePath, + [string]$Label + ) + + if (-not (Test-Path -LiteralPath $NativePath)) { + throw "Missing native capture: $NativePath" + } + if (-not (Test-Path -LiteralPath $BaselinePath)) { + throw "Missing baseline capture: $BaselinePath" + } + + $native = [System.Drawing.Bitmap]::new($NativePath) + $baseline = [System.Drawing.Bitmap]::new($BaselinePath) + try { + if ($native.Width -ne $baseline.Width -or $native.Height -ne $baseline.Height) { + throw "Capture dimensions differ for $Label." + } + + $changed = 0 + $sumR = 0L + $sumG = 0L + $sumB = 0L + $maxR = 0 + $maxG = 0 + $maxB = 0 + for ($y = 0; $y -lt $native.Height; $y++) { + for ($x = 0; $x -lt $native.Width; $x++) { + $a = $native.GetPixel($x, $y) + $b = $baseline.GetPixel($x, $y) + $dr = [Math]::Abs([int]$a.R - [int]$b.R) + $dg = [Math]::Abs([int]$a.G - [int]$b.G) + $db = [Math]::Abs([int]$a.B - [int]$b.B) + if ($dr -ne 0 -or $dg -ne 0 -or $db -ne 0) { + $changed++ + } + + $sumR += $dr + $sumG += $dg + $sumB += $db + if ($dr -gt $maxR) { $maxR = $dr } + if ($dg -gt $maxG) { $maxG = $dg } + if ($db -gt $maxB) { $maxB = $db } + } + } + + $total = $native.Width * $native.Height + [pscustomobject]@{ + Label = $Label + Width = $native.Width + Height = $native.Height + ChangedPixels = $changed + TotalPixels = $total + ChangedPercent = $changed / $total + MeanR = $sumR / $total + MeanG = $sumG / $total + MeanB = $sumB / $total + MaxR = $maxR + MaxG = $maxG + MaxB = $maxB + NativePath = $NativePath + BaselinePath = $BaselinePath + } + } + finally { + $native.Dispose() + $baseline.Dispose() + } +} + +$results = foreach ($suffix in $Suffixes) { + $nativePath = Join-Path $CaptureDirectory "$Prefix-$Stamp-native-$suffix.png" + $baselinePath = Join-Path $CaptureDirectory "$Prefix-$Stamp-baseline-$suffix.png" + Measure-ImageDelta -NativePath $nativePath -BaselinePath $baselinePath -Label $suffix +} + +New-Item -ItemType Directory -Force -Path (Split-Path $OutputPath) | Out-Null +$results | Export-Csv -NoTypeInformation -Path $csvPath + +$lines = [System.Collections.Generic.List[string]]::new() +$lines.Add("# Reservoir Mode Comparison") +$lines.Add("") +$lines.Add(("Stamp: ``{0}``" -f $Stamp)) +$lines.Add("") +$lines.Add("| Layer | Changed pixels | Changed % | Mean RGB delta | Max RGB delta |") +$lines.Add("| --- | ---: | ---: | ---: | ---: |") +foreach ($result in $results) { + $lines.Add(("| {0} | {1} / {2} | {3} | {4}, {5}, {6} | {7}, {8}, {9} |" -f ` + $result.Label, + $result.ChangedPixels, + $result.TotalPixels, + $result.ChangedPercent.ToString("P4"), + $result.MeanR.ToString("N4"), + $result.MeanG.ToString("N4"), + $result.MeanB.ToString("N4"), + $result.MaxR, + $result.MaxG, + $result.MaxB)) +} +$lines.Add("") +$lines.Add("This measures native-domain mode against texel-baseline mode for already captured frames. It proves the comparison switch changes visible output; it is not a temporal leakage or ghosting score by itself.") +Set-Content -LiteralPath $OutputPath -Value $lines -Encoding UTF8 + +Write-Host "Reservoir comparison metrics:" +foreach ($result in $results) { + Write-Host (" {0}: changed {1}/{2} ({3}) mean RGB ({4}, {5}, {6}) max RGB ({7}, {8}, {9})" -f + $result.Label, + $result.ChangedPixels, + $result.TotalPixels, + $result.ChangedPercent.ToString("P4"), + $result.MeanR.ToString("N4"), + $result.MeanG.ToString("N4"), + $result.MeanB.ToString("N4"), + $result.MaxR, + $result.MaxG, + $result.MaxB) +} +Write-Host "Wrote:" +Write-Host " $OutputPath" +Write-Host " $csvPath" diff --git a/src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs b/src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs index 4433669..d1f64bc 100644 --- a/src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs +++ b/src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs @@ -43,5 +43,6 @@ public readonly record struct AquariumRuntimeOptions( bool Headless, string? CultCachePath, int? RenderDebugModeOverride = null, - int? FieldReservoirModeOverride = null); + int? FieldReservoirModeOverride = null, + float? FieldReservoirScaleOverride = null); diff --git a/src/Aquarium.Engine.Contracts/GraphicsSettings.cs b/src/Aquarium.Engine.Contracts/GraphicsSettings.cs index d18fa48..f8014dd 100644 --- a/src/Aquarium.Engine.Contracts/GraphicsSettings.cs +++ b/src/Aquarium.Engine.Contracts/GraphicsSettings.cs @@ -5,12 +5,15 @@ public readonly record struct GraphicsSettings( float SceneExposure, float BloomIntensity, float BloomVeilIntensity, - int FieldReservoirMode) + int FieldReservoirMode, + float FieldReservoirScale) { public const int MinRenderDebugMode = 0; public const int MaxRenderDebugMode = 18; public const int FieldReservoirModeNativeDomain = 0; public const int FieldReservoirModeTexelBaseline = 1; + public const float MinFieldReservoirScale = 0.25f; + public const float MaxFieldReservoirScale = 0.75f; public const float MinSceneExposure = 0.02f; public const float MaxSceneExposure = 1.2f; public const float MinBloomIntensity = 0.0f; @@ -23,7 +26,8 @@ public readonly record struct GraphicsSettings( SceneExposure: 0.16f, BloomIntensity: 0.072f, BloomVeilIntensity: 0.014f, - FieldReservoirMode: FieldReservoirModeNativeDomain); + FieldReservoirMode: FieldReservoirModeNativeDomain, + FieldReservoirScale: 0.5f); public GraphicsSettings Normalized() { @@ -32,6 +36,7 @@ public readonly record struct GraphicsSettings( Math.Clamp(SceneExposure, MinSceneExposure, MaxSceneExposure), Math.Clamp(BloomIntensity, MinBloomIntensity, MaxBloomIntensity), Math.Clamp(BloomVeilIntensity, MinBloomVeilIntensity, MaxBloomVeilIntensity), - Math.Clamp(FieldReservoirMode, FieldReservoirModeNativeDomain, FieldReservoirModeTexelBaseline)); + Math.Clamp(FieldReservoirMode, FieldReservoirModeNativeDomain, FieldReservoirModeTexelBaseline), + Math.Clamp(FieldReservoirScale, MinFieldReservoirScale, MaxFieldReservoirScale)); } } diff --git a/src/Aquarium.Engine/AquariumHost.cs b/src/Aquarium.Engine/AquariumHost.cs index efe0117..02688ea 100644 --- a/src/Aquarium.Engine/AquariumHost.cs +++ b/src/Aquarium.Engine/AquariumHost.cs @@ -15,7 +15,8 @@ public static class AquariumHost ParseHeadless(args), ParseCachePath(args), ParseRenderDebugMode(args), - ParseFieldReservoirMode(args)); + ParseFieldReservoirMode(args), + ParseFieldReservoirScale(args)); using var runtimeLoader = new ClientRuntimeLoader(runtimeOptions, ParseClientAssemblyPath(args), ParseClientReloadPointerPath(args)); var runtime = runtimeLoader.Load(); if (runtimeOptions.RenderDebugModeOverride is { } renderDebugModeOverride) @@ -32,6 +33,13 @@ public static class AquariumHost FieldReservoirMode = fieldReservoirModeOverride, }).Normalized(); } + if (runtimeOptions.FieldReservoirScaleOverride is { } fieldReservoirScaleOverride) + { + runtime.GraphicsSettings = (runtime.GraphicsSettings with + { + FieldReservoirScale = fieldReservoirScaleOverride, + }).Normalized(); + } var input = new InputState(); var headlessSize = ParseHeadlessSize(args); var width = runtime.Options.Headless ? headlessSize.Width : 1280; @@ -289,6 +297,23 @@ public static class AquariumHost return ParseFieldReservoirModeValue(Environment.GetEnvironmentVariable("AQUARIUM_FIELD_RESERVOIR_MODE")); } + private static float? ParseFieldReservoirScale(IReadOnlyCollection args) + { + var values = args.ToArray(); + for (var index = 0; index < values.Length - 1; index++) + { + if (string.Equals(values[index], "--field-reservoir-scale", StringComparison.OrdinalIgnoreCase) + && float.TryParse(values[index + 1], out var scale)) + { + return scale; + } + } + + return float.TryParse(Environment.GetEnvironmentVariable("AQUARIUM_FIELD_RESERVOIR_SCALE"), out var environmentScale) + ? environmentScale + : null; + } + private static int? ParseFieldReservoirModeValue(string? value) { return value?.Trim().ToLowerInvariant() switch diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index ff87038..36c2970 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -310,9 +310,13 @@ public sealed class D3D12Renderer : IAquariumRenderer private int activeFieldResourceUploadCount; private int activeFieldResourceUploadSkippedCount; private Viewport viewport; + private Viewport reservoirViewport; private RawRect scissorRect; + private RawRect reservoirScissorRect; private int width; private int height; + private int reservoirWidth; + private int reservoirHeight; private ulong fenceValue; private int temporalFrameIndex; private int frameIndex; @@ -360,6 +364,7 @@ public sealed class D3D12Renderer : IAquariumRenderer ApplyGraphicsSettings(graphicsSettings ?? GraphicsSettings.Default); this.width = width; this.height = height; + RefreshReservoirWorkGrid(); programOutputEnabled = string.Equals( Environment.GetEnvironmentVariable(ProgramOutputEnabledEnvironmentVariable), "1", @@ -496,6 +501,7 @@ public sealed class D3D12Renderer : IAquariumRenderer StartPipelineBuild("initial"); viewport = new Viewport(0.0f, 0.0f, width, height); scissorRect = new RawRect(0, 0, width, height); + RefreshReservoirWorkGrid(); Console.WriteLine($"D3D12 resource registry: {resourceRegistry.Describe()}"); Console.WriteLine($"Aquarium render graph declared: {renderGraph.Describe()}"); Console.WriteLine("D3D12 device and swapchain created."); @@ -578,6 +584,8 @@ public sealed class D3D12Renderer : IAquariumRenderer .Options("Render Debug", () => RenderDebugMode, value => RenderDebugMode = Math.Clamp(value, GraphicsSettings.MinRenderDebugMode, GraphicsSettings.MaxRenderDebugMode), RenderDebugOptions, "Selects the active renderer debug view.", () => activeDebugTab == 0) .Button("Reset View", () => RenderDebugMode = 0, "Returns to the final presented frame.", () => activeDebugTab == 0) .Options("Reservoir Mode", () => settings.FieldReservoirMode, value => settings = (settings with { FieldReservoirMode = Math.Clamp(value, GraphicsSettings.FieldReservoirModeNativeDomain, GraphicsSettings.FieldReservoirModeTexelBaseline) }).Normalized(), FieldReservoirModeOptions, "Selects native-domain validation or texel-owned baseline reuse.", () => activeDebugTab == 0) + .Slider("Reservoir Scale", () => settings.FieldReservoirScale, value => settings = (settings with { FieldReservoirScale = Math.Clamp(value, GraphicsSettings.MinFieldReservoirScale, GraphicsSettings.MaxFieldReservoirScale) }).Normalized(), GraphicsSettings.MinFieldReservoirScale, GraphicsSettings.MaxFieldReservoirScale, "0.##", "Controls the internal reservoir work grid; presentation remains full resolution.", () => activeDebugTab == 0) + .Readout("Reservoir Grid", () => $"{reservoirWidth}x{reservoirHeight} / present {width}x{height}", "Internal reservoir work grid and final present size.", () => activeDebugTab == 0) .Section("HDR", () => activeDebugTab == 0) .Slider("Exposure", () => settings.SceneExposure, value => settings = (settings with { SceneExposure = Math.Clamp(value, GraphicsSettings.MinSceneExposure, GraphicsSettings.MaxSceneExposure) }).Normalized(), GraphicsSettings.MinSceneExposure, GraphicsSettings.MaxSceneExposure, "0.###", "Manual scene exposure before display transform.", () => activeDebugTab == 0) .Slider("Bloom Intensity", () => settings.BloomIntensity, value => settings = (settings with { BloomIntensity = Math.Clamp(value, GraphicsSettings.MinBloomIntensity, GraphicsSettings.MaxBloomIntensity) }).Normalized(), GraphicsSettings.MinBloomIntensity, GraphicsSettings.MaxBloomIntensity, "0.###", "Strength of pre-tonemap bloom energy.", () => activeDebugTab == 0) @@ -832,6 +840,7 @@ public sealed class D3D12Renderer : IAquariumRenderer var frameCpuStart = Stopwatch.GetTimestamp(); UpdateVisibleFrameRate(frameCpuStart); ResizeIfNeeded(width, height); + ResizeReservoirWorkGridIfNeeded(); ApplyCompletedPipelineBuild(); TryHotReloadShaders(); var frameResources = frames[frameIndex]; @@ -880,7 +889,7 @@ public sealed class D3D12Renderer : IAquariumRenderer ? frame.Scene.GpuFusionField.PresentationDelaySeconds : frame.Scene.TemporalGaussianField.PresentationDelaySeconds; var frameConstants = frameResources.UploadRing.WriteConstant(new FrameConstants( - new Vector2(width, height), + new Vector2(reservoirWidth, reservoirHeight), frame.TimeSeconds, frame.View.Radius, frame.CameraPosition, @@ -1932,6 +1941,7 @@ public sealed class D3D12Renderer : IAquariumRenderer width = newWidth; height = newHeight; + RefreshReservoirWorkGrid(); renderTargetViewArena.Dispose(); depthStencilViewArena.Dispose(); staticShaderDescriptorArena.Dispose(); @@ -1961,15 +1971,86 @@ public sealed class D3D12Renderer : IAquariumRenderer CreateGraphRenderTargets(); viewport = new Viewport(0.0f, 0.0f, width, height); scissorRect = new RawRect(0, 0, width, height); + RefreshReservoirWorkGrid(); Console.WriteLine($"D3D12 resized: {width}x{height}; {resourceRegistry.Describe()}"); } + private void RefreshReservoirWorkGrid() + { + var (workWidth, workHeight) = ResolveReservoirWorkGrid(); + reservoirWidth = workWidth; + reservoirHeight = workHeight; + reservoirViewport = new Viewport(0.0f, 0.0f, reservoirWidth, reservoirHeight); + reservoirScissorRect = new RawRect(0, 0, reservoirWidth, reservoirHeight); + } + + private void ResizeReservoirWorkGridIfNeeded() + { + var (workWidth, workHeight) = ResolveReservoirWorkGrid(); + if (workWidth == reservoirWidth && workHeight == reservoirHeight) + { + return; + } + + WaitForGpu(); + RemoveBloomRenderTargets(); + resourceRegistry.RemoveRenderTarget("scene-hdr-target"); + resourceRegistry.RemoveRenderTarget("scene-metadata-target"); + resourceRegistry.RemoveRenderTarget("scene-control-target"); + resourceRegistry.RemoveRenderTarget("scene-reservoir-guide-target"); + resourceRegistry.RemoveRenderTarget("scene-candidate-target"); + resourceRegistry.RemoveRenderTarget("scene-candidate-metadata-target"); + resourceRegistry.RemoveRenderTarget("scene-candidate-control-target"); + resourceRegistry.RemoveRenderTarget("scene-candidate-reservoir-guide-target"); + resourceRegistry.RemoveRenderTarget("reservoir-resolved-target"); + resourceRegistry.RemoveResource("scene-depth-target"); + DisposeBloomRenderTargets(); + sceneRenderTarget.Dispose(); + sceneMetadataRenderTarget.Dispose(); + sceneControlRenderTarget.Dispose(); + sceneReservoirGuideRenderTarget.Dispose(); + sceneCandidateRenderTarget.Dispose(); + sceneCandidateMetadataRenderTarget.Dispose(); + sceneCandidateControlRenderTarget.Dispose(); + sceneCandidateReservoirGuideRenderTarget.Dispose(); + reservoirResolvedRenderTarget.Dispose(); + fieldReservoirCandidateBuffer.Dispose(); + fieldReservoirLockBuffer.Dispose(); + DisposeFieldReservoirHistoryBuffers(); + sceneDepthTarget.Dispose(); + + reservoirWidth = workWidth; + reservoirHeight = workHeight; + reservoirViewport = new Viewport(0.0f, 0.0f, reservoirWidth, reservoirHeight); + reservoirScissorRect = new RawRect(0, 0, reservoirWidth, reservoirHeight); + sceneRenderTarget = CreateSceneRenderTarget(); + sceneMetadataRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-metadata-target", "Aquarium D3D12 Scene Metadata Target"); + sceneControlRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-control-target", "Aquarium D3D12 Scene Control Target"); + sceneReservoirGuideRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-reservoir-guide-target", "Aquarium D3D12 Scene Reservoir Guide Target"); + sceneCandidateRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-candidate-target", "Aquarium D3D12 Scene Candidate Target"); + sceneCandidateMetadataRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-candidate-metadata-target", "Aquarium D3D12 Scene Candidate Metadata Target"); + sceneCandidateControlRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-candidate-control-target", "Aquarium D3D12 Scene Candidate Control Target"); + sceneCandidateReservoirGuideRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-candidate-reservoir-guide-target", "Aquarium D3D12 Scene Candidate Reservoir Guide Target"); + reservoirResolvedRenderTarget = CreateReservoirResolvedRenderTarget(); + CreateFieldReservoirBuffers(); + sceneDepthTarget = CreateSceneDepthTarget(sceneDepthStencilView); + CreateBloomRenderTargets(); + } + + private (int Width, int Height) ResolveReservoirWorkGrid() + { + var scale = Math.Clamp(settings.FieldReservoirScale, GraphicsSettings.MinFieldReservoirScale, GraphicsSettings.MaxFieldReservoirScale); + return ( + Math.Max(1, (int)MathF.Ceiling(Math.Max(1, width) * scale)), + Math.Max(1, (int)MathF.Ceiling(Math.Max(1, height) * scale))); + } + private D3D12RenderTarget CreateSceneRenderTarget() { var target = new D3D12RenderTarget( device, - width, - height, + reservoirWidth, + reservoirHeight, SceneHdrFormat, renderTargetViewArena.Allocate(), staticShaderDescriptorArena.Allocate(), @@ -1985,8 +2066,8 @@ public sealed class D3D12Renderer : IAquariumRenderer { var target = new D3D12RenderTarget( device, - width, - height, + reservoirWidth, + reservoirHeight, SceneHdrFormat, renderTargetViewArena.Allocate(), staticShaderDescriptorArena.Allocate(), @@ -2002,8 +2083,8 @@ public sealed class D3D12Renderer : IAquariumRenderer { var target = new D3D12RenderTarget( device, - width, - height, + reservoirWidth, + reservoirHeight, SceneHdrFormat, renderTargetViewArena.Allocate(), null, @@ -2036,7 +2117,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private int FieldReservoirElementCount() { - return checked(Math.Max(1, width) * Math.Max(1, height) * FieldReservoirSlotsPerPixel); + return checked(Math.Max(1, reservoirWidth) * Math.Max(1, reservoirHeight) * FieldReservoirSlotsPerPixel); } private D3D12StructuredBuffer CreateFieldReservoirCandidateBuffer() @@ -2052,7 +2133,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private D3D12StructuredBuffer CreateFieldReservoirLockBuffer() { - var elementCount = checked(Math.Max(1, width) * Math.Max(1, height)); + var elementCount = checked(Math.Max(1, reservoirWidth) * Math.Max(1, reservoirHeight)); return new D3D12StructuredBuffer( device, elementCount, @@ -2114,8 +2195,8 @@ public sealed class D3D12Renderer : IAquariumRenderer { var target = new D3D12RenderTarget( device, - Math.Max(1, width >> (level + 1)), - Math.Max(1, height >> (level + 1)), + Math.Max(1, reservoirWidth >> (level + 1)), + Math.Max(1, reservoirHeight >> (level + 1)), SceneHdrFormat, renderTargetViewArena.Allocate(), staticShaderDescriptorArena.Allocate(), @@ -2351,8 +2432,8 @@ public sealed class D3D12Renderer : IAquariumRenderer { AquariumTargetSizeKind.Fixed => (Math.Max(1, size.Width), Math.Max(1, size.Height)), AquariumTargetSizeKind.MatchWindow => ( - Math.Max(1, (int)MathF.Ceiling(width * MathF.Max(size.Scale, 0.001f))), - Math.Max(1, (int)MathF.Ceiling(height * MathF.Max(size.Scale, 0.001f)))), + Math.Max(1, (int)MathF.Ceiling(reservoirWidth * MathF.Max(size.Scale, 0.001f))), + Math.Max(1, (int)MathF.Ceiling(reservoirHeight * MathF.Max(size.Scale, 0.001f)))), _ => throw new ArgumentOutOfRangeException(nameof(size), size.Kind, "Unsupported render target size policy."), }; } @@ -2408,8 +2489,8 @@ public sealed class D3D12Renderer : IAquariumRenderer context.CommandList.SetGraphicsRootDescriptorTable(RootSdfObjects, frameResources.SdfObjectDescriptor.Gpu); context.CommandList.SetGraphicsRootDescriptorTable(RootTemporalGaussians, frameResources.TemporalGaussianDescriptor.Gpu); context.CommandList.SetGraphicsRootDescriptorTable(RootBlueNoise, frameResources.BlueNoiseDescriptor.Gpu); - context.CommandList.RSSetViewports(viewport); - context.CommandList.RSSetScissorRects(scissorRect); + context.CommandList.RSSetViewports(reservoirViewport); + context.CommandList.RSSetScissorRects(reservoirScissorRect); context.CommandList.OMSetRenderTargets( [ sceneCandidateRenderTarget.RenderTargetView.Cpu, @@ -2545,8 +2626,8 @@ public sealed class D3D12Renderer : IAquariumRenderer activeCommandList.SetGraphicsRootDescriptorTable(RootCurrentSceneControl, frameResources.SceneCandidateControlDescriptor.Gpu); activeCommandList.SetGraphicsRootDescriptorTable(RootCurrentReservoirGuide, frameResources.SceneCandidateReservoirGuideDescriptor.Gpu); activeCommandList.SetGraphicsRootShaderResourceView(RootFieldReservoirCandidates, fieldReservoirCandidateBuffer.Resource.GPUVirtualAddress); - activeCommandList.RSSetViewports(viewport); - activeCommandList.RSSetScissorRects(scissorRect); + activeCommandList.RSSetViewports(reservoirViewport); + activeCommandList.RSSetScissorRects(reservoirScissorRect); activeCommandList.OMSetRenderTargets( [ sceneRenderTarget.RenderTargetView.Cpu, @@ -2622,7 +2703,7 @@ public sealed class D3D12Renderer : IAquariumRenderer activeCommandList.SetComputeRootDescriptorTable(RootReservoirResolvedOutput, frameResources.ReservoirResolvedUnorderedAccessDescriptor.Gpu); activeCommandList.SetComputeRootShaderResourceView(RootTubeFieldReplayManifest, tubeFieldReplayManifestBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootDescriptorTable(RootTubeFieldReplaySources, replaySourceDescriptors.Gpu); - activeCommandList.Dispatch((uint)((width + 7) / 8), (uint)((height + 7) / 8), 1); + activeCommandList.Dispatch((uint)((reservoirWidth + 7) / 8), (uint)((reservoirHeight + 7) / 8), 1); activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(historyWriteBuffer.Resource)); activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(reservoirResolvedRenderTarget.Resource)); } diff --git a/src/Aquarium.Fensalir/FensalirRuntime.cs b/src/Aquarium.Fensalir/FensalirRuntime.cs index 17d9398..837c19c 100644 --- a/src/Aquarium.Fensalir/FensalirRuntime.cs +++ b/src/Aquarium.Fensalir/FensalirRuntime.cs @@ -23,7 +23,8 @@ public sealed class FensalirRuntime : IAquariumRuntime 1.04f, 0.52f, 0.08f, - GraphicsSettings.FieldReservoirModeNativeDomain); + GraphicsSettings.FieldReservoirModeNativeDomain, + 0.5f); public AquariumRenderPlan RenderPlan { get; } = FensalirRenderPlan.Create(); diff --git a/src/Aquarium.Zyphos/ZyphosRuntime.cs b/src/Aquarium.Zyphos/ZyphosRuntime.cs index 1c8e6cf..e498d32 100644 --- a/src/Aquarium.Zyphos/ZyphosRuntime.cs +++ b/src/Aquarium.Zyphos/ZyphosRuntime.cs @@ -42,7 +42,8 @@ public sealed class ZyphosRuntime : IAquariumRuntime 1.08f, 0.32f, 0.05f, - GraphicsSettings.FieldReservoirModeNativeDomain); + GraphicsSettings.FieldReservoirModeNativeDomain, + 0.5f); public AquariumRenderPlan RenderPlan { get; } = ZyphosRenderPlan.Create(); diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 317a73b..f6458c8 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -297,3 +297,4 @@ {"timestamp":"2026-05-29T23:10:00+01:00","topic":"native-domain-sdf-object-replay","lesson":"SDF temporal reuse should validate the visible hit, not merely the texel history. The native reservoir now reconstructs the previous selected SDF world hit from stored UV/travel, carries it through object center motion, and rejects history unless the replayed hit still matches the current ray/travel/support envelope; exact client SDF distance re-evaluation remains producer-owned work until replay manifests or shared includes exist.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","tests/Aquarium.Engine.Tests/FieldReservoirAbiTests.cs","docs/perfect-fensalir-machine-roadmap.md","state/map.yaml","state/memory.json"],"source":"docs/perfect-fensalir-machine-roadmap.md"} {"timestamp":"2026-05-29T23:16:00+01:00","topic":"tubefield-replay-manifest","lesson":"TubeField replay authority no longer comes from a CPU-side single-batch special case. The history shader reads a bounded producer-keyed replay manifest and raw source descriptor table, scans for the selected sample's field-id family, and re-evaluates the shifted logical column/curve coordinate from the matching source. Overflow is invalid instead of guessed; exact scaling beyond the descriptor cap should become a replay atlas only when captures prove the cap is real pressure.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","tests/Aquarium.Engine.Tests/FieldReservoirAbiTests.cs","docs/perfect-fensalir-machine-roadmap.md","state/map.yaml","state/memory.json"],"source":"docs/perfect-fensalir-machine-roadmap.md"} {"timestamp":"2026-05-29T23:30:00+01:00","topic":"reservoir-baseline-comparison-mode","lesson":"Native-domain versus texel-owned baseline comparison now has an explicit field-reservoir mode switch. Both modes use the same reservoir rows; native mode enables domain validity, support overlap, and producer replay at temporal reuse, while baseline mode keeps texel-owned field/travel/normal/color/confidence validation. First paired captures at artifacts/fensalir-captures/reservoir-compare-20260529-231904-* changed 10.8208% of final-frame pixels, 0.0165% of rejection-debug pixels, and 0.2976% of shift-debug pixels. This proves the switch is live but does not yet measure temporal leakage or ghosting quality.","files":["src/Aquarium.Engine.Contracts/GraphicsSettings.cs","src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs","src/Aquarium.Engine/AquariumHost.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","scripts/capture-fensalir-frame.ps1","tests/Aquarium.Engine.Tests/FieldReservoirAbiTests.cs","docs/perfect-fensalir-machine-roadmap.md"],"source":"artifacts/fensalir-captures/reservoir-compare-20260529-231904-*"} +{"timestamp":"2026-05-29T23:55:00+01:00","topic":"budgeted-reservoir-work-grid","lesson":"The native-domain reservoir must be a budgeted spatiotemporal sampler, not a native-resolution buffer by another name. GraphicsSettings.FieldReservoirScale now clamps the internal work grid below final presentation scale; scene evidence targets, reservoir candidate/history rows, reservoir resolve, bloom sources, and match-window graph targets use that grid, while the full-resolution surface is reserved for final presentation/reconstruction. The comparison script now repeats native-vs-baseline image deltas, but the next real proof is temporal leakage/ghosting over motion sequences so adaptive update budgets can be spent where they buy visible stability.","files":["src/Aquarium.Engine.Contracts/GraphicsSettings.cs","src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs","src/Aquarium.Engine/AquariumHost.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Fensalir/FensalirRuntime.cs","src/Aquarium.Zyphos/ZyphosRuntime.cs","scripts/capture-fensalir-frame.ps1","scripts/measure-reservoir-mode-comparison.ps1","tests/Aquarium.Engine.Tests/FieldReservoirAbiTests.cs","docs/perfect-fensalir-machine-roadmap.md","state/map.yaml","state/scratch.md"],"source":"user spatiotemporal reservoir upscaling sampler correction"} diff --git a/state/map.yaml b/state/map.yaml index 545aa95..906eeb0 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -74,6 +74,12 @@ invariants: authority. Sampling budget may scale with target frame time and resolution, but identity, support, contribution mass, and visibility authority remain domain-native. + - Native-domain reservoirs are not native-resolution buffers. The reservoir + work grid is an explicit budgeted sampler below final present resolution; + scene evidence targets, candidate/history rows, resolve, bloom sources, and + match-window graph targets follow that grid. The final present buffer is + the only full-resolution surface, where reconstruction and denoising spend + visible-output budget. - Rendering backends are lowerings, not truth owners. Heightfields, splines, direct SDF proxies, meshes, volumes, fractal probes, and Mimir sensor observations must publish bounded Form/Appearance/Transport field claims @@ -138,7 +144,12 @@ next_actions: current ray/travel/support. A field-reservoir mode switch now captures native-domain validation against a texel-owned baseline; the first paired set is `reservoir-compare-20260529-231904-*`, where native versus baseline - changed 10.8208% of final-frame pixels. The next cut is a temporal + changed 10.8208% of final-frame pixels, and + `scripts/measure-reservoir-mode-comparison.ps1` now repeats those + single-frame deltas. The reservoir work grid is now clamped below present + resolution by `GraphicsSettings.FieldReservoirScale` (0.5 default, 0.75 + maximum), so native-domain replay spends bounded fill/compute before the + full-resolution presentation pass. The next cut is a temporal leakage/ghosting metric harness plus future exact producer SDF replay. - Build the planetary flow organ in staged cuts: provenance manifest, static relief and reanalysis cube-sphere bake pipeline, stochastic advection diff --git a/state/scratch.md b/state/scratch.md index bc60a29..d364d49 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -2,11 +2,20 @@ ## Current Slice -Extend native-domain reservoir replay from single-batch TubeField/SDF proof -paths into measured baseline/native-domain capture. The first comparison set is +Turn the native-domain reservoir from a native-resolution cache into a +budgeted spatiotemporal sampler. The work grid now defaults to half present +resolution and is clamped below native presentation scale; scene evidence, +reservoir candidate/history, resolve, bloom, and match-window graph targets use +that grid. The final present buffer is the only full-resolution surface. + +The first comparison set is `artifacts/fensalir-captures/reservoir-compare-20260529-231904-*`: native versus texel-baseline changed 10.8208% of final-frame pixels, 0.0165% of -rejection-debug pixels, and 0.2976% of shift-debug pixels. +rejection-debug pixels, and 0.2976% of shift-debug pixels. The repeatable +measurement script is `scripts/measure-reservoir-mode-comparison.ps1`. +First half-scale live capture: +`artifacts/fensalir-captures/budgeted-reservoir-20260529-234039-final.png` +at 1264x681 present output, nonblank by sampled pixel probe. ## Hot Lesson @@ -20,6 +29,10 @@ semantic domains and a dynamic contribution tree into bounded GPU reservoirs. The current nine-lane row ABI now carries first-class selected domain/sample-coordinate authority. A row keyed only by pixel, travel, field id, guide, proposal, and stats is no longer accepted as valid reservoir evidence. +That authority now lives on a budgeted work grid, not on the final present grid: +native-domain state describes selected field samples, while final resolution is +reconstructed from bounded evidence instead of allocating native-res +reservoirs. TubeField row samples store selected UV, logical column, curve coordinate, support footprint, domain kind, and shift kind; field id carries physical rolling-column identity. The old single-batch replay binding has been replaced @@ -35,12 +48,14 @@ cap remain intentionally non-authoritative. Follow `docs/perfect-fensalir-machine-roadmap.md` Phase 1: -1. Add a real metric harness for temporal leakage/ghosting instead of relying - on single-frame image deltas. +1. Add a real metric harness for temporal leakage/ghosting over motion and + disocclusion sequences instead of relying on single-frame image deltas. 2. Add exact SDF producer replay only when client SDF distance functions have a shared replay include or manifest instead of duplicating shader policy in post. -3. Replace the bounded TubeField replay source descriptor table with a replay +3. Add adaptive update/sample budget allocation only after the leakage harness + can tell whether extra samples buy visible stability. +4. Replace the bounded TubeField replay source descriptor table with a replay atlas only if real scenes hit the cap. ## Verification diff --git a/tests/Aquarium.Engine.Tests/FieldReservoirAbiTests.cs b/tests/Aquarium.Engine.Tests/FieldReservoirAbiTests.cs index e41220b..27d8b29 100644 --- a/tests/Aquarium.Engine.Tests/FieldReservoirAbiTests.cs +++ b/tests/Aquarium.Engine.Tests/FieldReservoirAbiTests.cs @@ -83,6 +83,24 @@ public sealed class FieldReservoirAbiTests Assert.Contains("FieldReservoirMode", capture); } + [Fact] + public void ReservoirWorkGridIsBudgetedBelowPresentationResolution() + { + var repoRoot = FindRepoRoot(); + var settings = File.ReadAllText(Path.Combine(repoRoot, "src", "Aquarium.Engine.Contracts", "GraphicsSettings.cs")); + var renderer = File.ReadAllText(Path.Combine(repoRoot, "src", "Aquarium.Engine", "Render", "D3D12Renderer.cs")); + var capture = File.ReadAllText(Path.Combine(repoRoot, "scripts", "capture-fensalir-frame.ps1")); + + Assert.Contains("MaxFieldReservoirScale = 0.75f", settings); + Assert.Contains("FieldReservoirScale: 0.5f", settings); + Assert.Contains("ResolveReservoirWorkGrid", renderer); + Assert.Contains("reservoirWidth", renderer); + Assert.Contains("new Vector2(reservoirWidth, reservoirHeight)", renderer); + Assert.Contains("RSSetViewports(reservoirViewport)", renderer); + Assert.Contains("RSSetViewports(viewport)", renderer); + Assert.Contains("--field-reservoir-scale", capture); + } + private static string FindRepoRoot() { var directory = new DirectoryInfo(AppContext.BaseDirectory);