Add flame fractal DSL resource planning

This commit is contained in:
Meta Vens 2026-05-19 13:33:38 +01:00
commit 5b4c13efab
15 changed files with 455 additions and 6 deletions

View file

@ -221,6 +221,8 @@ Tasks:
- [x] Add debug dump for authored tree and flattened packets.
- [x] Preserve multiple `.aquageo` tile roots in the ownership tree instead of
collapsing every claim under the final tile.
- [x] Add compact `flame` grammar primitive for deterministic curled recursive
brush emission.
Tests:
@ -280,6 +282,8 @@ Tasks:
- [x] Add hysteresis fade weights.
- [x] Add budget clamp.
- [x] Add debug channels: score, depth, fade, estimated cost.
- [x] Add explicit resource budget plan for CPU update count, GPU estimated
packet cost, RAM residency, and SSD request pressure.
Tests:
@ -338,6 +342,7 @@ Tasks:
- [x] Add child request queue.
- [ ] Add score/cost eviction policy.
- [x] Add parent-summary fallback path.
- [x] Clamp simulated RAM residency and SSD requests through the resource plan.
- [x] Add debug channels: residency, requests, evictions.
Tests:
@ -363,9 +368,12 @@ Tasks:
- [x] Add Zyphos cube-sphere domain root.
- [x] Add first tile grammar: ridges, craters, and material bands.
- [x] Add first flame-style microdetail grammar line inside the Zyphos leaf
domain.
- [x] Lower selected cut to shaped 2D height/material brush packets.
- [x] Feed planet shader from tile-local cube-face domains for post-hit
material/detail evaluation.
- [x] Route Zyphos render-plan construction through the resource budget planner.
- [ ] Feed traced planet geometry from selected-cut/resident tile packets.
- [ ] Add face/tile/LOD/cache debug modes.
- [ ] Remove or quarantine old spherical noise path as baseline fixture.

View file

@ -0,0 +1,22 @@
namespace Aquarium.Engine.Fractal;
public sealed class FractalXorShiftRandom(uint seed) : IFractalRandom
{
private uint state = seed == 0 ? 0xA341316Cu : seed;
public double NextDouble()
{
var value = NextUInt32();
return value / ((double)uint.MaxValue + 1.0);
}
private uint NextUInt32()
{
var value = state;
value ^= value << 13;
value ^= value >> 17;
value ^= value << 5;
state = value;
return value;
}
}

View file

