From e57dc3ece6a132a22b1f858a7bde11b862cf12d0 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 8 May 2026 21:29:47 +0100 Subject: [PATCH] Add SDF field renderer plan and cloud prototype --- docs/hlsl-renderer.md | 33 ++++ docs/sdf-field-renderer-plan.md | 179 ++++++++++++++++++ .../Render/Shaders/Aquarium.hlsl | 169 +++++++++++++++++ state/evidence.jsonl | 1 + state/map.yaml | 4 + state/memory.json | 2 + state/scratch.md | 12 +- 7 files changed, 396 insertions(+), 4 deletions(-) create mode 100644 docs/sdf-field-renderer-plan.md diff --git a/docs/hlsl-renderer.md b/docs/hlsl-renderer.md index 6458bb8..8ce5cda 100644 --- a/docs/hlsl-renderer.md +++ b/docs/hlsl-renderer.md @@ -37,6 +37,12 @@ Volumetric lighting, brick maps, HDR bloom, and debug controls are not one-pass pixel-shader jobs. They need engine systems around the shader rather than more stuffing in `AquariumPS`. +The SDF field renderer plan lives in `docs/sdf-field-renderer-plan.md`. Its +central constraint is that Aquarium/Aetheria-style clouds are local SDF media: +above, below, around, and sometimes enclosing the camera. They are not a fancy +skybox, so sky-dome/paraboloid-only cloud optimizations are not valid as the core +cloud architecture. + ## Deferred Grid Pass The renderer now has a deferred Grid height target. @@ -87,6 +93,33 @@ shader pattern: height contours are derived from the Grid height field, while angle lines quantize the terrain gradient direction and fade out on flat surfaces. +## SDF Cloud Prototype + +`AquariumPS` now includes a first analytic SDF cloud-medium prototype. It defines +four bounded local cloud fields in world/Grid space, including clouds below and +around the Grid, then integrates density and single-scattering along the camera +ray before compositing the nearest solid surface: + +```text +color = cloud_scattering + cloud_transmittance * surface_color +``` + +This is intentionally a prototype inside the fullscreen shader. It proves the +coordinate and composition contract for local SDF clouds, but the final renderer +should move toward the explicit field registry and volume pass described in +`docs/sdf-field-renderer-plan.md`. + +Current prototype traits: + +- ellipsoid SDF cloud containers +- stable world/Grid-space placement +- distance-guided empty-space stepping +- procedural erosion/noise inside each field +- Self-lit scattering and simple forward/back phase shaping +- no skybox/paraboloid assumption +- no sparse brick storage yet +- no debug view yet + ## Overlay Text Readable overlay text is handled by `DirectWriteOverlay`, using DirectWrite for diff --git a/docs/sdf-field-renderer-plan.md b/docs/sdf-field-renderer-plan.md new file mode 100644 index 0000000..65d02c7 --- /dev/null +++ b/docs/sdf-field-renderer-plan.md @@ -0,0 +1,179 @@ +# SDF Field Renderer Plan + +Aquarium's 3D renderer should converge on one field grammar: every visible 3D +thing is an SDF field that can behave as a solid surface, a participating medium, +or both. The scene is inspired by Aetheria, where clouds are not a skybox layer. +They can sit above the Grid, below it, around objects, and around the camera. +That kills optimizations that assume clouds are distant hemispherical scenery. + +## Goal + +Render juicy SDF solids and SDF clouds from one renderer-owned field system. +Solids and clouds are not separate tricks. They are field objects with different +material regimes. + +Each field should eventually expose: + +- `distance`: signed boundary for surface hits, volume masks, and empty-space + skipping. +- `density`: participating-media occupancy, usually derived from distance plus + erosion/noise. +- `material`: solid albedo, emission, roughness, and surface behavior. +- `medium`: extinction, scattering, phase, emission, and shadow density. +- `bounds`: conservative world-space bounds for culling and acceleration. +- `flags`: solid, cloud, hybrid, emitter, casts volume shadow, receives medium. + +## Non-Negotiable Constraint + +Clouds are local world objects, not atmospheric wallpaper. + +This means: + +- No paraboloid sky-map assumption for the core cloud system. +- No hemisphere-only cloud renderer. +- No "clouds are always behind surfaces" composition shortcut. +- No far-only temporal reprojection scheme that falls apart when the camera is + inside the medium. +- No skybox-relative noise that swims when the Grid/camera moves. + +Clouds may still be rendered into specialized buffers later, but only if the +buffer represents local SDF media correctly when clouds are under, beside, and +around the camera. + +## Field Model + +### Solid Field + +A solid field uses the SDF zero-crossing as its visible surface. + +Runtime needs: + +- bounded analytic or sampled SDF +- normal from the same function that produced the hit +- stable object-local coordinates +- material evaluation +- optional fuzzy shell density around the surface + +### Cloud Field + +A cloud field uses the SDF as a sculptural container and traversal accelerator. + +Runtime needs: + +- signed distance for outside skip and silhouette control +- density inside or near the SDF boundary +- erosion/domain noise in stable field-local space +- extinction/scattering/emission terms +- light visibility or a cheap self-shadow approximation +- preservation of symbolic silhouettes when the cloud is a sign, omen, or event + +### Hybrid Field + +A hybrid field has both solid and medium behavior. Examples: + +- a hard SDF object with a glowing cloud mantle +- a cloud creature with solid core bones +- a Grid event glyph with dense interior fog and crisp outer silhouette +- Self-adjacent aura shells + +## Render Architecture + +### Stage 1: Analytic Field Prototype + +Start inside the current fullscreen HLSL path: + +1. Keep the existing terrain/body raymarch. +2. Add a small analytic SDF cloud registry in shader code. +3. March local cloud density along the camera ray up to the nearest solid hit or + the Grid far distance. +4. Composite as: + + ```text + final = cloud_scattering + cloud_transmittance * surface_color + ``` + +This is allowed as a prototype because it proves the field contract and visual +direction. It is not allowed to become the final volume architecture by stealth. + +### Stage 2: Field Instance Contract + +Move analytic field identity out of hard-coded shader loops: + +- CPU packs field instances into a structured buffer. +- Each instance has transform, bounds, kind, material id, medium id, and shape + parameters. +- The current body froxel table evolves into a general field broad phase. +- Debug views show candidate fields, bounds, and step counts. + +### Stage 3: Explicit Volume Pass + +Add a renderer-owned low-resolution volume pass: + +- local frustum/Grid volume, not sky hemisphere +- density/extinction/scattering/emission targets +- Self as first light source +- world/Grid anchored sampling +- front-to-back accumulated transmittance and in-scattering +- surface composition through the accumulated medium + +This follows Wronski/Hillaire for the pass shape, but without assuming clouds +are distant sky content. + +### Stage 4: SDF Acceleration + +Only after profiling proves the need: + +- add coarse occupancy or distance mip fields for cloud skipping +- add sparse brick SDF storage for large/static fields +- separate static and dynamic update paths +- use toroidal partial updates for camera-centered cascades +- expose debug tracing modes before relying on the accelerator + +## Visual Direction + +The target is not neutral fog. Aquarium fields should feel sculpted, luminous, +and strange while staying readable. + +Useful techniques: + +- distance-guided cloud marching +- erosion noise in field-local coordinates +- fuzzy SDF shells around solids +- edge silverlining from light-facing gradients +- backscatter/forward-scatter blend by density and transmittance +- emissive veins and lightning inside cloud SDFs +- authored symbolic silhouettes for weather glyphs and event clouds +- Sea of Thieves-style geometry/field silhouettes when the shape is gameplay + language +- Dreams-style willingness to throw away beautiful machinery if the image gets + generic + +## Debug Views Required + +Before this grows teeth, add debug surfaces for: + +- field id +- field bounds +- signed distance +- density +- accumulated extinction +- transmittance +- in-scattering +- surface normal +- ray step count +- broad-phase candidate count + +If we cannot see why a pixel looks wrong, the renderer is already lying. + +## First Implementation Slice + +The first code slice is intentionally small: + +1. Add analytic local SDF cloud functions to `Aquarium.hlsl`. +2. March them in world space along each camera ray. +3. Allow clouds below, above, and around the Grid. +4. Composite cloud scattering/transmittance with the existing surface raymarch. +5. Keep all coordinates stable in world/object space. + +This starts the visual grammar without committing to the final storage or pass +layout. A tiny honest machine. How upsettingly rare. diff --git a/src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl b/src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl index 8b8483a..3021bd6 100644 --- a/src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl +++ b/src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl @@ -27,6 +27,10 @@ static const float GRID_LINE_PIXEL_FADE = 0.95; static const float TERRAIN_ISOLINE_SPACING = 0.12; static const float TERRAIN_ISOLINE_PIXEL_WIDTH = 0.54; static const float TERRAIN_FIELD_LINE_PIXEL_WIDTH = 0.38; +static const int CLOUD_FIELD_COUNT = 4; +static const float CLOUD_MIN_STEP = 0.055; +static const float CLOUD_MAX_STEP = 0.46; +static const float CLOUD_EMPTY_STEP_SCALE = 0.42; static const int PLANET_COUNT = 5; static const int PRIMITIVE_COUNT = PLANET_COUNT + 1; static const float GRID_HEIGHT_TEXEL_COUNT = 128.0; @@ -262,6 +266,165 @@ float sphereSdf(float3 p, float3 center, float radius) return length(p - center) - radius; } +float ellipsoidSdf(float3 p, float3 radius) +{ + float3 safeRadius = max(radius, 0.001); + float normalizedDistance = length(p / safeRadius) - 1.0; + return normalizedDistance * min(safeRadius.x, min(safeRadius.y, safeRadius.z)); +} + +void cloudFieldInfo(int index, out float3 center, out float3 radius, out float3 tint, out float densityScale) +{ + float slowTime = timeSeconds * 0.035; + if (index == 0) + { + center = float3(gridCenter + float2(0.0, -1.4), 0.34); + radius = float3(4.6, 1.55, 0.74); + tint = float3(0.30, 0.86, 0.92); + densityScale = 0.23; + } + else if (index == 1) + { + center = float3(gridCenter + float2(-3.8, 2.2), -0.52); + radius = float3(2.15, 1.36, 0.58); + tint = float3(0.24, 0.70, 0.58); + densityScale = 0.31; + } + else if (index == 2) + { + center = float3(gridCenter + float2(3.25, 2.85), 1.18); + radius = float3(1.34, 2.55, 0.86); + tint = float3(0.88, 0.72, 0.42); + densityScale = 0.26; + } + else + { + center = float3(gridCenter + float2(sin(slowTime) * 2.2, cos(slowTime * 0.7) * 2.6), 2.18); + radius = float3(2.8, 1.68, 0.92); + tint = float3(0.44, 0.62, 1.0); + densityScale = 0.18; + } +} + +float cloudFieldSdf(float3 p, int index) +{ + float3 center; + float3 radius; + float3 tint; + float densityScale; + cloudFieldInfo(index, center, radius, tint, densityScale); + + float3 local = p - center; + float angle = index * 1.73 + timeSeconds * 0.018 * (index + 1); + float c = cos(angle); + float s = sin(angle); + local.xy = float2(local.x * c - local.y * s, local.x * s + local.y * c); + return ellipsoidSdf(local, radius); +} + +float cloudDensity(float3 p, int index, out float3 tint) +{ + float3 center; + float3 radius; + float densityScale; + cloudFieldInfo(index, center, radius, tint, densityScale); + + float distanceToCloud = cloudFieldSdf(p, index); + float boundary = 1.0 - smoothstep(-0.18, 0.72, distanceToCloud); + if (boundary <= 0.0) + { + return 0.0; + } + + float3 local = (p - center) / max(radius, 0.001); + float3 wind = float3(0.035, -0.018, 0.011) * timeSeconds; + float broad = fbm3(local * 1.45 + wind + index * 7.1) * 0.5 + 0.5; + float fine = fbm3(local * 4.6 + wind.yzx * 2.0 + index * 11.3) * 0.5 + 0.5; + float erosion = saturate(broad * 0.78 + fine * 0.32); + float softCore = smoothstep(0.26, 0.76, erosion); + float edgeVeil = smoothstep(0.72, -0.18, abs(distanceToCloud)); + return boundary * lerp(0.34, 1.0, softCore) * (0.72 + edgeVeil * 0.28) * densityScale; +} + +float nearestCloudDistance(float3 p) +{ + float distanceToCloud = 100000.0; + [unroll] + for (int i = 0; i < CLOUD_FIELD_COUNT; i++) + { + distanceToCloud = min(distanceToCloud, cloudFieldSdf(p, i)); + } + + return distanceToCloud; +} + +void sampleCloudMedium(float3 p, float3 rayDirection, out float density, out float3 scattering) +{ + density = 0.0; + scattering = 0.0; + + [unroll] + for (int i = 0; i < CLOUD_FIELD_COUNT; i++) + { + float3 tint; + float fieldDensity = cloudDensity(p, i, tint); + if (fieldDensity > 0.0001) + { + float3 toSun = SUN_POSITION - p; + float sunDistanceSq = max(dot(toSun, toSun), 0.001); + float3 lightDirection = toSun * rsqrt(sunDistanceSq); + float forwardPhase = pow(saturate(dot(rayDirection, lightDirection) * 0.5 + 0.5), 3.0); + float backPhase = pow(saturate(dot(-rayDirection, lightDirection) * 0.5 + 0.5), 2.0); + float heightGlow = smoothstep(-1.2, 2.4, p.z); + float selfLight = 11.0 / sunDistanceSq; + float3 lightColor = float3(1.0, 0.76, 0.36) * selfLight; + float3 ambientField = lerp(float3(0.02, 0.08, 0.10), tint * 0.22, heightGlow); + float silver = forwardPhase * 0.72 + backPhase * 0.24; + scattering += fieldDensity * (ambientField + lightColor * (0.18 + silver)); + density += fieldDensity; + } + } + + density = saturate(density); +} + +void integrateCloudFields(float3 rayOrigin, float3 rayDirection, float maxTravel, out float3 cloudScattering, out float cloudTransmittance) +{ + cloudScattering = 0.0; + cloudTransmittance = 1.0; + + float travel = 0.0; + [loop] + for (int stepIndex = 0; stepIndex < 72; stepIndex++) + { + if (travel >= maxTravel || cloudTransmittance < 0.025) + { + break; + } + + float3 p = rayOrigin + rayDirection * travel; + float density; + float3 scattering; + sampleCloudMedium(p, rayDirection, density, scattering); + + float distanceToCloud = nearestCloudDistance(p); + float stepLength = density > 0.001 + ? CLOUD_MIN_STEP + : clamp(max(distanceToCloud, 0.0) * CLOUD_EMPTY_STEP_SCALE, CLOUD_MIN_STEP, CLOUD_MAX_STEP); + stepLength = min(stepLength, maxTravel - travel); + + if (density > 0.001) + { + float extinction = density * 1.35; + float segmentTransmittance = exp(-extinction * stepLength); + cloudScattering += cloudTransmittance * scattering * (1.0 - segmentTransmittance) / max(extinction, 0.001); + cloudTransmittance *= segmentTransmittance; + } + + travel += stepLength; + } +} + float planetCutDepth(float3 localPosition, float radius, int index, bool isSelf) { float3 domain = localPosition / max(radius, 0.001); @@ -858,14 +1021,20 @@ float4 AquariumPS(VertexOut input) : SV_Target int materialId; float travel; float3 color = 0.0; + float maxCloudTravel = farDistance; if (raymarch(cameraPosition, rayDirection, hitPosition, materialId, travel)) { float3 normal = surfaceNormal(hitPosition, materialId); color = shade(hitPosition, normal, materialId, rayDirection); color *= exp(-travel * 0.012); + maxCloudTravel = travel; } + float3 cloudScattering; + float cloudTransmittance; + integrateCloudFields(cameraPosition, rayDirection, maxCloudTravel, cloudScattering, cloudTransmittance); + color = cloudScattering + color * cloudTransmittance; color += float3(0.001, 0.003, 0.004); return float4(aces(color), 1.0); } diff --git a/state/evidence.jsonl b/state/evidence.jsonl index da018e5..daa0477 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -9,3 +9,4 @@ {"area":"research/volumetrics","lesson":"Follow-up scan through newer Advances/citation trails keeps Wronski/Hillaire froxel fog as Aquarium pass one. Nubis 2022/2023 is later cloud-asset work; AMD/Brixelizer-style GPU SDF points to cascaded sparse bricks with static/dynamic and toroidal partial updates; Neural Light Grid says learned fields are preprocessing/storage tools until runtime decode is cheap and inspectable.","source":"research/volumetrics/recent-volumetrics-and-gpu-sdf.md","ts":"2026-05-08"} {"area":"research/volumetrics","lesson":"Do not treat slide decks or presenter notes as transcripts. yt-dlp subtitle pulls for Dreams and GPUOpen sparse SDF materially changed the distilled lesson: Dreams preserved the evaluator/field into a painterly splat renderer after SDF, brick, hybrid transparency, and froxel-lighting attempts failed; Brixelizer is primarily an update/integration system with caps and debug tracing, not just an SDF sampler.","source":"research/volumetrics/transcript-addendum.md","ts":"2026-05-08"} {"area":"research/volumetrics","lesson":"Sea of Thieves clouds provide a stylized counterexample to dense cloud raymarching: Rare used authored opaque polygonal cloud geometry, low-res blurred color/depth compositing, approximate world-position reconstruction, noise/distortion, synchronized wrapped wind offsets, and pressure zones so clouds could be readable world/event objects like skulls, ships, and storms. For Aquarium, symbolic weather/field omens may want geometry/field silhouettes plus cloudy compositing before volumetric traversal.","source":"research/volumetrics/transcript-addendum.md","ts":"2026-05-08"} +{"area":"renderer/sdf-fields","lesson":"Documented the SDF field renderer plan and started a local SDF cloud prototype. Aquarium/Aetheria clouds are local world media that may be above, below, around, or enclosing the camera, so the core cloud architecture must not rely on skybox, hemisphere, paraboloid, or far-only assumptions. First implementation integrates four bounded analytic SDF cloud media along the camera ray before surface composition.","files":["docs/sdf-field-renderer-plan.md","docs/hlsl-renderer.md","src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl","state/map.yaml","state/memory.json","state/scratch.md"],"verification":["dotnet build Aquarium.Engine.slnx",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4"],"ts":"2026-05-08"} diff --git a/state/map.yaml b/state/map.yaml index 4f12566..88c80eb 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -27,6 +27,7 @@ current_model: renderer: docs/hlsl-renderer.md runtime_surface: docs/cult-runtime-surface.md native_spine: docs/vortice-spine.md + sdf_field_renderer_plan: docs/sdf-field-renderer-plan.md input: docs/input.md volumetrics_research: research/volumetrics/synthesis.md recent_volumetrics_and_gpu_sdf: research/volumetrics/recent-volumetrics-and-gpu-sdf.md @@ -37,6 +38,7 @@ invariants: - Grid radius follows camera zoom distance, not pitch/yaw/projection. - Body anchors remain world-space and independent of the moving Grid window. - World-space domains own Grid texture/weather sampling. + - SDF clouds are local world media, not skybox content; they can exist above, below, around, or enclosing the camera. - Visible scene lighting is diegetic; no default ambient/global fill. - Overlay text is DirectWrite final-pixel UI; scene text needs renderer-owned billboards. - CultCache persists live app state through reload. @@ -55,6 +57,7 @@ renderer_state: - Add explicit renderer debug modes for hits, normals, depth, bins, and lighting. - Restore HDR scene target, gentle pre-tonemap bloom, and ACES as explicit passes. - Add volumetrics as an explicit renderer-owned field pass, starting from Wronski/Hillaire-style frustum volume lighting with Self as the first emitter. + - Evolve solids and clouds toward one SDF field registry with material and medium regimes. - Move Grid gradients into the Grid target for cheaper terrain normals. - Rebuild lighting as an Aquarium-owned field before adding richer fog. - Add diegetic labels and object-local menus after the renderer and text contracts are stable. @@ -66,5 +69,6 @@ next_actions: - Use research/volumetrics/synthesis.md before designing fog, atmospheric scattering, clouds, or sparse volume storage. - Use research/volumetrics/recent-volumetrics-and-gpu-sdf.md before designing GPU SDF, cloud traversal, learned field storage, or radiance caching. - Check research/volumetrics/transcript-addendum.md before relying on slide decks as evidence; video transcripts can change the renderer lesson. + - Follow docs/sdf-field-renderer-plan.md when adding SDF solids, SDF clouds, or hybrid field objects. - Promote runtime knobs into typed CultCache documents. - Port only proven synth concepts into C# when audio returns; keep external prototypes as references, not engine baggage. diff --git a/state/memory.json b/state/memory.json index d472c0e..addf2d2 100644 --- a/state/memory.json +++ b/state/memory.json @@ -22,6 +22,7 @@ "The camera target is the Grid center on XY. Grid radius derives from zoom distance. Pitch, yaw, FOV, and screen aspect do not resize the Grid.", "Body anchors are world-space simulation state. Moving the Grid visibility window must not drag bodies with it.", "Grid texture, weather, line, and future fog domains should sample world-space coordinates so panning reveals the field instead of sliding a texture under the camera.", + "Aquarium/Aetheria clouds are local SDF media: above, below, around, and sometimes enclosing the camera. Do not build the core cloud path on skybox, hemisphere, paraboloid, or far-only assumptions.", "Cursor and camera interactions should project onto the same XY surface used by the Grid contract." ], "raymarching": [ @@ -40,6 +41,7 @@ "For GPU SDF or newer volumetric storage, consult research/volumetrics/recent-volumetrics-and-gpu-sdf.md. The durable pattern is cascaded sparse bricks, compressed distance/occupancy, separate static/dynamic updates, toroidal partial updates, and learned fields only when runtime evaluation stays cheap and inspectable.", "For research decks with recordings, pull subtitles/transcripts before distilling. The Dreams transcript changed the lesson: preserve the evaluator/field that serves the image, not the elegant SDF/brick/froxel experiment that drifted away from the art direction.", "Sea of Thieves clouds are the stylized counterexample: authored opaque cloud geometry filtered through low-res blurred color/depth compositing can beat dense raymarching when clouds are symbolic world objects or gameplay signage. Consider tool-time SDF baking for per-vertex cloud lighting, not runtime volume traversal by reflex.", + "The SDF field renderer plan is docs/sdf-field-renderer-plan.md: solids and clouds should share one field grammar, with distance, density, material, medium, bounds, and debug views.", "Bruneton-style atmospheric scattering is the later sky/planet solution, not the first Grid fog pass. Use LUTs, explicit texture mappings, and unit-tested physical terms when Aquarium reaches ground-to-space atmosphere.", "GigaVoxels-style ray-guided sparse bricks are only for large sparse field/world storage. Do not turn early fog into a monolithic persistent volume cache." ], diff --git a/state/scratch.md b/state/scratch.md index d669d28..88d176b 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -2,10 +2,11 @@ ## Current Slice -Merged the native C# engine branch to `main`, then stripped historical branch -memorial language from the live docs. The repo now needs to stay pure: C# host, -Vortice/D3D11 renderer, HLSL shaders, CultMath/CultLib, DirectWrite overlay, -CultCache state, CultNet future transport. +Planning and first implementation for the SDF field renderer. The core rule: +Aquarium/Aetheria clouds are local SDF media above, below, around, or enclosing +the camera, never skybox-only decoration. `docs/sdf-field-renderer-plan.md` +captures the architecture. `Aquarium.hlsl` now has a first analytic SDF cloud +prototype integrated along the camera ray before surface composition. ## Hot Context @@ -17,3 +18,6 @@ CultCache state, CultNet future transport. - `.\scripts\dev-reload.ps1 -Headless -RetainSlots 4` - Prototype histories remain external references. Do not re-import their source trees into this engine repo. +- Current cloud prototype is deliberately not the final volume pass. Next + renderer steps: debug views, field instance contract, then explicit local + volume/froxel pass.