diff --git a/research/rendering/fractal-reference-oracles.md b/research/rendering/fractal-reference-oracles.md index 287b067..d9c37ec 100644 --- a/research/rendering/fractal-reference-oracles.md +++ b/research/rendering/fractal-reference-oracles.md @@ -129,6 +129,63 @@ Apophysis-style minimal XML rather than full JWildfire `variationGroup` flame XML. Do not "fix" that by making the fixture bigger until the parser and DSL contract deliberately support the richer reference dialect. +## External Density Oracle + +Aquarium's CPU flame oracle is no longer the only visual-parity target. The GPU +receipt can compare Aquarium splat density against a binary PPM image rendered +by an external renderer: + +```powershell +.\scripts\new-jwildfire-baby-fixture.ps1 +.\scripts\fractal-flame-jwildfire-reference.ps1 ` + -Renderer FARender ` + -Flame artifacts\fractal-flame-jwildfire-reference\julian-disc-baby.flame ` + -Width 768 ` + -Height 768 ` + -Quality 2000 ` + -OutputDirectory artifacts\fractal-flame-jwildfire-reference +magick artifacts\fractal-flame-jwildfire-reference\julian-disc-baby-farender-*.png ` + -depth 8 artifacts\fractal-flame-jwildfire-reference\julian-disc-baby-farender.ppm +.\scripts\fractal-splat-receipt.ps1 ` + -ProgramFlame artifacts\fractal-flame-jwildfire-reference\julian-disc-baby.flame ` + -Splats 2000000 ` + -WarmupSplatUpdates 2000000 ` + -SplatUpdates 50000 ` + -Warmup 8 ` + -Frames 10 ` + -Depth 8 ` + -ReservoirUpdates 15000 ` + -ReadbackSplats 1000000 ` + -ReferenceDensityPpm artifacts\fractal-flame-jwildfire-reference\julian-disc-baby-farender.ppm ` + -HistogramSize 256x256 ` + -HistogramBounds '-2,-2,2,2' +``` + +`new-jwildfire-baby-fixture.ps1` derives a smaller, reproducible target from +FARender's bundled `selftest.flame`, preserving the boilerplate FARender needs +while reducing the nastier variation pressure: `jwf_julian_power` drops from +`126` to `8`, `jwf_gaussian_blur` becomes `0`, and the `wfield_*` amount fields +are set to zero. This is not a pristine flame design. It is a compatible rung +on the ladder that FARender actually renders. + +First external-density receipt, local GTX 1070, 2026-05-21: + +- reference renderer: JWildfire 9.00 bundled FARenderJWF +- fixture: `artifacts/fractal-flame-jwildfire-reference/julian-disc-baby.flame` +- reference render: `768x768`, quality `2000`, CUDA +- Aquarium steady GPU time: `1.145 ms/frame`, `873.4 FPS` equivalent +- external density score: `15.33%` in `256x256` bounds `-2,-2,2,2` +- score sweep at `128x128`: best tested bound was `-4,-4,4,4` at `32.95%` +- contact sheet: + `artifacts/fractal-flame-jwildfire-reference/julian-disc-baby-external-contact.png` + +The low external score is useful. Aquarium still scores about `89.94%` against +its CPU interpretation of the same baby fixture in `128x128` bounds +`-4,-4,4,4`, while FARender density disagrees hard. That means the next work is +not "more samples"; it is dialect and camera semantics: FARender flame camera +mapping, color/density filtering, chaos/xaos and weighting-field behavior, and +variation exactness. + ## JWildfire Selftest Faceplant Running JWildfire's bundled `selftest.flame` through Aquarium is the correct diff --git a/scripts/fractal-splat-receipt.ps1 b/scripts/fractal-splat-receipt.ps1 index 93a2e0e..3b0f505 100644 --- a/scripts/fractal-splat-receipt.ps1 +++ b/scripts/fractal-splat-receipt.ps1 @@ -13,6 +13,7 @@ param( [int]$VisualParityReferenceSamples = 1000000, [string]$HistogramSize = "64x64", [string]$HistogramBounds = "-8,-8,8,8", + [string]$ReferenceDensityPpm = "", [string[]]$VisualParityView = @(), [string]$VisualParityImageDirectory = "", [string]$VisualParityImagePrefix = "visual-parity", @@ -28,13 +29,15 @@ if (-not [string]::IsNullOrWhiteSpace($ProgramFlame)) { } $parityArgs = @() -if ($VisualParity) { +if ($VisualParity -or -not [string]::IsNullOrWhiteSpace($ReferenceDensityPpm)) { $parityArgs = @( - "--visual-parity", "--visual-parity-reference-samples", "$VisualParityReferenceSamples", "--histogram-size", $HistogramSize, "--histogram-bounds", $HistogramBounds ) + if ($VisualParity) { + $parityArgs = @("--visual-parity") + $parityArgs + } foreach ($view in $VisualParityView) { $parityArgs += @("--visual-parity-view", $view) } @@ -43,6 +46,10 @@ if ($VisualParity) { $parityArgs += @("--visual-parity-image-dir", $parityImageDir, "--visual-parity-image-prefix", $VisualParityImagePrefix) } } +if (-not [string]::IsNullOrWhiteSpace($ReferenceDensityPpm)) { + $referenceDensityPpmPath = if ([System.IO.Path]::IsPathRooted($ReferenceDensityPpm)) { $ReferenceDensityPpm } else { Join-Path $repoRoot $ReferenceDensityPpm } + $parityArgs += @("--reference-density-ppm", $referenceDensityPpmPath) +} dotnet run --project (Join-Path $repoRoot "tools\Aquarium.Fractal.Receipt\Aquarium.Fractal.Receipt.csproj") -c Release -- ` --splats $Splats ` diff --git a/scripts/new-jwildfire-baby-fixture.ps1 b/scripts/new-jwildfire-baby-fixture.ps1 new file mode 100644 index 0000000..c5c4bd6 --- /dev/null +++ b/scripts/new-jwildfire-baby-fixture.ps1 @@ -0,0 +1,21 @@ +param( + [string]$Source = "artifacts\reference-tools\j-wildfire-9.00\lib\FARenderJWF\selftest.flame", + [string]$Output = "artifacts\fractal-flame-jwildfire-reference\julian-disc-baby.flame" +) + +$ErrorActionPreference = "Stop" +$repoRoot = Split-Path -Parent $PSScriptRoot +$sourcePath = if ([System.IO.Path]::IsPathRooted($Source)) { $Source } else { Join-Path $repoRoot $Source } +$outputPath = if ([System.IO.Path]::IsPathRooted($Output)) { $Output } else { Join-Path $repoRoot $Output } +New-Item -ItemType Directory -Force -Path (Split-Path -Parent $outputPath) | Out-Null + +$text = [System.IO.File]::ReadAllText((Resolve-Path $sourcePath)) +$text = $text.Replace('JulianDisc - 535389044', 'julian-disc-baby') +$text = $text.Replace('jwf_julian_power="126"', 'jwf_julian_power="8"') +$text = $text.Replace('jwf_gaussian_blur="0.039366260122290476"', 'jwf_gaussian_blur="0.0"') +$text = $text.Replace('wfield_var_amount="0.21416904132907888"', 'wfield_var_amount="0.0"') +$text = $text.Replace('wfield_color_amount="0.26564915787570376"', 'wfield_color_amount="0.0"') +$text = $text.Replace('wfield_jitter_amount="0.13887944166913668"', 'wfield_jitter_amount="0.0"') + +[System.IO.File]::WriteAllText($outputPath, $text, [System.Text.UTF8Encoding]::new($false)) +Write-Host "JWildfire baby fixture: $outputPath" diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 0024972..b3837e7 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -191,3 +191,4 @@ {"timestamp":"2026-05-20T14:20:00+01:00","topic":"flame-subset-parser-histogram-receipts","lesson":"The reference path now parses and evaluates a small Apophysis/FLAM3 flame subset in runtime code: xform weight, color, affine coefficients, and `linear`, `spherical`, and `bubble` variation weights. Tests cover parser fields, independent variation formulas, and a deterministic 64x64 histogram checksum for a mixed linear/spherical/bubble fixture. This is still not external renderer parity, but it gives Aquarium a stable CPU receipt before GPU lowering and keeps Zyphos out of the correctness loop.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalFlameDefinition.cs","src/Aquarium.Engine.Fractal/Grammar/FractalFlameFileParser.cs","src/Aquarium.Engine.Fractal/Grammar/FractalFlameChaosGame.cs","src/Aquarium.Engine.Fractal/Grammar/FractalPointHistogram.cs","tests/Aquarium.Engine.Fractal.Tests/ApophysisReferenceParityTests.cs","tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-spherical-bubble.flame","research/rendering/fractal-reference-oracles.md"],"source":"continued after adopting Apophysis/FLAM3 as the fractal reference family"} {"timestamp":"2026-05-20T14:30:00+01:00","topic":"flame-histogram-receipt-cli","lesson":"The receipt tool now has a non-GPU `--flame` mode that loads a `.flame` fixture, runs FractalFlameChaosGame, bins points through FractalPointHistogramBuilder, and writes a JSON checksum receipt. `scripts/fractal-flame-receipt.ps1` runs the default mixed linear/spherical/bubble fixture with seed 0x0BADC0DE and emits checksum 0xAEB1C81B. This creates a cheap local receipt path before wiring external FLAM3/Apophysis renderer parity or GPU lowering.","files":["tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-flame-receipt.ps1","research/rendering/fractal-reference-oracles.md"],"source":"continued reference-first fractal pipeline build"} {"timestamp":"2026-05-21T00:25:00+01:00","topic":"gpu-resident-flame-iteration-state","lesson":"Flame splat generation now has a real GPU-resident iteration cache. `AquariumPackedFractalFlameState` is a 32-byte UAV row per resident splat storing point/support/material plus RNG/step; D3D12FractalReservoirCompute advances touched rows instead of replaying chaos-game ancestry from zero. The receipt harness separates full-population acquisition from steady stochastic maintenance: on the GTX 1070, JWildfire FARender selftest.flame with 2,000,000 splats/states, 8 full acquisition frames, then 50,000 splat updates/frame plus 15,000 reservoir updates/pass/frame at depth 8 measured 1.011 ms/frame / 988.8 FPS equivalent and 84.85% CPU-slice distribution parity. The same steady budget without acquisition scored 32.64%, so persistent caches must report cold-start versus maintenance explicitly.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs","tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-splat-receipt.ps1","research/rendering/fractal-reference-oracles.md","state/map.yaml","state/memory.json"],"source":"user demanded the Perfect Machine stop replaying crayon flames and keep building toward GPU-resident stochastic fractal rendering"} +{"lesson":"The flame parity gate now has an external image-density reference instead of only Aquarium CPU self-agreement. tools/Aquarium.Fractal.Receipt accepts --reference-density-ppm, loads a binary PPM rendered by JWildfire/FARender, converts luminance into the reference histogram, and compares Aquarium GPU splat density against it. scripts/new-jwildfire-baby-fixture.ps1 derives a smaller FARender-compatible julian-disc-baby.flame from FARender selftest while preserving boilerplate FARender requires. First GTX 1070 receipt: FARender 768x768 quality 2000 reference, Aquarium 2M splats/states, 8 acquisition frames, 50k steady splat updates/frame, depth 8, 1.145 ms/frame, but only 15.33% external density score in 256x256 bounds -2..2; a 128x128 bounds sweep peaked at 32.95% for -4..4 while Aquarium-vs-CPU scored 89.94%. This proves the next failure is dialect/camera/render filtering, not GPU sampling count.","timestamp":"2026-05-21T01:05:00+01:00","files":["tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-splat-receipt.ps1","scripts/new-jwildfire-baby-fixture.ps1","research/rendering/fractal-reference-oracles.md","state/map.yaml","state/memory.json"],"source":"user asked to ditch the shitty oracle and get proper ground truth that gives Aquarium useful exercise","topic":"external-flame-density-oracle"} diff --git a/state/map.yaml b/state/map.yaml index 1cc099e..d20a66e 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -154,6 +154,7 @@ renderer_state: - View-conditioned visual parity now scores named camera windows instead of trusting one global histogram. For the depth-16 flame receipt, global -8..8 scores 97.09%, mid -1..1 scores 91.93%, close -0.5..0.5 scores 88.97%, and micro -0.25..0.25 scores 82.05% with 2,656 starved reference bins and 17.95% underrepresented mass. This is the current hard loss: the reservoir is not yet spending work based on camera-conditioned underrepresentation. - High-reference flame contact sheets should use at least 20M CPU oracle samples for visual judgment. The current artifact is artifacts/fractal-contact-sheet-hq/flame-parity-contact-sheet-hq.png, comparing 20M CPU oracle histograms against 250k Aquarium GPU readback samples for global frame 1/10 and zoom frame 1/10. The 1M-sample oracle was too noisy and should be treated as a scalar smoke check only. - External flame visual references are now reproducible from ignored local artifacts. scripts/install-flame-reference-tools.ps1 hydrates JWildfire 9.00 plus Temurin JRE 17 under artifacts/reference-tools; scripts/fractal-flame-jwildfire-reference.ps1 prefers JWildfire's bundled FARenderJWF GPU renderer for explicit PNG output. Local GTX 1070 smoke rendered FARender's selftest.flame at 1024x1024 quality 2000 in 7.69 sec to artifacts/fractal-flame-jwildfire-reference/selftest-farender-20260520-233638.png. JWildfire/FARender is a visual reference artifact lane, not Aquarium runtime code. + - tools/Aquarium.Fractal.Receipt now has an external density oracle: --reference-density-ppm compares Aquarium GPU splat XY histograms against luminance density from a binary PPM rendered by an external flame renderer. scripts/new-jwildfire-baby-fixture.ps1 derives a smaller FARender-compatible julian-disc-baby.flame from JWildfire's selftest by reducing julian power and muting gaussian/wfield amounts while preserving FARender boilerplate. First GTX 1070 external-density receipt against FARender's 768x768 quality-2000 baby render scored only 15.33% in 256x256 bounds -2..2; a 128x128 bounds sweep peaked at 32.95% for -4..4 while Aquarium still scored 89.94% against its own CPU slice. This is the new honest oracle: dialect/camera/render-filter semantics, not GPU sampling count, are the current failure. - JWildfire selftest flame is the current honest faceplant target. After adding a first dialect slice for JWildfire coefficient layout, variationGroup, disc, julian, gaussian_blur, and post transforms, the depth-64 GTX 1070 receipt against Aquarium's CPU interpretation of artifacts/reference-tools/j-wildfire-9.00/lib/FARenderJWF/selftest.flame reaches 84.19% score in bounds -8..8 and 88.01% in bounds -128..128, but costs about 129 ms/frame. This is CPU/GPU slice parity, not external JWildfire visual parity. It proves the remaining hard work is richer dialect semantics plus persistent GPU iteration-state reservoirs; brute replaying deep flame iteration from zero per splat is not the final hot path. - FractalFlameFileParser now has ParseFirstWithReport for import accountability. Receipt runs emit fractal-flame-import-report-*.json beside flame histogram/GPU receipts. The JWildfire selftest report currently records 15 accepted fields, 3 approximations, 45 ignored render/presentation fields, and 11 rejected geometry/sampling fields: wfield_* weighting-field attributes. Successful XML parsing is not successful translation. - FractalFlameIterationState and FractalFlameIterationStepper define the persistent flame iteration invariant before GPU lowering: advancing a sample in chunks must match a one-shot advance from the same state. This is a parity/mock boundary for the future GPU state buffer, not a runtime CPU renderer. diff --git a/state/memory.json b/state/memory.json index 2fc0377..0e940be 100644 --- a/state/memory.json +++ b/state/memory.json @@ -112,6 +112,7 @@ "Global flame parity is not enough. View-conditioned parity now scores named viewport bounds and reports GPU/reference hits, starved reference bins, and underrepresented mass. First depth-16 GTX 1070 receipt with 250k GPU readback splats vs 1M CPU samples: global -8..8 scores 97.09%, mid -1..1 scores 91.93%, close -0.5..0.5 scores 88.97%, micro -0.25..0.25 scores 82.05% with 2,656 starved bins and 17.95% underrepresented mass. This proves the current reservoir is fast but not view-adaptive; next work needs camera-conditioned target weights and underrepresented-region feedback.", "Do not use the quick 1M-sample flame oracle image for visual judgment; it is too noisy. The high-reference contact sheet uses 20,000,000 CPU oracle samples and 250,000 Aquarium GPU readback splats per panel at artifacts/fractal-contact-sheet-hq/flame-parity-contact-sheet-hq.png. It makes the zoom failure legible: the CPU oracle smooths out while Aquarium remains under-sampled after zoom because the current reservoir is not view-adaptive.", "Aquarium's CPU flame histogram is a math oracle, not visual ground truth. The visual reference ladder is: Chaotica as gold market-quality reference when available/imported, JWildfire/FARender as scriptable visual reference, FLAM3/Apophysis as portable baseline compatibility, Aquarium CPU as deterministic unit-test/debug oracle only. On 2026-05-20 Chaotica and flam3-render were not on PATH, but scripts/install-flame-reference-tools.ps1 hydrated JWildfire 9.00 plus Temurin JRE 17 under ignored artifacts, and scripts/fractal-flame-jwildfire-reference.ps1 rendered JWildfire's bundled FARenderJWF selftest flame at 1024x1024 quality 2000 in 7.69 sec on the GTX 1070. JWildfire/FARender is an external visual reference artifact lane, not Aquarium runtime code. Do not claim best-in-market flame parity until imported Chaotica renders or fully matched JWildfire flame dialect metrics are wired into residual scoring.", + "The useful flame oracle is now external density, not Aquarium CPU self-agreement. tools/Aquarium.Fractal.Receipt accepts --reference-density-ppm to compare GPU splat histograms against luminance density from a binary PPM rendered by JWildfire/FARender. scripts/new-jwildfire-baby-fixture.ps1 derives a smaller FARender-compatible julian-disc-baby.flame from the bundled selftest while preserving required FARender boilerplate. First external receipt scored 15.33% in 256x256 bounds -2..2, and a 128x128 sweep peaked at 32.95% in -4..4 while Aquarium-vs-CPU scored 89.94%; the live failure is dialect/camera/render-filter semantics, not sample count.", "JWildfire selftest is now the flame renderer faceplant target. The current dialect slice supports JWildfire coefficient layout, variationGroup, disc, julian, gaussian_blur, and post transforms. After post lowering, the depth-64 GTX 1070 receipt scores 84.19% against Aquarium's CPU slice oracle in bounds -8..8 and 88.01% in bounds -128..128, but costs about 129 ms/frame. This is not external JWildfire visual parity; it is CPU/GPU agreement on the supported slice. Aquarium still needs richer dialect semantics, palette/density/render-filter parity, weighting-field handling, and persistent per-sample GPU iteration-state reservoirs instead of replaying deep chaos-game ancestry from zero for every splat.", "Flame imports must report translation loss. FractalFlameFileParser.ParseFirstWithReport returns accepted, approximated, ignored, and rejected fields per transform, and receipt runs write fractal-flame-import-report-*.json. The JWildfire selftest report currently shows 15 accepted fields, 3 approximations, 45 ignored render/presentation fields, and 11 rejected geometry/sampling fields: wfield_* weighting-field attributes. Treat successful XML parsing as insufficient until rejected geometry fields are either implemented as DSL/operator nodes or explicitly accepted as out-of-scope diagnostics.", "Persistent flame iteration now has both a CPU parity contract and a GPU realization. FractalFlameIterationState plus FractalFlameIterationStepper prove chunked CPU advancement; AquariumPackedFractalFlameState mirrors the point/support/material/RNG/step packet in D3D12FractalReservoirCompute as a UAV so flame splats advance over frames. Keep the acquisition/maintenance split explicit in receipts and renderer budgets.", diff --git a/tools/Aquarium.Fractal.Receipt/Program.cs b/tools/Aquarium.Fractal.Receipt/Program.cs index f1e24ea..00cb1a1 100644 --- a/tools/Aquarium.Fractal.Receipt/Program.cs +++ b/tools/Aquarium.Fractal.Receipt/Program.cs @@ -66,6 +66,7 @@ if (importReportPath is not null) } if (receipt.VisualParity is not null) { + Console.WriteLine($"visual parity reference: {receipt.VisualParity.ReferenceSource}"); Console.WriteLine($"visual parity samples: {receipt.VisualParity.ComparedSamples:N0}/{receipt.VisualParity.ReferenceSamples:N0}"); Console.WriteLine($"visual parity views: {receipt.VisualParity.Views.Count:N0}"); Console.WriteLine($"visual parity bins: {receipt.VisualParity.Width}x{receipt.VisualParity.Height}"); @@ -474,17 +475,11 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable int splatStride, int readbackSplatCount) { - if (!options.VisualParity || options.ProgramFlamePath is null || readbackSplatCount <= 0) + if (!options.VisualParity || readbackSplatCount <= 0) { return null; } - var flame = FractalFlameFileParser.ParseFirst(File.ReadAllText(options.ProgramFlamePath), unchecked((int)options.Seed)); - var referencePoints = FractalFlameChaosGame.Generate( - flame, - options.VisualParityReferenceSamples, - options.HistogramBurnIn, - new FractalXorShiftRandom(options.Seed)); var points = new Vector2[readbackSplatCount]; var splats = (AquariumPackedFractalSdfSplat3D*)readback.Map(0); for (var index = 0; index < points.Length; index++) @@ -497,13 +492,22 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable var views = options.VisualParityViews.Count > 0 ? options.VisualParityViews : [new VisualParityView("global", options.HistogramBounds)]; + ReferenceDensityImage? externalReference = options.ReferenceDensityPpmPath is null + ? null + : LoadReferenceDensityPpm(options.ReferenceDensityPpmPath, options.HistogramBounds); + var flameReferencePoints = externalReference is null + ? BuildCpuFlameReferencePoints(options) + : null; var viewReceipts = new VisualParityViewReceipt[views.Count]; for (var index = 0; index < views.Count; index++) { + var referenceHistogram = externalReference is null + ? FractalPointHistogramBuilder.Build(flameReferencePoints!, options.HistogramWidth, options.HistogramHeight, views[index].Bounds) + : externalReference.Value.ToHistogram(options.HistogramWidth, options.HistogramHeight, views[index].Bounds); viewReceipts[index] = BuildVisualParityView( options, views[index], - referencePoints, + referenceHistogram, points, options.HistogramWidth, options.HistogramHeight); @@ -511,8 +515,9 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable var primary = viewReceipts[0]; return new VisualParityReceipt( + externalReference is null ? "Aquarium CPU flame oracle" : Path.GetFullPath(options.ReferenceDensityPpmPath!), readbackSplatCount, - options.VisualParityReferenceSamples, + externalReference?.TotalLuminance ?? options.VisualParityReferenceSamples, options.HistogramWidth, options.HistogramHeight, primary.Bounds, @@ -532,12 +537,11 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable private static VisualParityViewReceipt BuildVisualParityView( ReceiptOptions options, VisualParityView view, - IReadOnlyList referencePoints, + FractalPointHistogram referenceHistogram, IReadOnlyList gpuPoints, int width, int height) { - var referenceHistogram = FractalPointHistogramBuilder.Build(referencePoints, width, height, view.Bounds); var gpuHistogram = FractalPointHistogramBuilder.Build(gpuPoints, width, height, view.Bounds); WriteVisualParityImages(options, view.Name, referenceHistogram, gpuHistogram); var metrics = CompareHistograms(referenceHistogram, gpuHistogram); @@ -564,6 +568,124 @@ internal sealed class GpuFractalSplatReceiptRunner : IDisposable metrics.DistributionScorePercent); } + private static Vector2[] BuildCpuFlameReferencePoints(ReceiptOptions options) + { + if (options.ProgramFlamePath is null) + { + throw new ArgumentException("Visual parity needs either --program-flame or --reference-density-ppm."); + } + + var flame = FractalFlameFileParser.ParseFirst(File.ReadAllText(options.ProgramFlamePath), unchecked((int)options.Seed)); + return FractalFlameChaosGame.Generate( + flame, + options.VisualParityReferenceSamples, + options.HistogramBurnIn, + new FractalXorShiftRandom(options.Seed)); + } + + private static ReferenceDensityImage LoadReferenceDensityPpm(string path, Vector4 bounds) + { + var bytes = File.ReadAllBytes(path); + var cursor = 0; + var magic = ReadPpmToken(bytes, ref cursor); + if (!magic.SequenceEqual("P6"u8)) + { + throw new FormatException("External density reference must be a binary P6 PPM image."); + } + + var width = ParsePositivePpmInt(ReadPpmToken(bytes, ref cursor), "width"); + var height = ParsePositivePpmInt(ReadPpmToken(bytes, ref cursor), "height"); + var max = ParsePositivePpmInt(ReadPpmToken(bytes, ref cursor), "max channel value"); + if (max > 255) + { + throw new FormatException("External density reference must be 8-bit PPM."); + } + + ConsumePpmWhitespace(bytes, ref cursor); + var expectedBytes = checked(width * height * 3); + if (bytes.Length - cursor < expectedBytes) + { + throw new FormatException("External density reference ended before all RGB pixels were present."); + } + + var luminance = new int[width * height]; + var total = 0L; + var pixels = bytes.AsSpan(cursor, expectedBytes); + for (var source = 0; source < pixels.Length; source += 3) + { + var r = pixels[source]; + var g = pixels[source + 1]; + var b = pixels[source + 2]; + var value = ((r * 54) + (g * 183) + (b * 19)) >> 8; + var pixelIndex = source / 3; + luminance[pixelIndex] = value; + total += value; + } + + return new ReferenceDensityImage(width, height, bounds, luminance, Math.Max(total, 1L)); + } + + private static ReadOnlySpan ReadPpmToken(ReadOnlySpan bytes, ref int cursor) + { + while (cursor < bytes.Length) + { + if (bytes[cursor] is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n') + { + cursor++; + continue; + } + + if (bytes[cursor] != (byte)'#') + { + break; + } + + while (cursor < bytes.Length && bytes[cursor] != (byte)'\n') + { + cursor++; + } + } + + var start = cursor; + while (cursor < bytes.Length && bytes[cursor] is not ((byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n' or (byte)'#')) + { + cursor++; + } + + if (cursor == start) + { + throw new FormatException("PPM header ended unexpectedly."); + } + + return bytes.Slice(start, cursor - start); + } + + private static void ConsumePpmWhitespace(ReadOnlySpan bytes, ref int cursor) + { + if (cursor >= bytes.Length || bytes[cursor] is not ((byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n')) + { + throw new FormatException("PPM header is missing the pixel-data separator."); + } + + cursor++; + } + + private static int ParsePositivePpmInt(ReadOnlySpan token, string name) + { + var value = 0; + foreach (var digit in token) + { + if (digit is < (byte)'0' or > (byte)'9') + { + throw new FormatException($"PPM {name} is not an integer."); + } + + value = checked((value * 10) + digit - (byte)'0'); + } + + return value > 0 ? value : throw new FormatException($"PPM {name} must be positive."); + } + private static void WriteVisualParityImages( ReceiptOptions options, string viewName, @@ -765,6 +887,7 @@ internal sealed record ReceiptOptions( string OutputDirectory, string? FlamePath, string? ReferencePpmPath, + string? ReferenceDensityPpmPath, string? ProgramFlamePath, int HistogramSamples, int HistogramBurnIn, @@ -797,6 +920,7 @@ internal sealed record ReceiptOptions( null, null, null, + null, 8192, 64, 64, @@ -829,6 +953,7 @@ internal sealed record ReceiptOptions( "--out" => options with { OutputDirectory = Next() }, "--flame" => options with { FlamePath = Next() }, "--reference-ppm" => options with { ReferencePpmPath = Next() }, + "--reference-density-ppm" => options with { ReferenceDensityPpmPath = Next(), VisualParity = true }, "--histogram-samples" => options with { HistogramSamples = int.Parse(Next()) }, "--histogram-burn-in" => options with { HistogramBurnIn = int.Parse(Next()) }, "--histogram-size" => ParseHistogramSize(options, Next()), @@ -872,6 +997,11 @@ internal sealed record ReceiptOptions( throw new FileNotFoundException("Receipt program flame file was not found.", options.ProgramFlamePath); } + if (options.ReferenceDensityPpmPath is not null && !File.Exists(options.ReferenceDensityPpmPath)) + { + throw new FileNotFoundException("External density reference PPM file was not found.", options.ReferenceDensityPpmPath); + } + options = options.ProgramFlamePath is not null && options.ProgramTransformCount <= 0 ? options with { ProgramTransformCount = int.MaxValue, ProgramMode = 2 } : options; @@ -884,9 +1014,9 @@ internal sealed record ReceiptOptions( throw new FileNotFoundException("Receipt shader file was not found.", options.ShaderPath); } - if (options.VisualParity && options.ProgramFlamePath is null) + if (options.VisualParity && options.ProgramFlamePath is null && options.ReferenceDensityPpmPath is null) { - throw new ArgumentException("Visual parity requires --program-flame so the GPU distribution has a CPU flame oracle."); + throw new ArgumentException("Visual parity requires --program-flame or --reference-density-ppm."); } if (options.SplatCount <= 0 || options.WarmupSplatUpdatesPerFrame <= 0 || options.WarmupSplatUpdatesPerFrame > options.SplatCount || options.SplatUpdatesPerFrame <= 0 || options.SplatUpdatesPerFrame > options.SplatCount || options.WarmupFrames < 0 || options.MeasuredFrames <= 0 || options.Depth <= 0 || options.CandidatesPerPass <= 0 || options.ReservoirUpdatesPerPass <= 0 || options.ReservoirUpdatesPerPass > options.SplatCount || options.ProgramTransformCount < 0 || options.ProgramMode < 0 || options.ProgramMode > 2 || options.ReadbackSplats < 0 || options.VisualParityReferenceSamples <= 0) @@ -977,9 +1107,56 @@ internal sealed record FlameImportReportReceipt( internal readonly record struct VisualParityView(string Name, Vector4 Bounds); +internal readonly record struct ReferenceDensityImage( + int Width, + int Height, + Vector4 Bounds, + int[] Luminance, + long TotalLuminance) +{ + public FractalPointHistogram ToHistogram(int width, int height, Vector4 viewBounds) + { + var bins = new int[width * height]; + var sourceSpan = new Vector2(Bounds.Z - Bounds.X, Bounds.W - Bounds.Y); + var viewSpan = new Vector2(viewBounds.Z - viewBounds.X, viewBounds.W - viewBounds.Y); + for (var sourceY = 0; sourceY < Height; sourceY++) + { + var worldY = Bounds.Y + ((Height - 0.5f - sourceY) / Math.Max(Height, 1)) * sourceSpan.Y; + var v = (worldY - viewBounds.Y) / MathF.Max(viewSpan.Y, 0.000001f); + if (v < 0.0f || v >= 1.0f) + { + continue; + } + + var targetY = Math.Clamp((int)(v * height), 0, height - 1); + for (var sourceX = 0; sourceX < Width; sourceX++) + { + var value = Luminance[(sourceY * Width) + sourceX]; + if (value == 0) + { + continue; + } + + var worldX = Bounds.X + ((sourceX + 0.5f) / Math.Max(Width, 1)) * sourceSpan.X; + var u = (worldX - viewBounds.X) / MathF.Max(viewSpan.X, 0.000001f); + if (u < 0.0f || u >= 1.0f) + { + continue; + } + + var targetX = Math.Clamp((int)(u * width), 0, width - 1); + bins[(targetY * width) + targetX] += value; + } + } + + return new FractalPointHistogram(width, height, viewBounds, bins); + } +} + internal sealed record VisualParityReceipt( + string ReferenceSource, int ComparedSamples, - int ReferenceSamples, + long ReferenceSamples, int Width, int Height, float[] Bounds,