@ -67,6 +67,15 @@ public static class FractalDslCompiler
AddIfsClaims(tokens, ifsDomain.Key, currentNode!.Key, lineIndex, claims);
currentNode.ClaimCount += claims.Count - beforeIfs;
break;
case "flame":
EnsureDomain(domain, lineIndex);
EnsureNode(currentNode, lineIndex);
EnsureTokenCount(tokens, 15, lineIndex);
var flameDomain = domain!.Value;
var beforeFlame = claims.Count;
AddFlameClaims(tokens, flameDomain.Key, currentNode!.Key, lineIndex, claims);
currentNode.ClaimCount += claims.Count - beforeFlame;
break;
default:
throw new FormatException($"Unknown fractal DSL command `{tokens[0]}` at line {lineIndex + 1}.");
}
@ -144,6 +153,30 @@ public static class FractalDslCompiler
EmitIfsLevel(domainKey, nodeKey, name, center, radii, levels, branches, childScale, spread, rotationStep, falloff, shapePower, amplitude, seed, tags, claims);
}
private static void AddFlameClaims(string[] tokens, AquariumFractalKey domainKey, AquariumFractalKey nodeKey, int lineIndex, List<AquariumBrushClaim> claims)
{
var name = tokens[1];
var levels = ParsePositiveInt(tokens[2], lineIndex);
var branches = ParsePositiveInt(tokens[3], lineIndex);
var center = new Vector2(ParseFloat(tokens[4], lineIndex), ParseFloat(tokens[5], lineIndex));
var radii = new Vector2(ParsePositiveFloat(tokens[6], lineIndex), ParsePositiveFloat(tokens[7], lineIndex));
var childScale = ParsePositiveFloat(tokens[8], lineIndex);
var curl = ParseFloat(tokens[9], lineIndex);
var spread = ParsePositiveFloat(tokens[10], lineIndex);
var falloff = ParsePositiveFloat(tokens[11], lineIndex);
var shapePower = ParsePositiveFloat(tokens[12], lineIndex);
var amplitude = ParseFloat(tokens[13], lineIndex);
var seed = ParseInt(tokens[14], lineIndex);
var tags = tokens.Length >= 16 ? tokens[15] : name;
if (childScale >= 1.0f)
{
throw new FormatException($"Flame child scale must be below 1 at line {lineIndex + 1}.");
}
EmitFlameLevel(domainKey, nodeKey, name, center, radii, 0.0f, levels, branches, childScale, curl, spread, falloff, shapePower, amplitude, seed, tags, claims);
}
private static void EmitIfsLevel(
AquariumFractalKey domainKey,
AquariumFractalKey nodeKey,
@ -191,6 +224,62 @@ public static class FractalDslCompiler
amplitude * childScale,
seed + 31 + branch,
tags,
claims);
}
}
private static void EmitFlameLevel(
AquariumFractalKey domainKey,
AquariumFractalKey nodeKey,
string name,
Vector2 center,
Vector2 radii,
float spiralAngle,
int levelsRemaining,
int branches,
float childScale,
float curl,
float spread,
float falloff,
float shapePower,
float amplitude,
int seed,
string tags,
List<AquariumBrushClaim> claims)
{
var level = claims.Count;
var rotation = spiralAngle + curl * level;
claims.Add(HeightClaim(domainKey, nodeKey, $"{name}/{level}", claims.Count, center, radii, rotation, falloff, shapePower, amplitude, seed + level, tags));
if (levelsRemaining <= 1)
{
return;
}
var nextRadii = radii * childScale;
var branchStep = MathF.Tau / branches;
for (var branch = 0; branch < branches; branch++)
{
var turn = spiralAngle + curl + (branchStep * branch) + HashAngle(seed, level, branch) * 0.5f;
var reach = spread * MathF.Max(nextRadii.X, nextRadii.Y) * (1.0f + branch * 0.17f);
var offset = new Vector2(MathF.Cos(turn), MathF.Sin(turn)) * reach;
EmitFlameLevel(
domainKey,
nodeKey,
name,
center + offset,
nextRadii,
turn,
levelsRemaining - 1,
branches,
childScale,
curl,
spread,
falloff,
shapePower,
amplitude * MathF.Sqrt(childScale),
seed + 97 + (branch * 17),
tags,
claims);
}
}

View file

@ -5,10 +5,29 @@ namespace Aquarium.Engine.Fractal.Lod;
public static class FractalResidencyPlanner
{
public static FractalResidencyPlan Plan(IReadOnlyList<AquariumSelectedCut> selectedCut, IFractalPayloadStore payloadStore)
{
return Plan(selectedCut, payloadStore, maxRequests: int.MaxValue, maxResidentNodes: int.MaxValue);
}
public static FractalResidencyPlan Plan(
IReadOnlyList<AquariumSelectedCut> selectedCut,
IFractalPayloadStore payloadStore,
int maxRequests,
int maxResidentNodes)
{
ArgumentNullException.ThrowIfNull(selectedCut);
ArgumentNullException.ThrowIfNull(payloadStore);
if (maxRequests < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxRequests), maxRequests, "Request budget must not be negative.");
}
if (maxResidentNodes < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxResidentNodes), maxResidentNodes, "Resident budget must not be negative.");
}
var resident = new List<AquariumFractalKey>();
var fallback = new List<AquariumFractalKey>();
var requested = new List<AquariumFractalKey>();
@ -17,12 +36,20 @@ public static class FractalResidencyPlanner
{
if (payloadStore.IsResident(cut.NodeKey))
{
resident.Add(cut.NodeKey);
if (resident.Count < maxResidentNodes)
{
resident.Add(cut.NodeKey);
}
else
{
fallback.Add(cut.NodeKey);
}
continue;
}
fallback.Add(cut.NodeKey);
if (cut.RequestedChildren)
if (cut.RequestedChildren && requested.Count < maxRequests)
{
payloadStore.Request(cut.NodeKey);
requested.Add(cut.NodeKey);

View file

@ -0,0 +1,62 @@
using Aquarium.Engine.Fractal;
namespace Aquarium.Engine.Fractal.Lod;
public readonly record struct FractalResourceBudget(
int MaxCpuUpdates,
float MaxGpuEstimatedCost,
int MaxResidentPayloads,
int MaxSsdRequests)
{
public static FractalResourceBudget Empty { get; } = new(0, 0.0f, 0, 0);
public void Validate()
{
if (MaxCpuUpdates < 0)
{
throw new ArgumentOutOfRangeException(nameof(MaxCpuUpdates), MaxCpuUpdates, "CPU update budget must not be negative.");
}
if (MaxGpuEstimatedCost < 0.0f)
{
throw new ArgumentOutOfRangeException(nameof(MaxGpuEstimatedCost), MaxGpuEstimatedCost, "GPU packet budget must not be negative.");
}
if (MaxResidentPayloads < 0)
{
throw new ArgumentOutOfRangeException(nameof(MaxResidentPayloads), MaxResidentPayloads, "Resident payload budget must not be negative.");
}
if (MaxSsdRequests < 0)
{
throw new ArgumentOutOfRangeException(nameof(MaxSsdRequests), MaxSsdRequests, "SSD request budget must not be negative.");
}
}
}
public sealed class FractalResourcePlan
{
public FractalResourcePlan(
AquariumSelectedCut[] selectedCut,
AquariumFractalKey[] updateNodes,
FractalResidencyPlan residency,
float gpuEstimatedCost,
FractalResourceBudget budget)
{
SelectedCut = selectedCut;
UpdateNodes = updateNodes;
Residency = residency;
GpuEstimatedCost = gpuEstimatedCost;
Budget = budget;
}
public AquariumSelectedCut[] SelectedCut { get; }
public AquariumFractalKey[] UpdateNodes { get; }
public FractalResidencyPlan Residency { get; }
public float GpuEstimatedCost { get; }
public FractalResourceBudget Budget { get; }
}

View file

@ -0,0 +1,50 @@
using Aquarium.Engine.Fractal;
namespace Aquarium.Engine.Fractal.Lod;
public static class FractalResourceBudgetPlanner
{
public static FractalResourcePlan Plan(
IReadOnlyList<AquariumFractalSummary> summaries,
IReadOnlyList<AquariumContributionState> states,
Func<AquariumFractalSummary, float> projectedPixelsPerWorldUnit,
Func<AquariumContributionState, float> currentScore,
FractalResourceBudget budget,
IFractalRandom random,
IFractalPayloadStore payloadStore,
uint frameIndex)
{
ArgumentNullException.ThrowIfNull(summaries);
ArgumentNullException.ThrowIfNull(states);
ArgumentNullException.ThrowIfNull(projectedPixelsPerWorldUnit);
ArgumentNullException.ThrowIfNull(currentScore);
ArgumentNullException.ThrowIfNull(random);
ArgumentNullException.ThrowIfNull(payloadStore);
budget.Validate();
var selectedCut = FractalSelectedCutBuilder.Build(summaries, projectedPixelsPerWorldUnit, budget.MaxGpuEstimatedCost);
var updateNodes = FractalStochasticUpdateScheduler.SelectUpdates(states, currentScore, budget.MaxCpuUpdates, random, frameIndex);
var residency = FractalResidencyPlanner.Plan(selectedCut, payloadStore, budget.MaxSsdRequests, budget.MaxResidentPayloads);
return new FractalResourcePlan(
selectedCut,
updateNodes,
residency,
EstimatedCost(summaries, selectedCut),
budget);
}
private static float EstimatedCost(IReadOnlyList<AquariumFractalSummary> summaries, IReadOnlyList<AquariumSelectedCut> selectedCut)
{
var summariesByKey = summaries.ToDictionary(summary => summary.NodeKey.Value, StringComparer.Ordinal);
var cost = 0.0f;
foreach (var cut in selectedCut)
{
cost += summariesByKey.TryGetValue(cut.NodeKey.Value, out var summary)
? MathF.Max(summary.EstimatedCost, 1.0f)
: 1.0f;
}
return cost;
}
}

View file

@ -23,6 +23,7 @@ height shelf 17 -8 9 3.5 0.35 3.4 1.1 0.045 43 shelf
ifs vein 2 2 14 -11 4.2 1.1 0.42 3.8 1.12 4.8 0.78 0.035 47 vein
tile NegativeX 2 2 1 zyphos/greenleaf-canopy zyphos/canopy-leaf
ifs leaf 3 3 9 9 1.8 0.72 0.42 2.8 0.61 6.0 0.58 0.018 101 leaf
flame veinlet 2 2 10.4 8.2 0.92 0.28 0.42 0.78 3.2 6.5 0.62 0.012 103 flame-leaf
tile NegativeZ 2 1 2 zyphos/pebble-field zyphos/pebble-field
ifs pebble 3 2 -11 13 1.2 0.9 0.48 3.4 -0.77 8.0 0.64 0.022 107 pebble
tile PositiveZ 0 0 0 umbros/first-fractal-terrain zyphos/umbros-latlong

View file

@ -14,10 +14,23 @@ public static class ZyphosFractalTerrain
private static readonly Lazy<string> PatchSource = new(() => File.ReadAllText(PatchPath));
private static readonly Lazy<FractalOwnershipTree> Tree = new(() => FractalDslCompiler.Compile(PatchSource.Value));
private static readonly Lazy<AquariumFractalSummary[]> Summaries = new(() => FractalSummaryBuilder.Build(Tree.Value));
private static readonly Lazy<AquariumContributionState[]> ContributionStates = new(() => Summaries.Value.Select(summary => new AquariumContributionState(
summary.NodeKey,
MeanContribution: 0.0f,
Variance: MathF.Max(summary.MaxHeightError, 0.001f),
Confidence: 0.0f,
SampleCount: 0,
LastSampledFrame: 0,
Resident: true)).ToArray());
private static readonly Lazy<AquariumSelectedCut[]> SelectedCut = new(() => FractalSelectedCutBuilder.Build(Summaries.Value, _ => 8.0f, maxEstimatedCost: 64.0f));
private static readonly Lazy<AquariumHeightFieldBrush[]> Brushes = new(() => FractalHeightBrushCompiler.CompileSelectedTree(Tree.Value, SelectedCut.Value));
private static readonly object PlanCacheLock = new();
private static readonly Dictionary<int, ZyphosFractalRenderPlan> PlanCache = [];
private static readonly FractalResourceBudget DefaultBudget = new(
MaxCpuUpdates: 2,
MaxGpuEstimatedCost: 64.0f,
MaxResidentPayloads: 64,
MaxSsdRequests: 2);
public static string PatchPath => Path.Combine(AppContext.BaseDirectory, PatchRelativePath);
@ -44,13 +57,22 @@ public static class ZyphosFractalTerrain
}
var bucketPixelsPerWorld = bucket / 16.0f;
var selectedCut = FractalSelectedCutBuilder.Build(Summaries.Value, _ => bucketPixelsPerWorld, maxEstimatedCost: 64.0f);
var resourcePlan = FractalResourceBudgetPlanner.Plan(
Summaries.Value,
ContributionStates.Value,
_ => bucketPixelsPerWorld,
state => ScoreForState(state, bucketPixelsPerWorld),
DefaultBudget,
new FractalXorShiftRandom((uint)bucket ^ 0x9E3779B9u),
ResidentFractalPayloadStore.Instance,
frameIndex: (uint)bucket);
var selectedCut = resourcePlan.SelectedCut;
var brushes = FractalHeightBrushCompiler.CompileSelectedTree(Tree.Value, selectedCut);
var plan = new ZyphosFractalRenderPlan(
brushes,
selectedCut,
bucketPixelsPerWorld,
$"{selectedCut.Length}/{Summaries.Value.Length} cuts / {brushes.Length}/{OwnershipTree.Claims.Count} brushes / {bucketPixelsPerWorld:0.00} px-wu");
$"{selectedCut.Length}/{Summaries.Value.Length} cuts / {brushes.Length}/{OwnershipTree.Claims.Count} brushes / {resourcePlan.UpdateNodes.Length}/{DefaultBudget.MaxCpuUpdates} cpu updates / {resourcePlan.GpuEstimatedCost:0.0}/{DefaultBudget.MaxGpuEstimatedCost:0.0} gpu cost / {resourcePlan.Residency.ResidentNodes.Count}/{DefaultBudget.MaxResidentPayloads} resident / {resourcePlan.Residency.RequestedNodes.Count}/{DefaultBudget.MaxSsdRequests} ssd requests / {bucketPixelsPerWorld:0.00} px-wu");
lock (PlanCacheLock)
{
@ -62,6 +84,33 @@ public static class ZyphosFractalTerrain
public static string Summary =>
$"{Path.GetFileName(PatchPath)} / {OwnershipTree.Claims.Count} DSL claims / {OwnershipTree.Nodes.Count} tile nodes / {SelectedCut.Value.Length} cuts / {HeightBrushes.Length} shaped brushes";
private static float ScoreForState(AquariumContributionState state, float pixelsPerWorld)
{
foreach (var summary in Summaries.Value)
{
if (summary.NodeKey == state.NodeKey)
{
return FractalProjectedErrorScorer.Score(summary, pixelsPerWorld);
}
}
return 0.0f;
}
private sealed class ResidentFractalPayloadStore : IFractalPayloadStore
{
public static ResidentFractalPayloadStore Instance { get; } = new();
public bool IsResident(AquariumFractalKey nodeKey)
{
return true;
}
public void Request(AquariumFractalKey nodeKey)
{
}
}
}
public readonly record struct ZyphosFractalRenderPlan(

View file

@ -149,3 +149,4 @@
{"lesson":"The first live bridge from the fractal architecture into Zyphos SDF rendering is material/detail, not traced form: .aquageo now preserves multiple tile roots, height brush packets carry cube-tile face/level/x/y metadata, D3D12 binds that packet table into the SDF pass, and the planet shader evaluates authored brushes in cube-face tile space after hit. Evaluating all authored brushes inside sdfDistance was tested and cut because it pushed the live frame toward 50-100 ms; traced geometry needs selected-cut/resident packet policy first.","timestamp":"2026-05-18T11:28:00+01:00","files":["src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs","src/Aquarium.Engine.Fractal/Brushes/FractalHeightBrushCompiler.cs","src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine/Render/Features/D3D12HeightFieldBrushConstants.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"user pointed out the renderer was only a pile of legos and ordered the real machine to be built","topic":"zyphos-aquageo-tile-packet-sdf-bridge"}
{"timestamp":"2026-05-18T12:22:00+01:00","topic":"fractal-temporal-detail-control","lesson":"Fractal cache influence now has a first TAA-facing lane. SdfSurface carries temporalDetail, SDF proxy writes it into scene-control.z, D3D12Post validates history continuity against the current and previous temporalDetail signal, and history-control.z preserves it across frames. Zyphos feeds this from authored cube-face brush material influence; other SDFs explicitly emit zero until they gain cache-owned detail.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","src/Aquarium.Epiphany/Shaders"],"source":"user said to weave the stochastic fractal cache into TAA buffers"}
{"timestamp":"2026-05-18T18:09:50+01:00","topic":"temporal-sdf-gaussian-renderer-boundary","lesson":"Live sensor-fusion splats now enter Aquarium through an engine-owned temporal SDF Gaussian field instead of client-side renderer folklore. The contract carries stable keyed world-space Gaussians; `TemporalGaussianAccumulator` buffers observations with presentation delay and history weights; D3D12 uploads structured packets and renders an instanced compact-kernel splat pass into the existing scene/metadata/control targets. Scaling beyond 4096 splats belongs to Aquarium residency/binning, not LocalCastBridge.","files":["src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianAccumulator.cs","src/Aquarium.Engine/Render/Shaders/D3D12TemporalGaussian.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs","docs/temporal-sdf-gaussian-field.md"],"source":"user directed the point-cloud/TAA renderer feature to be implemented on the Aquarium side for clean client consumption"}
{"timestamp":"2026-05-19T13:38:00+01:00","topic":"fractal-resource-budget-and-flame-dsl","lesson":"The fractal DSL now has a compact `flame` primitive for deterministic curled recursive brush emission, and Zyphos exercises it in a leaf microdetail domain without exceeding the 64-brush stress table. Fractal render planning now coordinates CPU stochastic update count, GPU selected-cut estimated cost, RAM resident payload budget, and SSD request budget before packet compilation. This budget vocabulary should remain compatible with Mimir-style sensor fusion because both pipelines accumulate confidence-weighted spatial samples into temporal reservoirs before rendering a resolved field.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs","src/Aquarium.Engine.Fractal/Lod/FractalResourceBudget.cs","src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs","src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/Worlds/zyphos-first-fractal-terrain.aquageo","tests/Aquarium.Engine.Fractal.Tests/FractalResourceBudgetPlannerTests.cs"],"source":"user demanded full fractal SDF rendering and noted Mimir sensor fusion shares the same temporal spatial evidence shape"}

View file

@ -121,13 +121,14 @@ renderer_state:
- Aquarium frames now carry a 3D camera target in addition to the legacy 2D ViewFrame center. Zyphos uses a camera composer to separate tracked subject, parent composition anchor, and camera orbit distance.
- Zyphos camera navigation is domain-key driven: selecting any solar/orbital/planetary/surface/object/tile domain in the floating Navigation tree changes the active camera mode, derives the parent pivot from the domain hierarchy, and lets mouse drag/wheel orbit or zoom that selected spatial frame. Zyphos and Umbros both expose lat/long surface domains, recursive subdomains, object-scale domains, and cube-tile children.
- Zyphos domain zoom is scale-aware: leaf/pebble domains can drive the camera below planetary distances, while larger domains retain broad framing. The parent star is a rendered SDF object as well as a light source, so selecting the Solar domain targets a visible sun instead of an invisible lamp.
- The current height-field stress backend uploads a fixed table of 64 shaped 2D brushes to D3D12. The richer Zyphos/Umbros .aquageo patch currently emits 58 brushes across recursive continent/forest/leaf/coast/pebble and Umbros crater/boulder/pebble domains.
- The current height-field stress backend uploads a fixed table of 64 shaped 2D brushes to D3D12. The richer Zyphos/Umbros .aquageo patch currently emits 61 brushes across recursive continent/forest/leaf/flame/coast/pebble and Umbros crater/boulder/pebble domains.
- Zyphos and Umbros SDF planet shaders include cheap bounded quadtree-style layered relief in object space, separate from the flattened 2D height-brush stress path.
- SceneState can disable the legacy height-field surface trace and request a procedural starfield background; Zyphos uses this for space views so the old Grid does not leak into planetary rendering.
- Future multiscale terrain and agent/body detail should come from bounded IFS brush grammars using shared shaped anisotropic envelopes; texture/material detail can be abundant, but traced SDF form detail must be proxy-bounded, LOD-gated, and measured.
- The IFS brush grammar should preserve a semantic ownership tree before backend lowering: local frames, deterministic seeds, named fields/captures, tags, payload bindings, LOD/cost tiers, and boolean-style union/subtract/common nodes should survive even if the first renderer path flattens them into fixed brush tables or SDF shader code.
- IFS LOD should be driven by cached node contribution summaries: each node carries bounds, projected error/material delta, coverage, cost, estimator state, residency, and summary/child payload handles so traversal can choose a stable hierarchy cut and render parent summaries while child details stream or fade in.
- Contribution weights cannot all be refreshed every frame; the cache needs a probabilistic online estimator that samples nodes under budget, updates mean/uncertainty/sample age/confidence, preserves nonzero exploration for visible or near-threshold nodes, and can later become a learned predictor without replacing conservative SDF bounds.
- Fractal resource planning is explicit: one plan coordinates CPU contribution updates, GPU selected-cut estimated cost, RAM resident payload budget, and SSD request pressure before backend packet compilation. This same budget language should generalize to Mimir-style sensor fusion because both fractal SDF probes and camera/microphone feature detections accumulate confidence-weighted spatial samples into temporal reservoirs.
- The consolidated fractal brush architecture plan defines the intended pipeline: client intent -> domain roots -> semantic IFS brush grammar -> ownership tree -> node summaries -> contribution cache/residency scheduler -> backend packets -> renderer passes -> debug/evidence, with explicit module boundaries and mockable unit-test seams.
- The actionable fractal brush implementation roadmap lives in research/rendering/fractal-brush-implementation-roadmap.md and is the execution authority for the first pass.
- Bundled blue-noise texture assets are retained for future dithering/noise work even though the removed medium path no longer samples them.

View file

@ -79,6 +79,7 @@
"VibeGeometry's `vg_grammar` and `vg_csg` tree are the local model for Aquarium's future IFS brush DSL: emit semantic claims with local frames, deterministic seeds, tags, captures/fields, payload bindings, LOD/cost tiers, and boolean ownership nodes before lowering to renderer backends. The authored tree is durable design; flattened brush tables, SDF includes, splat batches, or offline mips are compiled verdicts.",
"IFS LOD should choose a stable hierarchy cut from cached node summaries, not blindly score every leaf. Each node needs bounds, max form/material error, coverage/normal or gradient bounds, estimated cost, online estimator state, residency, and summary/child payload handles. Children fade in when projected contribution exceeds threshold and resident budget allows; parent summaries remain renderable fallbacks.",
"The IFS contribution cache must probabilistically refresh node weights under a per-frame update budget. Use online mean/variance/confidence/sample-age state with nonzero exploration for visible or near-threshold nodes so weights converge instead of freezing stale guesses. Learned scoring may later rank update and residency priority from observed high-quality probes, but conservative summaries remain the safety authority for SDF bounds and visibility.",
"Aquarium's fractal renderer and Mimir-style sensor fusion share a deeper shape: both accumulate confidence-weighted spatial evidence into temporal reservoirs, then render a resolved surface/volume field. Keep the budget planner vocabulary general enough for CPU update work, GPU packet cost, RAM residency, and SSD request pressure; do not trap the future shared machinery inside renderer-only folklore.",
"Zyphos fractal stress data should keep authored topology richer than the first renderer backend: both Zyphos and Umbros expose lat/long, surface, object-scale, and cube-tile domains in `.aquageo`, with explicit continent/forest/tree/leaf/coast/pebble and crater/boulder/pebble recursion. The current D3D12 height-field stress table uploads 64 shaped 2D brushes and the SDF planet shaders carry separate cheap bounded quadtree-style relief.",
"The `.aquageo` compiler must preserve each tile declaration as its own ownership-tree node. Collapsing every claim under the final tile makes the authored multi-domain world a lie even if the brush count looks impressive.",
"Zyphos passes cube-tile domain metadata through height brush packets and binds those packets into the SDF pass. The planet shader may use authored brush packets for post-hit material/detail evaluation; traced geometry must wait for selected-cut/resident packet policy so SDF distance loops do not evaluate every brush at every step.",

View file

@ -63,6 +63,25 @@ public sealed class FractalDslCompilerTests
Assert.All(first.Claims, claim => Assert.Equal("crater", claim.Tags));
}
[Fact]
public void DslFlameEmitsCompactCurlingRecursiveClaims()
{
const string source = """
tile PositiveZ 0 0 0 zyphos/terrain
flame ember 3 2 1 -2 6 2 0.45 0.72 3.1 5.0 0.8 0.05 23 flame
""";
var first = FractalDslCompiler.Compile(source);
var second = FractalDslCompiler.Compile(source);
Assert.Equal(7, first.Claims.Count);
Assert.Equal(first.Claims, second.Claims);
Assert.All(first.Claims, claim => Assert.Equal("flame", claim.Tags));
Assert.True(first.Claims[1].Radii.X < first.Claims[0].Radii.X);
Assert.NotEqual(first.Claims[1].Center, first.Claims[2].Center);
Assert.NotEqual(first.Claims[0].RotationRadians, first.Claims[1].RotationRadians);
}
[Fact]
public void DslPreservesMultipleTileRoots()
{

View file

@ -35,6 +35,30 @@ public sealed class FractalResidencyPlannerTests
Assert.Empty(store.Requests);
}
[Fact]
public void ResidencyPlannerRespectsRamAndSsdBudgets()
{
var residentA = new AquariumFractalKey("node/resident-a");
var residentB = new AquariumFractalKey("node/resident-b");
var missingA = new AquariumFractalKey("node/missing-a");
var missingB = new AquariumFractalKey("node/missing-b");
var store = new TestPayloadStore([residentA, residentB]);
var cuts = new[]
{
new AquariumSelectedCut(residentA, Score: 4.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: true),
new AquariumSelectedCut(residentB, Score: 3.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: true),
new AquariumSelectedCut(missingA, Score: 2.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: true),
new AquariumSelectedCut(missingB, Score: 1.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: true),
};
var plan = FractalResidencyPlanner.Plan(cuts, store, maxRequests: 1, maxResidentNodes: 1);
Assert.Equal([residentA], plan.ResidentNodes);
Assert.Equal([residentB, missingA, missingB], plan.SummaryFallbackNodes);
Assert.Equal([missingA], plan.RequestedNodes);
Assert.Equal([missingA], store.Requests);
}
private sealed class TestPayloadStore(IEnumerable<AquariumFractalKey>? resident = null) : IFractalPayloadStore
{
private readonly HashSet<string> residentKeys = resident?.Select(key => key.Value).ToHashSet(StringComparer.Ordinal) ?? [];

View file

@ -0,0 +1,94 @@
using System.Numerics;
using Aquarium.Engine.Fractal;
using Aquarium.Engine.Fractal.Lod;
namespace Aquarium.Engine.Fractal.Tests;
public sealed class FractalResourceBudgetPlannerTests
{
[Fact]
public void ResourcePlannerCoordinatesCpuGpuRamAndSsdBudgets()
{
var summaries = new[]
{
Summary("node/a", maxHeightError: 2.0f, estimatedCost: 2.0f),
Summary("node/b", maxHeightError: 1.5f, estimatedCost: 2.0f),
Summary("node/c", maxHeightError: 1.0f, estimatedCost: 2.0f),
};
var states = summaries.Select(summary => new AquariumContributionState(
summary.NodeKey,
MeanContribution: 0.0f,
Variance: 1.0f,
Confidence: 0.0f,
SampleCount: 0,
LastSampledFrame: 0,
Resident: false)).ToArray();
var store = new TestPayloadStore([summaries[0].NodeKey]);
var budget = new FractalResourceBudget(
MaxCpuUpdates: 1,
MaxGpuEstimatedCost: 4.0f,
MaxResidentPayloads: 1,
MaxSsdRequests: 1);
var plan = FractalResourceBudgetPlanner.Plan(
summaries,
states,
_ => 4.0f,
_ => 1.0f,
budget,
new TestFractalRandom(0.01, 0.01, 0.01),
store,
frameIndex: 10);
Assert.Equal(1, plan.UpdateNodes.Length);
Assert.True(plan.GpuEstimatedCost <= budget.MaxGpuEstimatedCost);
Assert.True(plan.Residency.ResidentNodes.Count <= budget.MaxResidentPayloads);
Assert.True(plan.Residency.RequestedNodes.Count <= budget.MaxSsdRequests);
Assert.Equal(plan.Residency.RequestedNodes, store.Requests);
Assert.Equal(budget, plan.Budget);
}
[Fact]
public void ResourcePlannerRejectsNegativeBudgets()
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => FractalResourceBudgetPlanner.Plan(
[],
[],
_ => 0.0f,
_ => 0.0f,
new FractalResourceBudget(MaxCpuUpdates: -1, MaxGpuEstimatedCost: 0.0f, MaxResidentPayloads: 0, MaxSsdRequests: 0),
new TestFractalRandom(0.5),
new TestPayloadStore(),
frameIndex: 0));
Assert.Equal("MaxCpuUpdates", ex.ParamName);
}
private static AquariumFractalSummary Summary(string key, float maxHeightError, float estimatedCost)
{
return new AquariumFractalSummary(
new AquariumFractalKey(key),
Vector4.Zero,
maxHeightError,
MaxMaterialDelta: 0.0f,
estimatedCost,
DescendantCount: 1);
}
private sealed class TestPayloadStore(IEnumerable<AquariumFractalKey>? resident = null) : IFractalPayloadStore
{
private readonly HashSet<string> residentKeys = resident?.Select(key => key.Value).ToHashSet(StringComparer.Ordinal) ?? [];
public List<AquariumFractalKey> Requests { get; } = [];
public bool IsResident(AquariumFractalKey nodeKey)
{
return residentKeys.Contains(nodeKey.Value);
}
public void Request(AquariumFractalKey nodeKey)
{
Requests.Add(nodeKey);
}
}
}

View file

@ -24,13 +24,14 @@ public sealed class ZyphosFractalTerrainTests
Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.CubeSphereTile && domain.ParentKey.Value == "umbros/pebble-field");
Assert.Equal(new AquariumFractalKey("umbros/pebble-field"), tree.Domain.ParentKey);
Assert.Equal(7, tree.Nodes.Count);
Assert.Equal(58, tree.Claims.Count);
Assert.Equal(61, tree.Claims.Count);
Assert.Equal(tree.Claims.Count, brushes.Length);
Assert.Contains(tree.Claims, claim => claim.Tags == "crater");
Assert.Contains(tree.Claims, claim => claim.Tags == "ridge");
Assert.Contains(tree.Claims, claim => claim.Tags == "shard");
Assert.Contains(tree.Claims, claim => claim.Tags == "crown");
Assert.Contains(tree.Claims, claim => claim.Tags == "leaf");
Assert.Contains(tree.Claims, claim => claim.Tags == "flame-leaf");
Assert.Contains(tree.Claims, claim => claim.Tags == "pebble");
Assert.Contains(brushes, brush => brush.EnvelopeFalloff > 0.0f && brush.RadiusY > 0.0f);
}