diff --git a/AGENTS.md b/AGENTS.md index c60428c..02b2f97 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ clients. It owns the window, D3D12 renderer, input loop, live-reload boundary, audio host, debug chrome, render contracts, and reusable field/fractal machinery. Client-specific meaning belongs to client repos. Epiphany Aquarium lives at -`E:\Projects\Aquarium-Engine`. +`..\Aquarium`. ## Operating Doctrine diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..640c1a1 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +Repository doctrine for this project lives in AGENTS.md, shared with Codex. + +@AGENTS.md diff --git a/Fensalir.sln b/Fensalir.sln index 1c196ee..c5c2320 100644 --- a/Fensalir.sln +++ b/Fensalir.sln @@ -9,7 +9,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine.Contracts", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine", "src\Aquarium.Engine\Aquarium.Engine.csproj", "{51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CultMath", "..\CultMath\src\CultMath\CultMath.csproj", "{0089E341-25F2-43FC-8FD9-CBD1AE646D91}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CultMath", "..\CultLib\packages\cultmath\src\CultMath\CultMath.csproj", "{0089E341-25F2-43FC-8FD9-CBD1AE646D91}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Sample.Minimal", "src\Aquarium.Sample.Minimal\Aquarium.Sample.Minimal.csproj", "{7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}" EndProject @@ -29,8 +29,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Fractal.Receipt", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Fensalir", "src\Aquarium.Fensalir\Aquarium.Fensalir.csproj", "{F9274D99-3CC6-42B6-9817-EC7F19663B1D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Saga", "src\Saga\Saga.csproj", "{30324495-56BE-4D45-80E8-CE03C24726C8}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -161,18 +159,6 @@ Global {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x64.Build.0 = Release|Any CPU {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x86.ActiveCfg = Release|Any CPU {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x86.Build.0 = Release|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|x64.ActiveCfg = Debug|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|x64.Build.0 = Debug|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|x86.ActiveCfg = Debug|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Debug|x86.Build.0 = Debug|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Release|Any CPU.Build.0 = Release|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x64.ActiveCfg = Release|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x64.Build.0 = Release|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x86.ActiveCfg = Release|Any CPU - {30324495-56BE-4D45-80E8-CE03C24726C8}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -187,6 +173,5 @@ Global {A9D41C48-7E78-4D75-A814-0C1500245EFC} = {0AB3BF05-4346-4AA6-1389-037BE0695223} {C0D1BFAC-B1B4-4350-92A7-D537AE382909} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} {F9274D99-3CC6-42B6-9817-EC7F19663B1D} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {30324495-56BE-4D45-80E8-CE03C24726C8} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} EndGlobalSection EndGlobal diff --git a/README.md b/README.md index 15eaf15..0f16e5c 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,14 @@ evidence, and synth-backed sound. The repo is not the Epiphany Aquarium client. Epiphany lives in `GameCult/Aquarium-Engine` and consumes Fensalir as the runtime dependency. +**Valuable here:** the spatio-temporal evidence reservoir (`ResampledImportanceReservoir` and `TemporalSpatialEvidenceReservoir` in `src/Aquarium.Engine.Fractal/Temporal/`), the `.aquageo` fractal field DSL in `src/Aquarium.Engine.Fractal`, and the engine/client contract in `src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs` (`IAquariumRuntime`). + +**Problem it solves:** interactive visual clients need a renderer that decides which field evidence deserves rendering, fusion and residency under a budget, instead of each client owning temporal truth or drawing private geometry. Fensalir holds that machinery once; client repos own meaning. + +**Entry points:** `dotnet build Fensalir.sln`; run a client with `scripts/dev-reload.ps1 -ClientProject ` (see Run below). Start reading at `docs/engine-client-boundary.md` and `docs/temporal-spatial-evidence-reservoir.md`; the target pipeline is `docs/perfect-fensalir-machine-roadmap.md`. The smallest client is `src/Aquarium.Sample.Minimal`; `src/Aquarium.Fensalir` and `src/Aquarium.Zyphos` are demo clients. + +**Live versus planned:** live are the Win32 host, D3D12 renderer, hot reload, headless capture, AquaSynth/WASAPI audio, CPU reservoirs, fractal probe samples, evidence tracks and validator coverage. Planned (see the roadmap) are full GPU reservoir storage and page residency. + ## What Runs The host executable in `src/Aquarium.Engine` loads a client assembly that @@ -136,9 +144,6 @@ how WASAPI or Faust got invited to the party. audio/synth host, bundled assets, and renderer-owned shaders. - `src/Aquarium.Engine.Fractal`: `.aquageo`, IFS/fractal fields, temporal reservoirs, evidence tracks, contribution cache, and lowering machinery. -- `src/Saga`: stochastic planetary flow middleware for cube-sphere Transport - fields, arbitrary forcing, Coriolis-aware advection, and learned atmosphere / - ocean / debris flow packets. - `src/Aquarium.Fensalir`: Fensalir splash/art reconstruction demo. - `src/Aquarium.Sample.Minimal`: tiny client proving the runtime boundary. - `src/Aquarium.Zyphos`: planetary/fractal terrain demo. @@ -153,8 +158,8 @@ Requirements: - Windows - .NET SDK matching `global.json` -- sibling repos currently expected at `E:\Projects\CultMath` and - `E:\Projects\CultLib` +- sibling `CultLib` checkout beside this repo (override with the `CultLibRoot` + MSBuild property); CultMath is consumed from `CultLib/packages/cultmath` ```powershell dotnet build Fensalir.sln diff --git a/docs/README.md b/docs/README.md index 8c6243d..0434328 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,8 +13,6 @@ historical branch scar. ## Fields, Reservoirs, And Fractals -- `../src/Saga/README.md`: studio-facing Saga middleware pitch and subproject - overview for stochastic planetary flow. - `papers/fensalir-pipeline.tex`: living MiKTeX paper for the Fensalir pipeline, research spine, domain reservoir model, and evaluation plan. - `papers/fensalir-native-domain-reservoirs.tex`: focused SIGGRAPH-shaped diff --git a/docs/papers/fensalir-native-domain-reservoirs.pdf b/docs/papers/fensalir-native-domain-reservoirs.pdf deleted file mode 100644 index a06d2ca..0000000 Binary files a/docs/papers/fensalir-native-domain-reservoirs.pdf and /dev/null differ diff --git a/docs/papers/fensalir-pipeline.pdf b/docs/papers/fensalir-pipeline.pdf deleted file mode 100644 index e2482aa..0000000 Binary files a/docs/papers/fensalir-pipeline.pdf and /dev/null differ diff --git a/docs/planet-work-assimilation.md b/docs/planet-work-assimilation.md new file mode 100644 index 0000000..403e8e5 --- /dev/null +++ b/docs/planet-work-assimilation.md @@ -0,0 +1,479 @@ +# Fensalir planet work: validation and reorientation beside Asura + +Status: Imagination pass 1, 2026-09-30. Nothing committed and no working tree +switched. The build probes ran on Yggdrasil through `ygg-verify.sh`, using +composite snapshots in a scratch repo. That repo lives in the scratchpad, not +in any project. + +Adopting instruction (operator, 2026-09-30): "Fensalir planet work is old, +needs validation and reorientation beside the Asura campaign". + + +## Rulings (operator, 2026-09-30) + +- **Q-F1: no planet terrain in Fensalir for now.** The July planetary runtime retires behind an archive + tag. A landing-scale Zyphos would be a new campaign built on Asura, not a revival of that runtime. +- **Q-F2: park the flow docs,** with a status line: parked, superseded by Asura for the field, no code. +- **Q-F3: triage now.** Eyes classifies each non-planet line on the donor ref before anything is tagged or + deleted: the 66 Bokusho commits, the Eve native surface work, Leap/stereo, and the reservoir work. P1 + waits for that triage. +- **Q-F4: delete Geometry's duplicate vector types before Asura Cut 3** (P4, in CultLib). This is on + Asura's critical path. + +## Pinned heads (every `file:line` below is against these) + +| Repo | Ref | SHA | Note | +| --- | --- | --- | --- | +| Fensalir | `origin/main` = local `main` | `e053486` | 3 commits past the merge base, all housekeeping | +| Fensalir | `origin/codex/geometry-ownership-migration` (the donor) | `42778c1` | 125 ahead of merge base `57b6040` (2026-05-30) | +| Fensalir | `origin/codex/leap-packed-depth` | `492d123` | the donor minus its last commit | +| CultLib | `origin/main` | `93fe1b9` | includes the bounded-least-squares merge; local `main` is `069ecc3` | +| CultLib | `origin/codex/geometry-ownership-migration` | `6a65369` | the donor's other half: 31 ahead of `a58daa5` (2026-07-12), 832 behind | +| CultLib | tags `gamecult-geometry{,-rs,-unity}-v0.1.0` | `b65619f` | pushed to origin, on `origin/codex/geometry-cultmesh-unity-release`, not in main | +| CultMath (standalone, retired) | `main` | `1c007a5` | "Point CultMath history at its CultLib home"; planetary deleted at `6a16260` | +| Asura | `main` | `63f9216` | snoise fix status recorded; the fix is on CultLib `hands/cultmath-snoise-grad` `0a5f4bf` | + +## Verdict + +**Retire the planet work. Do not land it.** The donor has no surviving code +owner: CultMath deleted the planetary runtime in July, and CultLib never merged +it. Asura has since claimed the planet field with a design that contradicts the +donor's central promises. Its erosion port is the one Asura already judged "not +a source". Its only consumer is a Fensalir demo client that has not changed +since 2026-05-30. + +One idea from the geometry half is still live and time-sensitive: deleting the +duplicate vector types from `GameCult.Geometry`. That is separate work, but it +has a closing window. Once Asura Cut 3 ships `GameCult.Geometry.dll` into Unity, +the duplicate `CultVec3` becomes public Unity API (Q-F4). + +Most of the branch is not planet work at all. 66 Bokusho commits, 10 Eve +commits, and the Leap/stereo and reservoir work ride on the same ref. They need +their own adoption decision before any ref is deleted (Q-F3). + +--- + +## 1. Validation report + +### 1.1 What the donor actually is + +Grouping `git log 57b6040..42778c1` by subject: + +| Slice | Commits | Dates | Size | +| --- | --- | --- | --- | +| Leap stereo depth, point cloud, reservoir history, camera fusion, loopback audio | ~20 | 05-30 to 05-31 | inside the 61-file, +8832/−279 pre-planet diff | +| Eve native surface client (Direct2D, CultUI previews) | ~17 | 05-31 to 06-02 | same | +| Bokusho brush simulation on D3D12 | 66 | 06-12 to 06-16 | `BokushoBrushSimulation.cs` +1076, `D3D12BokushoBrush.hlsl` +699, tests +1143 | +| **Planet slice** | **23** | **07-12 to 07-22** | **61 files, +2865/−359 (`5854630^..42778c1`)** | + +Inside the planet slice, only the last three commits are the "geometry ownership +migration": +- `2531df5` moves Fensalir onto CultMath's July planetary runtime. +- `492d123` deletes Fensalir's `CubeFace`, `CubeFacePosition` and `CubeTileKey`. +- `42778c1` renames every consumer from `cultmath_planetary_*` to + `gamecult_geometry_planetary_*`. + +Its partner commits live in CultLib (`13e8c56..6a65369`) and CultMath (`6a16260`). + +### 1.2 Merge probes (`git merge-tree --write-tree`) + +- **Fensalir, donor into `origin/main`: 7 conflicts.** + - Content conflicts in `Fensalir.sln`, `README.md`, `docs/README.md` and + `src/Aquarium.Engine/Aquarium.Engine.csproj`. + - The csproj conflict matters. Main's `dc35ecc` moved CultMath to + `$(CultLibRoot)\packages\cultmath\...` (`Aquarium.Engine.csproj:4,26` at + `e053486`). The donor still points at the standalone repo + (`..\..\..\CultMath\src\CultMath\CultMath.csproj`, `Aquarium.Engine.csproj:25` + and `Aquarium.Engine.Contracts.csproj:10` at `42778c1`). + - Modify/delete conflicts in `src/Saga/{README.md,Saga.csproj,SagaOrgan.cs}`. + Main deleted Saga as dead in `d755d9c`; the donor still migrates it. +- **CultLib, July branch into `origin/main`: 23 conflicts.** + - 13 are source and docs, including a modify/delete on + `CultDocumentMessagePackGenerator.cs`, which main deleted. The others are in + `CultManagedDocument.cs`, the serialization code, `GameCult.Geometry.csproj` + and `README.md`, `GeometryDocumentTests.cs` and `build-unity-package.ps1`. + - 10 are prebuilt Unity DLLs and pdbs. + - The branch is 832 commits behind. That is not a merge; it would be a + re-implementation. + +### 1.3 Build probes (Yggdrasil, `mcr.microsoft.com/dotnet/sdk:10.0`, Linux) + +The probes use three composite snapshots in the scratch repo. Each lays the +three repos out as siblings, the way the csproj relative paths expect. + +| Probe | Layout | Result | +| --- | --- | --- | +| **mainline** | Fensalir `e053486` + CultLib `93fe1b9` | `Aquarium.Engine.Fractal` builds. Fractal tests: **167/167 pass** | +| **then** (the July world) | Fensalir `42778c1` + CultLib `6a65369` + CultMath `b43cf49` | Restore fails first with NU1101: `CultMath 0.1.0` comes only from a git-ignored local feed (`CultLib/Directory.Build.props:18-19` at `6a65369`: `..\CultMath\.tools\local-feed`). After `dotnet pack` of CultMath `b43cf49` and passing the feed explicitly, the lib builds and the Fractal tests give **169/170**. The failure is `ProjectionTests.CheckedInProjectionReportMatchesSampler`, which passes on mainline. The donor regenerated `research/rendering/fractal-projection-report.md` against the July projection code on Windows; this was not chased. | +| **now** (donor against today's owners) | Fensalir `42778c1` + CultLib `93fe1b9` + CultMath `1c007a5` | **Fails** with 10 unique errors (`FRACTAL_LIB_EXIT=1`). Nine are CS0246 for `PlanetaryCubeFace`, `PlanetaryTileAddress` and `PlanetaryFaceCoordinate` (`FractalDslCompiler.cs:505`, `FractalStableKeyBuilder.cs:8`, `ICubeSphereProjection.cs:11`, `NormalizeCubeSphereProjection.cs:11`, `ProjectionDistortionResult.cs:8`, `ProjectionDistortionSampler.cs:14,61,68`, `TangentCubeSphereProjection.cs:11`). The tenth is CS1704: two assemblies named `CultMath` are loaded, one from the standalone repo through the donor's `Contracts` reference and one from CultLib `packages/cultmath` through `GameCult.Geometry`. The donor straddles the pre-monorepo and monorepo layouts. | + +Static proof that "now" cannot build, independent of the probe: every +`Planetary*` symbol the donor consumes is absent from CultLib main. +- The donor uses these (`git grep` at `42778c1`): `PlanetaryCubeFace` (47 uses), + `PlanetaryTileAddress` (24), `PlanetarySurfacePages`, + `PlanetaryProjectionKind`, `PlanetaryFaceCoordinate`, `PlanetaryPageSampling`, + `PlanetaryPageLayout`, `PlanetaryResidualResidency`, `PlanetaryLodSelector`, + `PlanetaryGpuPageBuilder`, `AdvancedErosionParameters` and the + `GameCultGeometry*` HLSL structs. +- Counts on CultLib `93fe1b9`: `PlanetaryCubeFace` 0, `PlanetaryTileAddress` 0, + `PlanetaryTopology` 0. +- `src/GameCult.Geometry/Shaders/` does not exist on main, so + `#include "GameCult.Geometry/GameCult.Geometry.hlsl"` + (`D3D12ZyphosTerrain.hlsli:4` at `42778c1`) has nothing to resolve. + +**Not run, because it needs Windows and D3D12:** +- `tests/Aquarium.Engine.Tests`: `D3D12PlanetarySurfacePageTests`, + `D3D12PlanetaryTopologyParityTests` and `D3D12AdvancedErosionParityTests`, + which are GPU readback parity tests; +- `Aquarium.Engine` itself (Vortice D3D12); +- the Zyphos client. + +Per the workstation budget, none of this ran on Starfire. Given the verdict, +it does not need to run at all: the GPU parity would prove a runtime nobody +will keep. + +### 1.4 What is still right, and what has rotted + +Still right: +- The donor's direction of dependency. Algorithms sit in a library and D3D12 + resources stay in Fensalir. That matches the doctrine and Asura's own shape + (CultLib algorithms, consumer-owned rendering). +- The July migration plan's authority sentence: "CultMath owns how numeric + primitives behave; GameCult.Geometry owns what those primitives mean in + space" (CultLib `docs/cultmath-gamecult-geometry-migration-plan.md:56-57` at + `6a65369`). CultLib main adopted the same split at `63d6094` (2026-08-26), + and `HlslMirrorTests.cs:7-15` on main enforces the CultMath side. +- The idea of deleting `CultVec2`/`CultVec3` (CultLib `317b7d5`). Main still + carries both (see Q-F4). + +Rotted: +1. **Ownership of the planet field.** The donor's objective + (`docs/cultmath-planetary-field-runtime-plan.md:3-15` at `42778c1`) makes a + shared library the canonical planet field for "Aetheria's daemon + simulation, Unity's three-dimensional planet renderer, Fensalir's D3D12 + renderer, and Electron/Web strategic maps". Asura now owns Aetheria's + planets and rules the opposite: + - The field is HLSL only, and the CPU never evaluates it (Asura + `docs/target.md:42-47`, invariant 2). + - There is no landing and no surface streaming (the scope boundary). + - The donor's authoritative CPU queries, residency LOD and QSC page + streaming are therefore out of scope, or forbidden outright. +2. **The erosion port.** Asura's 4b-iii already rejected the July + `spherical_erosion` because it "lerps raw phases across cells instead of + blending phasors, which is not Phacelle" (`docs/cut-map.md:1132-1135`, + `:1736` at `63f9216`). Phacelle is going into CultMath fresh (2a-ii-b). +3. **Derivatives.** Zyphos's base field is ad hoc sine plates with a + central-difference gradient (`D3D12ZyphosTerrain.hlsli:113-129` at + `42778c1`). That is the pattern Asura's invariant 8 exists to prevent. +4. **The code owner is gone.** CultMath deleted the planetary runtime + (`6a16260`, reachable from CultLib main through the subtree). The receiving + CultLib branch never merged. On mainline the runtime is orphaned: it exists + only on unmerged branches and the three pushed `v0.1.0` tags. +5. **The build contract.** It needs an untracked local NuGet feed (see 1.3) + and paths from before the monorepo. +6. **The CultLib geometry half diverged from main's ruling.** + - The branch absorbs CSG into `GameCult.Geometry` (`6b44f96`). Main ruled + that `GameCult.Geometry.Csg` owns CSG production behaviour (`63d6094`, + `src/GameCult.Geometry/README.md`), and that repo shipped `distance(p)` + at `d84acb6`. + - The branch also adds a geometry worker, `CultGeometryWorkerDocuments`, + `CultGeometryWorkerProvider` and "v2 contracts". None of these exist on + main, and main's documents never moved to v2. + +--- + +## 2. Ownership table + +| Piece (donor) | Where it sits in the donor | Owner today | Disposition | +| --- | --- | --- | --- | +| Planet field definition, base field and erosion as one function | CultLib branch `src/GameCult.Geometry/Planetary/PlanetaryField.cs`, `Shaders/Planetary.hlsl` | **Asura** (field in HLSL, per body archetype) | Retire. Duplicates Asura's field | +| Advanced erosion filter (Johansen port) and `SphericalErosion` | branch `Planetary/AdvancedErosionFilter.cs`, `SphericalErosion.cs`, `Shaders/AdvancedErosionFilter.hlsl` | **Asura** 4b-iii (`AsuraErosion.hlsl`, fresh port with provenance) | Retire. Asura already ruled it "not a source" | +| Phacelle and noise primitives | embedded in the erosion port | **CultMath** (2a-ii-b `phacelle`, `CultPhasor`) | Retire the embedded copy | +| Cube-sphere/QSC topology, tile addresses, page layout, residency, LOD selection, patch meshes, radial refinement | branch `Planetary/PlanetaryTopology.cs`, `PlanetaryPages.cs`, `PlanetaryResidency.cs`, `PlanetaryPatch.cs`, `PlanetaryRadialRefinement.cs` | **No live consumer.** Asura meshes with surface nets and tiles per quad; streaming is out of scope | Retire. Revive only through a new campaign with a named consumer (Q-F1) | +| CPU ray, region and great-circle queries for an "Aetheria daemon" | branch `Planetary/PlanetaryQueries.cs` | **Forbidden** by Asura invariant 2. The dock-site query is Asura's | Retire | +| Map projections and `CMPT` tile codec (Electron maps) | branch `PlanetaryProjection.cs`, `PlanetaryMapTileEncoding.cs`, TS decoder | No consumer exists or is planned | Retire | +| `org.gamecult.geometry` Unity package and planetary viewer sample | branch `unity/org.gamecult.geometry/**`, tags `b65619f` | Superseded: Asura Cut 3 ships Geometry inside `org.gamecult.cultlib` | Retire the branch. Keep the pushed tags as immutable history (Q-F3) | +| Frequency-band selection by sample footprint | branch `Planetary/ErosionFrequencyBands.cs` | **Asura** (band limits per lowering; target invariant 8, Q11) | Retire. Same concept, and Asura implements it fresh | +| D3D12 page buffers, root parameters 29-32, dispatch, patch raster, debug modes | Fensalir `D3D12Renderer.cs:99-102,223` and about 157 planetary lines; `AquariumRenderPlan.cs:526-565` (render ABI) at `42778c1` | **Fensalir** would own it if Fensalir rendered planets. Its only producer is the retired runtime | Retire with the runtime | +| DXC include resolver for `Packages/org.gamecult.cultmath/shaders/` and `GameCult.Geometry/` | Fensalir `D3D12ShaderCompiler.cs:68-102` at `42778c1` | Fensalir. On main no shader includes CultMath HLSL at all | Retire. Its search paths are also stale (the standalone `CultMath/shaders`, pre-monorepo). Rebuild against `packages/cultmath/shaders` when a Fensalir shader first includes CultMath | +| Zyphos terrain shaders, page and patch entry points, `ZyphosPlanetarySurfacePages` | Fensalir `src/Aquarium.Zyphos/**` at `42778c1` | Fensalir's demo client. Main's Zyphos keeps its pre-July analytic sphere | Retire | +| Fensalir's `CubeFace`, `CubeFacePosition`, `CubeTileKey` and the projection code in `Aquarium.Engine.Fractal` | **Main keeps them.** The donor deleted them in favour of Geometry | **Fensalir** (fractal DSL, projection reports; 167 tests green on main) | Keep on main; nothing to do. The donor's deletion is void once the runtime is retired | +| Planetary flow organ (ocean and atmosphere advection), documentation only | Fensalir main: `docs/planetary-flow-{organ,nn-architecture,implementation-plan}.md` (289/462/185 lines); `docs/README.md:39-44`; `state/map.yaml:114-120` and the flow `next_actions` entries after `:171` | Fensalir, as plans. No code exists; last touched 2026-05-29. Not in Asura's scope (no atmospheres or oceans) | Q-F2 | +| Vector-type unification (delete `CultVec2`/`CultVec3`/`CultRect` in favour of CultMath `float2`/`float3`/`rect`) | CultLib branch `317b7d5`, `364c9cd` | **CultMath** owns the vector vocabulary (main `63d6094`). Main still has the duplicates: `CultGeometryPrimitives.cs:11,62,128` and the `origin` parameter of `CultGeometryIsoSurface.cs:42` and `CultGeometrySurfaceNets.cs:47` | Q-F4: a fresh cut on main, not the branch code | +| CSG absorption, geometry worker, v2 schemas, Rust `gamecult-geometry-rs` | CultLib branch | CSG: `GameCult.Geometry.Csg` (main's ruling). The rest have no owner and no consumer | Retire with the branch | + +### Duplication against Asura (one side is cut, not kept in parallel) + +| Concept | Donor | Asura | Side cut | +| --- | --- | --- | --- | +| Planet shape function | `PlanetaryFieldDefinition` plus base-field provider (CPU and HLSL) | the field `f(p) = |p| − (1 + h(u))`, HLSL only | donor | +| Erosion | July port with raw-phase lerp | 4b-iii fresh port, exact Phacelle, provenance file | donor | +| Level of detail | QSC pages, residency, projected-error LOD | surface-net grid resolution plus per-body tile N | donor. Asura's scope rules streaming out | +| Band limiting | `ErosionFrequencyBands` | per-lowering band limit (Q11) | donor | +| Unity packaging | `org.gamecult.geometry` | `org.gamecult.cultlib` (Cut 3, default A) | donor | + +--- + +## 3. Cuts + +Every cut below is deletion or documentation, with no new code. Numbers are +prefixed `P` so they cannot be confused with Asura's cut numbers. + +### P0. Operator rulings (Self; blocks everything below) + +Q-F1 and Q-F3 must be ruled before P1. Q-F2 gates P3. Q-F4 gates P4. + +### P1. Archive the refs, then delete them (Fensalir, CultLib, standalone CultMath) + +- **Precondition:** Q-F3 ruled. The non-planet work on the Fensalir donor + (Bokusho, Eve surface, Leap) must be either archived with it or adopted + separately first. +- **Deletes first:** + - Fensalir remote branches: `codex/geometry-ownership-migration` (`42778c1`) + and `codex/leap-packed-depth` (`492d123`, a strict ancestor). + - CultLib remote branches: `codex/geometry-ownership-migration` (`6a65369`) + and `codex/geometry-cultmesh-unity-release` (`b65619f`). + - The standalone CultMath remote `codex/geometry-ownership-migration` + (`b43cf49`), already an ancestor of CultMath `main`, so deleting it loses + nothing. +- **Then:** + - An annotated tag at each unique tip, so every commit stays reachable: + - Fensalir `archive/geometry-ownership-migration` → `42778c1`; + - CultLib `archive/geometry-ownership-migration` → `6a65369`; + - CultLib `archive/geometry-cultmesh-unity-release` → `b65619f`, if a + branch ref is wanted beyond the release tags that already pin it. + - The tag message names this map and the ruling. + - The published `gamecult-geometry{,-rs,-unity}-v0.1.0` tags stay: they are + released, immutable artifacts. +- **Authority map:** + - Owner of planet shape: Asura. Owner of numeric primitives: CultMath. + - Derived: the archive tags are history only, and nothing resolves a build + from them. + - Forbidden writers: any branch that could be merged back to revive + `Planetary*` in CultLib, or `cultmath_planetary_*` in CultMath. + - Shared paths: none. No mainline build references these refs; the mainline + probe proves Fensalir main builds without them. +- **Verification:** + - `git merge-base --is-ancestor archive/` for each deleted + ref, run before deleting. + - `git ls-remote --heads origin | grep -c geometry-ownership` gives 0 in all + three repos. + - Mainline probe re-run (Fensalir `e053486` + CultLib main): 167/167. + - Negative: `git grep -c "Planetary" origin/main -- src packages` in CultLib + stays at its current count (only `HlslMirrorTests.cs:12,14`). +- **Subtraction:** 5 remote branch refs, net of the 2–3 archive tags. The + unmerged surface removed from view is Fensalir +11,650/−591 (116 files) and + CultLib +14,933/−317 (156 files). No mainline lines change. +- **Hands budget:** about 20k tokens. It is ref surgery and needs the + operator's credentials for the pushes. + +### P2. Asura documents: replace "do not delete it" with the ruling (Asura, docs only) + +- **Deletes first, at Asura `63f9216`:** + - `docs/target.md:110-113`: the "Not consumers" bullet naming the branches. + - `docs/cut-map.md:814-820`, Cut 3's "Not a source", including + "do not delete it; see findings". +- **Then:** + - One sentence in each place: the July planetary line was retired on + 2026-09-30 and archived at the tags from P1; Asura is the sole owner of + planet shape. + - `cut-map.md:1132-1135` and `:1736` keep their technical reason (raw-phase + lerp, not Phacelle). They point at the archive tag instead of the branch + names. + - `target.md:252` (the substrate fact about the `unity-v0.1.0` tag) stays + true and is unchanged. +- **Authority map:** `target.md` owns the ends, so the retirement ruling is + recorded under its dated operator rulings. The cut map only points at it. +- **Verification:** + - `rg -n "codex/geometry-" docs/` in Asura gives 0 lines. + - `rg -n "do not delete it" docs/` gives 0. +- **Subtraction:** about −8 +4 lines. +- **Timing:** Self can do this in the same pass that records the rulings. It + does not touch 2a-ii. + +### P3. Fensalir main: record the disposition; flow docs per Q-F2 (Fensalir `main`) + +- **If Q-F2 = retire. Deletes first, at `e053486`:** + - `docs/planetary-flow-organ.md`, `docs/planetary-flow-nn-architecture.md` + and `docs/planetary-flow-implementation-plan.md` (936 lines); + - `docs/README.md:39-44`; + - `state/map.yaml:114-120`, and the flow entries in `next_actions` (the + bullets beginning "Build the planetary flow organ" and "For planetary flow + modeling", about 10 lines after `:171`). +- **If Q-F2 = park:** add one "Status: parked 2026-09-30, no consumer" line at + the top of each of the three docs instead. +- **Then, either way:** + - One line in `state/map.yaml`: Fensalir renders no planet terrain beyond + the Zyphos demo's analytic sphere. Planet shape for GameCult games is + Asura's. If Fensalir ever renders an Asura body, it lowers Asura's field + HLSL and owns only D3D12 resources. + - Fix `README.md:141` from "planetary/fractal terrain demo" to "fractal + terrain demo", only if the operator agrees the demo carries no planet + ambition. Otherwise leave it. +- **Authority map:** Fensalir owns its renderer and demos. It claims no planet + field. +- **Verification:** + - `git grep -n -i "planetary" origin/main -- docs/README.md state/map.yaml` + matches the intended remainder. + - The mainline Fractal probe still gives 167/167; docs cannot break it. +- **Subtraction:** retire gives about −950 lines and +2. Park gives +3. +- **Hands budget:** about 15k tokens. + +### P4. CultLib: collapse `CultVec2`, `CultVec3` and `CultRect` into CultMath, before Asura Cut 3 (only if Q-F4 = A) + +- **Why now:** + - Asura Cut 3 (`docs/cut-map.md:801`) ships `GameCult.Geometry.dll` in + `org.gamecult.cultlib` 1.1.0. + - Both extractors take `CultVec3 origin`, so the duplicate type becomes + Unity public API in that release. Deleting it afterwards is a semver + major. + - `CultGeometrySurfaceNets.cs:83` already converts `CultVec3` to `float3` + internally. +- **Deletes first, at CultLib `93fe1b9`:** + - In `src/GameCult.Geometry/CultGeometryPrimitives.cs`: + - `CultVec2` (`:11-60`) and `CultVec3` (`:62-126`); + - `CultRect` (`:128-197`), which duplicates CultMath `rect` + (`packages/cultmath/src/CultMath/rect.cs:7`, added 2026-08-07). + - `CultCircle` and `CultSphere` stay; they are spatial meaning, and that is + Geometry's. They are rebuilt on `float2`/`float3`. +- **Then:** + - `CultGeometryIsoSurface.Extract(..., float3 origin = default, ...)` + (`:42`) and `CultGeometrySurfaceNets.Extract(..., float3 origin = default, + ...)` (`:47`); delete the conversion at `:83`. + - Update the tests: `GeometryDocumentTests.cs` (16 uses), `IsoSurfaceTests.cs` + and `SurfaceNetsTests.cs`. + - Update `src/GameCult.Geometry/README.md`. +- **Explicitly out of scope:** CultMesh's native-slice value-type names + `"CultVec2"` and `"CultVec3"` (`packages/cultmesh-ts/test/cultmesh.test.ts:1717,2440,2453`, + and `src/GameCult.Mesh/docs/public-api.md`). Those are wire vocabulary with + their own owner. Record them as a finding for the CultMesh owner; do not + rename them here. +- **Authority map:** + - Owner: CultMath owns vector and rectangle values. Geometry owns what they + mean in space. + - Forbidden writers: any type in `GameCult.Geometry` that carries x/y/z + fields. +- **Verification (Yggdrasil):** + - `dotnet test tests/GameCult.Geometry.Tests`, with the per-file counts. The + Surface Nets byte-identical fixtures from Asura Cut 2 (31 fixtures) must + stay byte-identical. + - Negative: `git grep -n "CultVec\|CultRect" -- src/GameCult.Geometry tests/GameCult.Geometry.Tests` + gives 0. + - Stryker `--since:93fe1b9` on the touched files. +- **Subtraction:** about −190 lines of duplicate value types, plus test + churn, net negative. +- **Sequencing:** after Q13 (it blocks Cut 3 anyway) and before Cut 3's + release tag. It can run beside 2a-ii-b. +- **Hands budget:** about 60k tokens. + +--- + +## 4. Sequencing against Asura + +```text +Asura: 2a-ii-a snoise fix (Hands done 0a5f4bf, Soul running) -> 2a-ii-b Phacelle -> 2a-ii-c cultmath 0.3.0 (with bounded LS, already on main 93fe1b9) + \ + Q13 (Geometry CultReference strings) ------------------------------------> Cut 3 cultlib-unity 1.1.0 ---> 4a ... + P4 (Q-F4 = A) ------------------/ (must land before this tag) + +This map: P0 rulings -> P2 (Asura docs, any time) ; P1 (refs, after Q-F3) ; P3 (Fensalir docs, after Q-F2) +``` + +- None of P1–P3 touches CultMath or CultLib source, so none can collide with + the snoise fix, Phacelle, or the 0.3.0 release that carries bounded least + squares. +- P4 is the only cut on Asura's critical path. It must land before Cut 3's + tag, and it touches `GameCult.Geometry`, which Cut 3 packages. Run it in its + own worktree from `main`, never in the snoise worktree. +- The Asura campaign gains nothing from the donor. 4b-iii stays a fresh port. + +--- + +## 5. Operator questions (one fork each) + +### Q-F1. What is a planet in Fensalir *for*? + +Asura answers this for Aetheria: orbital tiny planets, no landing. The donor +answered it for "every renderer, including an Aetheria daemon and strategic +maps", and that answer has been overtaken. What remains is Fensalir's own +Zyphos demo: the domain catalog runs from planet to continent, forest, tree, +leaf and pebble field (`ZyphosSpatialDomainCatalog.cs` on main). That is +landing-scale LOD, which Asura rules out. + +- **A. No planet terrain in Fensalir for now.** Retire the donor (P1–P3). If a + GameCult game later wants planets in Fensalir, it lowers Asura's field HLSL. +- **B. Zyphos needs landing-scale planets.** That is a new campaign with its + own target. It would decide whether streaming LOD extends Asura's field + (one field, two lowerings) or is a separate organ. It must not revive the + July runtime as a second planet-field owner. +- **C. Keep the donor alive as a Fensalir-private runtime.** This recreates a + second planet-field authority beside Asura, over an orphaned library. + +**Recommended: A.** Nothing on main consumes the donor. The Zyphos client has +not moved since 2026-05-30. B stays open as a future campaign and loses nothing +by waiting. + +### Q-F2. The planetary *flow* documents in Fensalir: what are they for now? + +There are three documents (936 lines) for a cube-sphere ocean and atmosphere +advection organ with neural-network budgets (FlowNet-S/M/T). No code exists, +they were last touched 2026-05-29, and their only client is the Zyphos demo. +Asura is not affected. Separately, Asura's target queues "the flow field as the +single owner of motion in Aetheria" as a later campaign. That is a different +flow. + +- **A. Retire** (P3 deletes them). If Zyphos oceans return, their campaign + starts from a target, not from these plans. +- **B. Park them** with a status line. + +**Recommended: B, weakly.** They carry real research (datasets, model sizing), +nothing depends on them, and parking costs 3 lines. Choose A if you want the +docs tree to describe only live machinery. + +### Q-F3. The non-planet work that rides on the same Fensalir branch + +The donor ref also holds 66 Bokusho commits (a D3D12 port beside the TS/WebGPU +`bokusho` repo), 10 Eve native-surface commits, and the Leap/stereo depth, +reservoir and loopback-audio work. None is on Fensalir main. + +- **A. Archive the whole ref** under one tag in P1, and route each of those + lines to its own adoption decision later. +- **B. Adopt them before touching the ref.** + +**Recommended: A.** An archive tag keeps every commit reachable, so B is still +possible afterwards. This map does not judge those lines. + +### Q-F4. Delete Geometry's duplicate vectors before Asura Cut 3 ships them to Unity? + +What is `CultVec3` for? Nothing that `float3` does not already do, and the +surface-nets code converts it straight to `float3` (`CultGeometrySurfaceNets.cs:83`). +The July branch deleted it, and main never did. + +- **A. P4 before Cut 3:** no semver cost, and about −190 lines. +- **B. Ship Cut 3 as is:** a later deletion is a major bump for + `org.gamecult.cultlib`. + +**Recommended: A.** It is the one piece of the geometry half that is right, and +it gets more expensive after Cut 3's release. + +## 6. Findings not assigned to a cut + +- **Unreproducible build (CultLib `6a65369`).** The July CultLib branch + restores `CultMath 0.1.0` from a git-ignored local feed. The "Fensalir and + Aetheria green" receipts in its progress document + (`docs/cultmath-gamecult-geometry-migration-progress.md`, stage 6) could not + have been reproduced from committed sources alone. The branch is being + retired, so this is recorded as a scar and needs no fix. +- **A failing test in the donor's July world.** + `ProjectionTests.CheckedInProjectionReportMatchesSampler` fails on Linux in + the July composite (169/170), and the same test passes on mainline. The most + likely cause is a platform difference in the regenerated report. It was not + chased, because the code is being retired. +- **CultMath's `HlslMirrorTests.cs:7-15`** is a negative spelling test. It + guards against planetary kernels returning to CultMath and is cited by Asura + as the ruling's enforcement. Keep it; after P1 its only threat is gone, but it + is cheap and names the boundary. +- **Stopgap note.** Composite multi-repo snapshots are how a Fensalir build + can be probed on Yggdrasil at all: `ygg-verify.sh` takes one repo, and + Fensalir needs sibling checkouts. The Idunn verify campaign should take a + multi-repo revision set rather than rely on this trick. diff --git a/packages/AquaSynth.Core.0.1.0-alpha.2.nupkg b/packages/AquaSynth.Core.0.1.0-alpha.2.nupkg deleted file mode 100644 index 3b7ea64..0000000 Binary files a/packages/AquaSynth.Core.0.1.0-alpha.2.nupkg and /dev/null differ diff --git a/packages/AquaSynth.Faust.0.1.0-alpha.2.nupkg b/packages/AquaSynth.Faust.0.1.0-alpha.2.nupkg deleted file mode 100644 index 45b861f..0000000 Binary files a/packages/AquaSynth.Faust.0.1.0-alpha.2.nupkg and /dev/null differ diff --git a/packages/AquaSynth.Faust.0.1.0-alpha.3.nupkg b/packages/AquaSynth.Faust.0.1.0-alpha.3.nupkg deleted file mode 100644 index bd1391e..0000000 Binary files a/packages/AquaSynth.Faust.0.1.0-alpha.3.nupkg and /dev/null differ diff --git a/scripts/dev-reload.ps1 b/scripts/dev-reload.ps1 index 26a9520..574f364 100644 --- a/scripts/dev-reload.ps1 +++ b/scripts/dev-reload.ps1 @@ -19,6 +19,7 @@ $liveProjectPath = (Resolve-Path $liveProjectPath).Path $liveAssemblyName = [System.IO.Path]::GetFileNameWithoutExtension($liveProjectPath) $devRoot = Join-Path $repoRoot "artifacts\dev-reload" $slotRoot = Join-Path $devRoot "slots" +$liveSlotRoot = Join-Path $devRoot "live-slots" $visibleStatePath = Join-Path $devRoot "state.clixml" $headlessStatePath = Join-Path $devRoot "headless-state.clixml" $statePath = if ($Headless) { $headlessStatePath } else { $visibleStatePath } @@ -79,9 +80,11 @@ function Remove-OldSlots { return } - $slots = Get-ChildItem -Path $slotRoot -Directory -ErrorAction SilentlyContinue | - Sort-Object LastWriteTimeUtc -Descending | - Select-Object -Skip $RetainSlots + $slots = foreach ($root in @($slotRoot, $liveSlotRoot)) { + Get-ChildItem -Path $root -Directory -ErrorAction SilentlyContinue | + Sort-Object LastWriteTimeUtc -Descending | + Select-Object -Skip $RetainSlots + } foreach ($slot in $slots) { try { @@ -241,6 +244,10 @@ function Reopen-VisibleProcess { $liveAssemblyPath = [string]$state.liveAssembly } + if (-not (Test-Path -LiteralPath $liveAssemblyPath)) { + throw "Visible dev-reload state names '$liveAssemblyPath', which no longer exists (pruned slot). Run dev-reload without -Reopen to rebuild." + } + $process = Start-AquariumProcess -SlotPath $slotPath -LiveAssemblyPath $liveAssemblyPath -RunHeadless:$false Wait-ForStartedAquarium -Process $process -ExpectWindow:$true diff --git a/src/Aquarium.Engine/Aquarium.Engine.csproj b/src/Aquarium.Engine/Aquarium.Engine.csproj index 911e96a..8bf3795 100644 --- a/src/Aquarium.Engine/Aquarium.Engine.csproj +++ b/src/Aquarium.Engine/Aquarium.Engine.csproj @@ -1,6 +1,7 @@ + $(MSBuildThisFileDirectory)..\..\..\CultLib WinExe net10.0 enable @@ -22,14 +23,13 @@ - + - diff --git a/src/Aquarium.Engine/AquariumHost.cs b/src/Aquarium.Engine/AquariumHost.cs index 7ba0c72..1966946 100644 --- a/src/Aquarium.Engine/AquariumHost.cs +++ b/src/Aquarium.Engine/AquariumHost.cs @@ -18,8 +18,21 @@ public static class AquariumHost ParseFieldReservoirMode(args), ParseFieldReservoirScale(args), ParseFieldReservoirSpatialReuseBudget(args)); - using var runtimeLoader = new ClientRuntimeLoader(runtimeOptions, ParseClientAssemblyPath(args), ParseClientReloadPointerPath(args)); - var runtime = runtimeLoader.Load(); + ClientRuntimeLoader? loader = null; + IAquariumRuntime runtime; + try + { + loader = new ClientRuntimeLoader(runtimeOptions, ParseClientAssemblyPath(args), ParseClientReloadPointerPath(args)); + runtime = loader.Load(); + } + catch (Exception error) + { + Console.Error.WriteLine($"Client runtime failed to start ({error.GetType().FullName ?? error.GetType().Name}). {error.Message}"); + loader?.Dispose(); + return 1; + } + + using var runtimeLoader = loader; if (runtimeOptions.RenderDebugModeOverride is { } renderDebugModeOverride) { runtime.GraphicsSettings = (runtime.GraphicsSettings with diff --git a/src/Aquarium.Engine/Assets/Fensalir-Splash.png b/src/Aquarium.Engine/Assets/Fensalir-Splash.png deleted file mode 100644 index a2b1afc..0000000 Binary files a/src/Aquarium.Engine/Assets/Fensalir-Splash.png and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.png b/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.png deleted file mode 100644 index e7d9173..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.png and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.r8 b/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.r8 deleted file mode 100644 index bcf3b09..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.r8 and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/studio2_irradiance.dds b/src/Aquarium.Engine/Assets/Textures/studio2_irradiance.dds deleted file mode 100644 index a3246b1..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/studio2_irradiance.dds and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds b/src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds deleted file mode 100644 index c8487bf..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds and /dev/null differ diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 6cdb517..2eb9192 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -237,9 +237,9 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly D3D12StructuredBuffer sdfObjectBuffer; private readonly D3D12StructuredBuffer gpuSensorCameraBuffer; private readonly D3D12StructuredBuffer acousticConstraintBuffer; - private readonly D3D12StructuredBuffer gpuFusionSeedBuffer; - private readonly D3D12StructuredBuffer gpuFusionPointBuffer; - private readonly D3D12StructuredBuffer temporalGaussianBuffer; + private D3D12StructuredBuffer? gpuFusionSeedBuffer; + private D3D12StructuredBuffer? gpuFusionPointBuffer; + private D3D12StructuredBuffer? temporalGaussianBuffer; private D3D12StructuredBuffer? fractalSplatBuffer; private D3D12StructuredBuffer? fractalSdfReservoirBuffer; private D3D12StructuredBuffer? fractalPbrReservoirBuffer; @@ -248,11 +248,11 @@ public sealed class D3D12Renderer : IAquariumRenderer private D3D12StructuredBuffer? fractalProgramTransformBuffer; private D3D12StructuredBuffer? bufferFieldTextureSplineProgramBuffer; private D3D12StructuredBuffer? bufferFieldTextureSampleBuffer; - private readonly D3D12StructuredBuffer tubeFieldVertexBuffer; - private readonly D3D12StructuredBuffer tubeFieldIndexBuffer; - private readonly D3D12StructuredBuffer tubeFieldSegmentBuffer; - private readonly D3D12StructuredBuffer tubeFieldStatsBuffer; - private readonly D3D12StructuredBuffer tubeFieldDrawArgumentBuffer; + private D3D12StructuredBuffer? tubeFieldVertexBuffer; + private D3D12StructuredBuffer? tubeFieldIndexBuffer; + private D3D12StructuredBuffer? tubeFieldSegmentBuffer; + private D3D12StructuredBuffer? tubeFieldStatsBuffer; + private D3D12StructuredBuffer? tubeFieldDrawArgumentBuffer; private readonly D3D12StructuredBuffer tubeFieldReplayManifestBuffer; private D3D12StructuredBuffer fieldReservoirCandidateBuffer = null!; private D3D12StructuredBuffer fieldReservoirLockBuffer = null!; @@ -280,8 +280,8 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly AquariumSdfObject[] sdfObjects = new AquariumSdfObject[MaxSdfObjectCount]; private readonly D3D12GpuSensorCameraPacket[] gpuSensorCameras = new D3D12GpuSensorCameraPacket[MaxGpuSensorCameraCount]; private readonly D3D12AcousticConstraintPacket[] acousticConstraints = new D3D12AcousticConstraintPacket[MaxAcousticConstraintCount]; - private readonly D3D12GpuFusionSeedPacket[] gpuFusionSeeds = new D3D12GpuFusionSeedPacket[MaxTemporalGaussianCount]; - private readonly D3D12TemporalGaussianPacket[] temporalGaussians = new D3D12TemporalGaussianPacket[MaxTemporalGaussianCount]; + private D3D12GpuFusionSeedPacket[]? gpuFusionSeeds; + private D3D12TemporalGaussianPacket[]? temporalGaussians; private AquariumGpuFusionPointBuffer gpuFusionPointSource; private int temporalGaussianCount; private int gpuSensorCameraCount; @@ -444,28 +444,12 @@ public sealed class D3D12Renderer : IAquariumRenderer sdfObjectBuffer = new D3D12StructuredBuffer(device, MaxSdfObjectCount, Marshal.SizeOf(), "Aquarium D3D12 Sdf Object Buffer"); gpuSensorCameraBuffer = new D3D12StructuredBuffer(device, MaxGpuSensorCameraCount, Marshal.SizeOf(), "Aquarium D3D12 GPU Sensor Camera Buffer"); acousticConstraintBuffer = new D3D12StructuredBuffer(device, MaxAcousticConstraintCount, Marshal.SizeOf(), "Aquarium D3D12 Acoustic Constraint Buffer"); - gpuFusionSeedBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 GPU Sensor Fusion Seed Buffer"); - gpuFusionPointBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 GPU Sensor Fusion Native Point Buffer"); - temporalGaussianBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 Temporal Gaussian Buffer", allowUnorderedAccess: true); - tubeFieldVertexBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldVertices, Marshal.SizeOf(), "Aquarium D3D12 TubeField Vertex Buffer", allowUnorderedAccess: true); - tubeFieldIndexBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldIndices, Marshal.SizeOf(), "Aquarium D3D12 TubeField Index Buffer", allowUnorderedAccess: true); - tubeFieldSegmentBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldSegments, Marshal.SizeOf(), "Aquarium D3D12 TubeField Segment Buffer", allowUnorderedAccess: true); - tubeFieldStatsBuffer = new D3D12StructuredBuffer(device, 4, Marshal.SizeOf(), "Aquarium D3D12 TubeField Stats Buffer", allowUnorderedAccess: true); - tubeFieldDrawArgumentBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldDrawBatches * GeneratedMeshDrawArgumentUIntCount, Marshal.SizeOf(), "Aquarium D3D12 TubeField Indirect Draw Arguments", allowUnorderedAccess: true); tubeFieldReplayManifestBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldReplaySources, Marshal.SizeOf(), "Aquarium D3D12 TubeField Replay Manifest"); CreateFieldReservoirBuffers(); resourceRegistry.Add("sdf-light-buffer", sdfLightBuffer); resourceRegistry.Add("sdf-object-buffer", sdfObjectBuffer); resourceRegistry.Add("gpu-sensor-camera-buffer", gpuSensorCameraBuffer); resourceRegistry.Add("acoustic-constraint-buffer", acousticConstraintBuffer); - resourceRegistry.Add("gpu-fusion-seed-buffer", gpuFusionSeedBuffer); - resourceRegistry.Add("gpu-fusion-point-buffer", gpuFusionPointBuffer); - resourceRegistry.Add("temporal-gaussian-buffer", temporalGaussianBuffer); - resourceRegistry.Add("tube-field-vertex-buffer", tubeFieldVertexBuffer); - resourceRegistry.Add("tube-field-index-buffer", tubeFieldIndexBuffer); - resourceRegistry.Add("tube-field-segment-buffer", tubeFieldSegmentBuffer); - resourceRegistry.Add("tube-field-stats-buffer", tubeFieldStatsBuffer); - resourceRegistry.Add("tube-field-indirect-draw-arguments", tubeFieldDrawArgumentBuffer); resourceRegistry.Add("tube-field-replay-manifest", tubeFieldReplayManifestBuffer); commandList = device.CreateCommandList(0, CommandListType.Direct, frames[frameIndex].CommandAllocator, null); commandList.Name = "Aquarium D3D12 Graphics Command List"; @@ -882,6 +866,8 @@ public sealed class D3D12Renderer : IAquariumRenderer EnsureFractalReservoirBuffers(activeFractalReservoirField); EnsureFractalProgramTransformBuffer(); EnsureBufferFieldProgramBuffers(); + EnsureTemporalGaussianResources(); + EnsureGpuSensorFusionResources(); var activeGpuSensorInput = frame.Scene.GpuSensorFrame.HasInput; var activeAccumulationWindow = activeGpuSensorInput ? frame.Scene.GpuSensorFrame.AccumulationWindowSeconds @@ -962,14 +948,40 @@ public sealed class D3D12Renderer : IAquariumRenderer CreateGpuSensorTextureViews(frame.Scene.GpuSensorFrame, frameResources.GpuSensorTextureDescriptor); frameResources.AcousticConstraintDescriptor = frameResources.TransientShaderDescriptors.Allocate(); acousticConstraintBuffer.CreateShaderResourceView(device, frameResources.AcousticConstraintDescriptor); - frameResources.GpuFusionSeedDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - gpuFusionSeedBuffer.CreateShaderResourceView(device, frameResources.GpuFusionSeedDescriptor); - frameResources.GpuFusionPointDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - gpuFusionPointBuffer.CreateShaderResourceView(device, frameResources.GpuFusionPointDescriptor); + if (temporalGaussiansGpuGenerated && temporalGaussianCount > 0) + { + frameResources.GpuFusionSeedDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + if (gpuFusionSeedBuffer is not null) + { + gpuFusionSeedBuffer.CreateShaderResourceView(device, frameResources.GpuFusionSeedDescriptor); + } + else + { + CreateNullStructuredBufferView(frameResources.GpuFusionSeedDescriptor, Marshal.SizeOf()); + } + + frameResources.GpuFusionPointDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + if (gpuFusionPointBuffer is not null) + { + gpuFusionPointBuffer.CreateShaderResourceView(device, frameResources.GpuFusionPointDescriptor); + } + else + { + CreateNullStructuredBufferView(frameResources.GpuFusionPointDescriptor, Marshal.SizeOf()); + } + } + frameResources.TemporalGaussianDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - temporalGaussianBuffer.CreateShaderResourceView(device, frameResources.TemporalGaussianDescriptor); - frameResources.TemporalGaussianUnorderedAccessDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - temporalGaussianBuffer.CreateUnorderedAccessView(device, frameResources.TemporalGaussianUnorderedAccessDescriptor); + if (temporalGaussianBuffer is not null) + { + temporalGaussianBuffer.CreateShaderResourceView(device, frameResources.TemporalGaussianDescriptor); + frameResources.TemporalGaussianUnorderedAccessDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + temporalGaussianBuffer.CreateUnorderedAccessView(device, frameResources.TemporalGaussianUnorderedAccessDescriptor); + } + else + { + CreateNullStructuredBufferView(frameResources.TemporalGaussianDescriptor, Marshal.SizeOf()); + } frameResources.BlueNoiseDescriptor = frameResources.TransientShaderDescriptors.Allocate(); blueNoiseTexture.CreateShaderResourceView(device, frameResources.BlueNoiseDescriptor); frameResources.StudioPmremDescriptor = frameResources.TransientShaderDescriptors.Allocate(); @@ -1158,16 +1170,12 @@ public sealed class D3D12Renderer : IAquariumRenderer && heightFieldBrushPipelineState is not null && scenePipelineState is not null && splinePipelineState is not null - && temporalGaussianPipelineState is not null - && gpuSensorFusionPipelineState is not null && fractalSurfaceSplatRenderPipelineState is not null && fractalTransparentSplatRenderPipelineState is not null && fractalSplatPipelineState is not null && fractalSdfReservoirPipelineState is not null && fractalPbrReservoirPipelineState is not null && fractalRadiosityReservoirPipelineState is not null - && tubeFieldComputePipelineState is not null - && tubeFieldRenderPipelineState is not null && fieldReservoirResolvePipelineState is not null && sdfProxyPipelineStates.All(pipeline => pipeline is not null) && bloomPrefilterPipelineState is not null @@ -1221,18 +1229,18 @@ public sealed class D3D12Renderer : IAquariumRenderer DisposeFractalReservoirBuffers(); bufferFieldTextureSplineProgramBuffer?.Dispose(); bufferFieldTextureSampleBuffer?.Dispose(); - tubeFieldStatsBuffer.Dispose(); - tubeFieldDrawArgumentBuffer.Dispose(); + tubeFieldStatsBuffer?.Dispose(); + tubeFieldDrawArgumentBuffer?.Dispose(); tubeFieldReplayManifestBuffer.Dispose(); - tubeFieldSegmentBuffer.Dispose(); - tubeFieldIndexBuffer.Dispose(); - tubeFieldVertexBuffer.Dispose(); + tubeFieldSegmentBuffer?.Dispose(); + tubeFieldIndexBuffer?.Dispose(); + tubeFieldVertexBuffer?.Dispose(); fieldReservoirLockBuffer.Dispose(); fieldReservoirCandidateBuffer.Dispose(); DisposeFieldReservoirHistoryBuffers(); - temporalGaussianBuffer.Dispose(); - gpuFusionPointBuffer.Dispose(); - gpuFusionSeedBuffer.Dispose(); + temporalGaussianBuffer?.Dispose(); + gpuFusionPointBuffer?.Dispose(); + gpuFusionSeedBuffer?.Dispose(); acousticConstraintBuffer.Dispose(); gpuSensorCameraBuffer.Dispose(); foreach (var texture in externalSensorTextures.Values) @@ -1824,7 +1832,11 @@ public sealed class D3D12Renderer : IAquariumRenderer overlayWrappedBackBuffers = []; } - private D3D12PipelineSet CreatePipelineSet(D3D12ShaderPaths paths) + private D3D12PipelineSet CreatePipelineSet( + D3D12ShaderPaths paths, + bool includeTemporalGaussian, + bool includeGpuSensorFusion, + bool includeTubeField) { var heightFieldBase = CreateHeightFieldBasePipelineState(paths.HeightField); heightFieldBase.Name = "Aquarium D3D12 Height Field Base Pipeline"; @@ -1834,10 +1846,18 @@ public sealed class D3D12Renderer : IAquariumRenderer scene.Name = "Aquarium D3D12 Scene Pipeline"; var spline = CreateSplinePipelineState(paths.Spline); spline.Name = "Aquarium D3D12 Spline Surface Claim Pipeline"; - var temporalGaussian = CreateTemporalGaussianPipelineState(paths.TemporalGaussian); - temporalGaussian.Name = "Aquarium D3D12 Temporal Gaussian Pipeline"; - var gpuSensorFusion = CreateGpuSensorFusionPipelineState(paths.GpuSensorFusion); - gpuSensorFusion.Name = "Aquarium D3D12 GPU Sensor Fusion Compute Pipeline"; + ID3D12PipelineState? temporalGaussian = null; + if (includeTemporalGaussian) + { + temporalGaussian = CreateTemporalGaussianPipelineState(paths.TemporalGaussian); + temporalGaussian.Name = "Aquarium D3D12 Temporal Gaussian Pipeline"; + } + ID3D12PipelineState? gpuSensorFusion = null; + if (includeGpuSensorFusion) + { + gpuSensorFusion = CreateGpuSensorFusionPipelineState(paths.GpuSensorFusion); + gpuSensorFusion.Name = "Aquarium D3D12 GPU Sensor Fusion Compute Pipeline"; + } var fractalSurfaceSplatRender = CreateFractalSurfaceSplatRenderPipelineState(paths.FractalSplatRender); fractalSurfaceSplatRender.Name = "Aquarium D3D12 Fractal Surface Splat Render Pipeline"; var fractalTransparentSplatRender = CreateFractalTransparentSplatRenderPipelineState(paths.FractalSplatRender); @@ -1850,10 +1870,15 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalPbrReservoir.Name = "Aquarium D3D12 Fractal PBR Reservoir Compute Pipeline"; var fractalRadiosityReservoir = CreateFractalReservoirPipelineState(paths.FractalReservoir, "D3D12RadiosityReservoirCS"); fractalRadiosityReservoir.Name = "Aquarium D3D12 Fractal Radiosity Reservoir Compute Pipeline"; - var tubeFieldCompute = CreateTubeFieldComputePipelineState(paths.TubeField); - tubeFieldCompute.Name = "Aquarium D3D12 TubeField Compute Pipeline"; - var tubeFieldRender = CreateTubeFieldRenderPipelineState(paths.TubeField); - tubeFieldRender.Name = "Aquarium D3D12 TubeField Render Pipeline"; + ID3D12PipelineState? tubeFieldCompute = null; + ID3D12PipelineState? tubeFieldRender = null; + if (includeTubeField) + { + tubeFieldCompute = CreateTubeFieldComputePipelineState(paths.TubeField); + tubeFieldCompute.Name = "Aquarium D3D12 TubeField Compute Pipeline"; + tubeFieldRender = CreateTubeFieldRenderPipelineState(paths.TubeField); + tubeFieldRender.Name = "Aquarium D3D12 TubeField Render Pipeline"; + } var fieldReservoirResolve = CreateFieldReservoirResolvePipelineState(paths.Post); fieldReservoirResolve.Name = "Aquarium D3D12 Field Reservoir Resolve Pipeline"; var sdfProxies = new ID3D12PipelineState[paths.SdfShaders.Count]; @@ -2406,6 +2431,135 @@ public sealed class D3D12Renderer : IAquariumRenderer } } + private void EnsureTemporalGaussianResources() + { + if (temporalGaussianCount <= 0) + { + return; + } + + if (temporalGaussianBuffer is null) + { + temporalGaussianBuffer = new D3D12StructuredBuffer( + device, + MaxTemporalGaussianCount, + Marshal.SizeOf(), + "Aquarium D3D12 Temporal Gaussian Buffer", + allowUnorderedAccess: true); + resourceRegistry.Add("temporal-gaussian-buffer", temporalGaussianBuffer); + } + + if (temporalGaussianPipelineState is null) + { + temporalGaussianPipelineState = CreateTemporalGaussianPipelineState(shaderPaths.TemporalGaussian); + temporalGaussianPipelineState.Name = "Aquarium D3D12 Temporal Gaussian Pipeline"; + } + } + + private void EnsureGpuSensorFusionResources() + { + if (!temporalGaussiansGpuGenerated || temporalGaussianCount <= 0) + { + return; + } + + if (gpuFusionPointCount > 0 && gpuFusionPointBuffer is null) + { + gpuFusionPointBuffer = new D3D12StructuredBuffer( + device, + MaxTemporalGaussianCount, + Marshal.SizeOf(), + "Aquarium D3D12 GPU Sensor Fusion Native Point Buffer"); + resourceRegistry.Add("gpu-fusion-point-buffer", gpuFusionPointBuffer); + } + + if (gpuFusionSeedCount > 0 && gpuFusionSeedBuffer is null) + { + gpuFusionSeedBuffer = new D3D12StructuredBuffer( + device, + MaxTemporalGaussianCount, + Marshal.SizeOf(), + "Aquarium D3D12 GPU Sensor Fusion Seed Buffer"); + resourceRegistry.Add("gpu-fusion-seed-buffer", gpuFusionSeedBuffer); + } + + if (gpuSensorFusionPipelineState is null) + { + gpuSensorFusionPipelineState = CreateGpuSensorFusionPipelineState(shaderPaths.GpuSensorFusion); + gpuSensorFusionPipelineState.Name = "Aquarium D3D12 GPU Sensor Fusion Compute Pipeline"; + } + } + + private void EnsureTubeFieldResources() + { + if (tubeFieldVertexBuffer is null) + { + tubeFieldVertexBuffer = new D3D12StructuredBuffer( + device, + MaxTubeFieldVertices, + Marshal.SizeOf(), + "Aquarium D3D12 TubeField Vertex Buffer", + allowUnorderedAccess: true); + resourceRegistry.Add("tube-field-vertex-buffer", tubeFieldVertexBuffer); + } + + if (tubeFieldIndexBuffer is null) + { + tubeFieldIndexBuffer = new D3D12StructuredBuffer( + device, + MaxTubeFieldIndices, + Marshal.SizeOf(), + "Aquarium D3D12 TubeField Index Buffer", + allowUnorderedAccess: true); + resourceRegistry.Add("tube-field-index-buffer", tubeFieldIndexBuffer); + } + + if (tubeFieldSegmentBuffer is null) + { + tubeFieldSegmentBuffer = new D3D12StructuredBuffer( + device, + MaxTubeFieldSegments, + Marshal.SizeOf(), + "Aquarium D3D12 TubeField Segment Buffer", + allowUnorderedAccess: true); + resourceRegistry.Add("tube-field-segment-buffer", tubeFieldSegmentBuffer); + } + + if (tubeFieldStatsBuffer is null) + { + tubeFieldStatsBuffer = new D3D12StructuredBuffer( + device, + 4, + Marshal.SizeOf(), + "Aquarium D3D12 TubeField Stats Buffer", + allowUnorderedAccess: true); + resourceRegistry.Add("tube-field-stats-buffer", tubeFieldStatsBuffer); + } + + if (tubeFieldDrawArgumentBuffer is null) + { + tubeFieldDrawArgumentBuffer = new D3D12StructuredBuffer( + device, + MaxTubeFieldDrawBatches * GeneratedMeshDrawArgumentUIntCount, + Marshal.SizeOf(), + "Aquarium D3D12 TubeField Indirect Draw Arguments", + allowUnorderedAccess: true); + resourceRegistry.Add("tube-field-indirect-draw-arguments", tubeFieldDrawArgumentBuffer); + } + + if (tubeFieldComputePipelineState is null) + { + tubeFieldComputePipelineState = CreateTubeFieldComputePipelineState(shaderPaths.TubeField); + tubeFieldComputePipelineState.Name = "Aquarium D3D12 TubeField Compute Pipeline"; + } + + if (tubeFieldRenderPipelineState is null) + { + tubeFieldRenderPipelineState = CreateTubeFieldRenderPipelineState(shaderPaths.TubeField); + tubeFieldRenderPipelineState.Name = "Aquarium D3D12 TubeField Render Pipeline"; + } + } + private void DisposeFractalReservoirBuffers() { resourceRegistry.RemoveStructuredBuffer("buffer-field-texture-sample-buffer"); @@ -2516,9 +2670,9 @@ public sealed class D3D12Renderer : IAquariumRenderer context.CommandList.DrawInstanced(6, 1, 0, 0); } - if (temporalGaussianCount > 0) + if (temporalGaussianCount > 0 && temporalGaussianPipelineState is not null) { - context.CommandList.SetPipelineState(temporalGaussianPipelineState!); + context.CommandList.SetPipelineState(temporalGaussianPipelineState); context.CommandList.DrawInstanced(6, (uint)temporalGaussianCount, 0, 0); } @@ -2686,7 +2840,7 @@ public sealed class D3D12Renderer : IAquariumRenderer batch.Source.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); } - tubeFieldStatsBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + tubeFieldStatsBuffer?.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); tubeFieldReplayManifestBuffer.Upload(activeCommandList, frameResources.UploadRing, replayManifest); activeCommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); @@ -2694,8 +2848,18 @@ public sealed class D3D12Renderer : IAquariumRenderer for (var index = 0; index < MaxTubeFieldReplaySources; index++) { var descriptor = frameResources.TransientShaderDescriptors.Offset(replaySourceDescriptors, index); - var source = index < replaySourceCount ? tubeFieldDrawBatches[index].Source : tubeFieldStatsBuffer; - source.CreateRawShaderResourceView(device, descriptor); + if (index < replaySourceCount) + { + tubeFieldDrawBatches[index].Source.CreateRawShaderResourceView(device, descriptor); + } + else if (tubeFieldStatsBuffer is not null) + { + tubeFieldStatsBuffer.CreateRawShaderResourceView(device, descriptor); + } + else + { + CreateNullRawBufferView(descriptor); + } } activeCommandList.SetPipelineState(reservoirHistoryUpdatePipelineState); @@ -2723,7 +2887,12 @@ public sealed class D3D12Renderer : IAquariumRenderer private void RenderTubeFields(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { - if (activeTubeFieldDrawIndexCount <= 0 || tubeFieldRenderPipelineState is null || tubeFieldDrawBatches.Count == 0) + if (activeTubeFieldDrawIndexCount <= 0 + || tubeFieldRenderPipelineState is null + || tubeFieldDrawBatches.Count == 0 + || tubeFieldVertexBuffer is null + || tubeFieldIndexBuffer is null + || tubeFieldDrawArgumentBuffer is null) { return; } @@ -3076,21 +3245,21 @@ public sealed class D3D12Renderer : IAquariumRenderer { if (gpuFusionPointCount > 0) { - gpuFusionPointBuffer.UploadPartialBytes( + gpuFusionPointBuffer!.UploadPartialBytes( activeCommandList, frameResources.UploadRing, gpuFusionPointSource.Buffer, gpuFusionPointCount, gpuFusionPointSource.StrideBytes); } - else + else if (gpuFusionSeedCount > 0) { - gpuFusionSeedBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, gpuFusionSeeds.AsSpan(0, gpuFusionSeedCount)); + gpuFusionSeedBuffer!.UploadPartial(activeCommandList, frameResources.UploadRing, gpuFusionSeeds!.AsSpan(0, gpuFusionSeedCount)); } } - else + else if (temporalGaussianCount > 0) { - temporalGaussianBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, temporalGaussians.AsSpan(0, temporalGaussianCount)); + temporalGaussianBuffer!.UploadPartial(activeCommandList, frameResources.UploadRing, temporalGaussians!.AsSpan(0, temporalGaussianCount)); } } finally @@ -3101,7 +3270,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private void DispatchGpuSensorFusion(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { - if (!temporalGaussiansGpuGenerated || temporalGaussianCount <= 0) + if (!temporalGaussiansGpuGenerated || temporalGaussianCount <= 0 || temporalGaussianBuffer is null || gpuSensorFusionPipelineState is null) { return; } @@ -3109,12 +3278,12 @@ public sealed class D3D12Renderer : IAquariumRenderer activeCommandList.BeginEvent("GPU Sensor Fusion"); try { - gpuFusionSeedBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - gpuFusionPointBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + gpuFusionSeedBuffer?.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + gpuFusionPointBuffer?.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); temporalGaussianBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); activeCommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); activeCommandList.SetComputeRootSignature(gpuSensorFusionRootSignature); - activeCommandList.SetPipelineState(gpuSensorFusionPipelineState!); + activeCommandList.SetPipelineState(gpuSensorFusionPipelineState); activeCommandList.SetComputeRootDescriptorTable(RootFusionFrameConstants, frameResources.FrameConstantsDescriptor.Gpu); activeCommandList.SetComputeRootDescriptorTable(RootFusionSeeds, frameResources.GpuFusionSeedDescriptor.Gpu); activeCommandList.SetComputeRootDescriptorTable(RootFusionSensorCameras, frameResources.GpuSensorCameraDescriptor.Gpu); @@ -3216,7 +3385,7 @@ public sealed class D3D12Renderer : IAquariumRenderer activeFieldResourceUploadCount = 0; activeFieldResourceUploadSkippedCount = 0; tubeFieldDrawBatches.Clear(); - if (tubeFieldComputePipelineState is null || activeFieldEvidenceFrame.TubeSplineLowerings.Count == 0) + if (activeFieldEvidenceFrame.TubeSplineLowerings.Count == 0) { return; } @@ -3277,6 +3446,8 @@ public sealed class D3D12Renderer : IAquariumRenderer continue; } + EnsureTubeFieldResources(); + activeTubeFieldTruncatedSegments += requestedSegments - dispatchSegments; var startIndex = segmentBase * 6; var fieldId = StableFieldId(lowering.ClaimKey, 5100.0f, 4096); @@ -3299,19 +3470,19 @@ public sealed class D3D12Renderer : IAquariumRenderer var constantsUpload = frameResources.UploadRing.WriteConstant(constants); sourceBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - tubeFieldVertexBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - tubeFieldIndexBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - tubeFieldStatsBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - tubeFieldDrawArgumentBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); + tubeFieldVertexBuffer!.Transition(activeCommandList, ResourceStates.UnorderedAccess); + tubeFieldIndexBuffer!.Transition(activeCommandList, ResourceStates.UnorderedAccess); + tubeFieldStatsBuffer!.Transition(activeCommandList, ResourceStates.UnorderedAccess); + tubeFieldDrawArgumentBuffer!.Transition(activeCommandList, ResourceStates.UnorderedAccess); activeCommandList.SetComputeRootSignature(tubeFieldRootSignature); - activeCommandList.SetPipelineState(tubeFieldComputePipelineState); + activeCommandList.SetPipelineState(tubeFieldComputePipelineState!); activeCommandList.SetComputeRootConstantBufferView(RootTubeFieldConstants, constantsUpload.GpuVirtualAddress); activeCommandList.SetComputeRootShaderResourceView(RootTubeFieldSource, sourceBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldVertices, tubeFieldVertexBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldIndices, tubeFieldIndexBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldStats, tubeFieldStatsBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldDrawArguments, tubeFieldDrawArgumentBuffer.Resource.GPUVirtualAddress); - tubeFieldSegmentBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); + tubeFieldSegmentBuffer!.Transition(activeCommandList, ResourceStates.UnorderedAccess); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldSegments, tubeFieldSegmentBuffer.Resource.GPUVirtualAddress); var ramp = ResolveTubeFieldRamp(activeCommandList, normalized.RampResourceKey); ramp.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); @@ -3506,6 +3677,46 @@ public sealed class D3D12Renderer : IAquariumRenderer descriptor.Cpu); } + private void CreateNullStructuredBufferView(D3D12DescriptorSlot descriptor, int strideBytes) + { + device.CreateShaderResourceView( + null, + new ShaderResourceViewDescription + { + Format = Format.Unknown, + ViewDimension = Vortice.Direct3D12.ShaderResourceViewDimension.Buffer, + Shader4ComponentMapping = ShaderComponentMapping.Default, + Buffer = new BufferShaderResourceView + { + FirstElement = 0, + NumElements = 1, + StructureByteStride = (uint)strideBytes, + Flags = BufferShaderResourceViewFlags.None, + }, + }, + descriptor.Cpu); + } + + private void CreateNullRawBufferView(D3D12DescriptorSlot descriptor) + { + device.CreateShaderResourceView( + null, + new ShaderResourceViewDescription + { + Format = Format.R32_Typeless, + ViewDimension = Vortice.Direct3D12.ShaderResourceViewDimension.Buffer, + Shader4ComponentMapping = ShaderComponentMapping.Default, + Buffer = new BufferShaderResourceView + { + FirstElement = 0, + NumElements = 1, + StructureByteStride = 0, + Flags = BufferShaderResourceViewFlags.Raw, + }, + }, + descriptor.Cpu); + } + private void RenderHeightField(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { var viewport = new Viewport(0.0f, 0.0f, HeightFieldTextureSize, HeightFieldTextureSize); @@ -3629,6 +3840,7 @@ public sealed class D3D12Renderer : IAquariumRenderer temporalGaussianCount = seedCount; gpuFusionSeedCount = seedCount; temporalGaussiansGpuGenerated = true; + gpuFusionSeeds ??= new D3D12GpuFusionSeedPacket[MaxTemporalGaussianCount]; for (var index = 0; index < seedCount; index++) { gpuFusionSeeds[index] = ToGpuFusionSeedPacket(scene.GpuFusionField.Seeds[index]); @@ -3646,9 +3858,13 @@ public sealed class D3D12Renderer : IAquariumRenderer var gaussianCount = Math.Min(scene.TemporalGaussianField.Gaussians.Count, MaxTemporalGaussianCount); temporalGaussianCount = gaussianCount; - for (var index = 0; index < gaussianCount; index++) + if (gaussianCount > 0) { - temporalGaussians[index] = ToTemporalGaussianPacket(scene.TemporalGaussianField.Gaussians[index]); + temporalGaussians ??= new D3D12TemporalGaussianPacket[MaxTemporalGaussianCount]; + for (var index = 0; index < gaussianCount; index++) + { + temporalGaussians[index] = ToTemporalGaussianPacket(scene.TemporalGaussianField.Gaussians[index]); + } } } @@ -4256,9 +4472,12 @@ public sealed class D3D12Renderer : IAquariumRenderer } var paths = shaderPaths; + var includeTemporalGaussian = temporalGaussianPipelineState is not null || temporalGaussianCount > 0; + var includeGpuSensorFusion = gpuSensorFusionPipelineState is not null || (temporalGaussiansGpuGenerated && temporalGaussianCount > 0); + var includeTubeField = tubeFieldComputePipelineState is not null || tubeFieldRenderPipelineState is not null || activeFieldEvidenceFrame.TubeSplineLowerings.Count > 0; LatestShaderWriteTimeUtc(); pipelineBuildInProgressReported = false; - pipelineBuildTask = Task.Run(() => CreatePipelineSet(paths)); + pipelineBuildTask = Task.Run(() => CreatePipelineSet(paths, includeTemporalGaussian, includeGpuSensorFusion, includeTubeField)); Console.WriteLine($"D3D12 shader pipeline build started ({reason}): {shaderSourceRoot}"); } @@ -4294,7 +4513,11 @@ public sealed class D3D12Renderer : IAquariumRenderer } var replacement = task.Result; - var oldPipelines = CapturePipelineSetOrNull(); + var oldPipelines = CapturePipelineSetOrNull( + includeTemporalGaussian: replacement.TemporalGaussian is not null, + includeGpuSensorFusion: replacement.GpuSensorFusion is not null, + includeTubeFieldCompute: replacement.TubeFieldCompute is not null, + includeTubeFieldRender: replacement.TubeFieldRender is not null); if (oldPipelines is not null) { WaitForGpu(); @@ -4316,7 +4539,11 @@ public sealed class D3D12Renderer : IAquariumRenderer } } - private D3D12PipelineSet? CapturePipelineSetOrNull() + private D3D12PipelineSet? CapturePipelineSetOrNull( + bool includeTemporalGaussian = true, + bool includeGpuSensorFusion = true, + bool includeTubeFieldCompute = true, + bool includeTubeFieldRender = true) { return PipelinesReady ? new D3D12PipelineSet( @@ -4324,16 +4551,16 @@ public sealed class D3D12Renderer : IAquariumRenderer heightFieldBrushPipelineState!, scenePipelineState!, splinePipelineState!, - temporalGaussianPipelineState!, - gpuSensorFusionPipelineState!, + includeTemporalGaussian ? temporalGaussianPipelineState : null, + includeGpuSensorFusion ? gpuSensorFusionPipelineState : null, fractalSurfaceSplatRenderPipelineState!, fractalTransparentSplatRenderPipelineState!, fractalSplatPipelineState!, fractalSdfReservoirPipelineState!, fractalPbrReservoirPipelineState!, fractalRadiosityReservoirPipelineState!, - tubeFieldComputePipelineState!, - tubeFieldRenderPipelineState!, + includeTubeFieldCompute ? tubeFieldComputePipelineState : null, + includeTubeFieldRender ? tubeFieldRenderPipelineState : null, fieldReservoirResolvePipelineState!, sdfProxyPipelineStates.Select(pipeline => pipeline!).ToArray(), bloomPrefilterPipelineState!, @@ -4351,16 +4578,28 @@ public sealed class D3D12Renderer : IAquariumRenderer heightFieldBrushPipelineState = pipelines.HeightFieldBrush; scenePipelineState = pipelines.Scene; splinePipelineState = pipelines.Spline; - temporalGaussianPipelineState = pipelines.TemporalGaussian; - gpuSensorFusionPipelineState = pipelines.GpuSensorFusion; + if (pipelines.TemporalGaussian is not null) + { + temporalGaussianPipelineState = pipelines.TemporalGaussian; + } + if (pipelines.GpuSensorFusion is not null) + { + gpuSensorFusionPipelineState = pipelines.GpuSensorFusion; + } fractalSurfaceSplatRenderPipelineState = pipelines.FractalSurfaceSplatRender; fractalTransparentSplatRenderPipelineState = pipelines.FractalTransparentSplatRender; fractalSplatPipelineState = pipelines.FractalSplat; fractalSdfReservoirPipelineState = pipelines.FractalSdfReservoir; fractalPbrReservoirPipelineState = pipelines.FractalPbrReservoir; fractalRadiosityReservoirPipelineState = pipelines.FractalRadiosityReservoir; - tubeFieldComputePipelineState = pipelines.TubeFieldCompute; - tubeFieldRenderPipelineState = pipelines.TubeFieldRender; + if (pipelines.TubeFieldCompute is not null) + { + tubeFieldComputePipelineState = pipelines.TubeFieldCompute; + } + if (pipelines.TubeFieldRender is not null) + { + tubeFieldRenderPipelineState = pipelines.TubeFieldRender; + } fieldReservoirResolvePipelineState = pipelines.FieldReservoirResolve; for (var index = 0; index < sdfProxyPipelineStates.Length; index++) { @@ -4376,10 +4615,36 @@ public sealed class D3D12Renderer : IAquariumRenderer private void DisposePipelineStates() { - CapturePipelineSetOrNull()?.Dispose(); + resolvePipelineState?.Dispose(); + reservoirHistoryUpdatePipelineState?.Dispose(); + bloomBlurVerticalPipelineState?.Dispose(); + bloomBlurHorizontalPipelineState?.Dispose(); + bloomDownsamplePipelineState?.Dispose(); + bloomPrefilterPipelineState?.Dispose(); + fieldReservoirResolvePipelineState?.Dispose(); + foreach (var sdfProxy in sdfProxyPipelineStates) + { + sdfProxy?.Dispose(); + } + tubeFieldRenderPipelineState?.Dispose(); + tubeFieldComputePipelineState?.Dispose(); + fractalRadiosityReservoirPipelineState?.Dispose(); + fractalPbrReservoirPipelineState?.Dispose(); + fractalSdfReservoirPipelineState?.Dispose(); + fractalSplatPipelineState?.Dispose(); + fractalTransparentSplatRenderPipelineState?.Dispose(); + fractalSurfaceSplatRenderPipelineState?.Dispose(); + gpuSensorFusionPipelineState?.Dispose(); + temporalGaussianPipelineState?.Dispose(); + splinePipelineState?.Dispose(); + scenePipelineState?.Dispose(); + heightFieldBrushPipelineState?.Dispose(); + heightFieldBasePipelineState?.Dispose(); + heightFieldBasePipelineState = null; heightFieldBrushPipelineState = null; scenePipelineState = null; + splinePipelineState = null; temporalGaussianPipelineState = null; gpuSensorFusionPipelineState = null; fractalSurfaceSplatRenderPipelineState = null; @@ -4390,6 +4655,7 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalRadiosityReservoirPipelineState = null; tubeFieldComputePipelineState = null; tubeFieldRenderPipelineState = null; + fieldReservoirResolvePipelineState = null; Array.Clear(sdfProxyPipelineStates); bloomPrefilterPipelineState = null; bloomDownsamplePipelineState = null; @@ -5419,16 +5685,16 @@ public sealed class D3D12Renderer : IAquariumRenderer ID3D12PipelineState HeightFieldBrush, ID3D12PipelineState Scene, ID3D12PipelineState Spline, - ID3D12PipelineState TemporalGaussian, - ID3D12PipelineState GpuSensorFusion, + ID3D12PipelineState? TemporalGaussian, + ID3D12PipelineState? GpuSensorFusion, ID3D12PipelineState FractalSurfaceSplatRender, ID3D12PipelineState FractalTransparentSplatRender, ID3D12PipelineState FractalSplat, ID3D12PipelineState FractalSdfReservoir, ID3D12PipelineState FractalPbrReservoir, ID3D12PipelineState FractalRadiosityReservoir, - ID3D12PipelineState TubeFieldCompute, - ID3D12PipelineState TubeFieldRender, + ID3D12PipelineState? TubeFieldCompute, + ID3D12PipelineState? TubeFieldRender, ID3D12PipelineState FieldReservoirResolve, IReadOnlyList SdfProxies, ID3D12PipelineState BloomPrefilter, @@ -5448,15 +5714,15 @@ public sealed class D3D12Renderer : IAquariumRenderer BloomPrefilter.Dispose(); FieldReservoirResolve.Dispose(); FractalRadiosityReservoir.Dispose(); - TubeFieldRender.Dispose(); - TubeFieldCompute.Dispose(); + TubeFieldRender?.Dispose(); + TubeFieldCompute?.Dispose(); FractalPbrReservoir.Dispose(); FractalSdfReservoir.Dispose(); FractalSplat.Dispose(); FractalTransparentSplatRender.Dispose(); FractalSurfaceSplatRender.Dispose(); - GpuSensorFusion.Dispose(); - TemporalGaussian.Dispose(); + GpuSensorFusion?.Dispose(); + TemporalGaussian?.Dispose(); Spline.Dispose(); foreach (var sdfProxy in SdfProxies) { diff --git a/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs b/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs index 950e974..185177c 100644 --- a/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs +++ b/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs @@ -1,6 +1,6 @@ +using System.Diagnostics; using System.Reflection; using System.Runtime.Loader; -using System.Diagnostics; namespace Aquarium.Engine.Runtime; @@ -8,17 +8,24 @@ public sealed class ClientRuntimeLoader : IDisposable { private readonly string? clientAssemblyPath; private readonly string? clientReloadPointerPath; + private readonly TimeSpan reloadPollInterval; private readonly Stopwatch reloadClock = Stopwatch.StartNew(); private readonly AquariumRuntimeOptions options; private ReloadedRuntime? current; private TimeSpan lastReloadCheck; private string? currentAssemblyPath; - public ClientRuntimeLoader(AquariumRuntimeOptions options, string? clientAssemblyPath = null, string? clientReloadPointerPath = null) + public ClientRuntimeLoader( + AquariumRuntimeOptions options, + string? clientAssemblyPath = null, + string? clientReloadPointerPath = null, + TimeSpan? reloadPollInterval = null) { - this.clientAssemblyPath = clientAssemblyPath; - this.clientReloadPointerPath = clientReloadPointerPath; + this.clientAssemblyPath = string.IsNullOrWhiteSpace(clientAssemblyPath) ? null : Path.GetFullPath(clientAssemblyPath); + this.clientReloadPointerPath = string.IsNullOrWhiteSpace(clientReloadPointerPath) ? null : clientReloadPointerPath; + this.reloadPollInterval = reloadPollInterval ?? TimeSpan.FromMilliseconds(500); this.options = options; + lastReloadCheck = -this.reloadPollInterval; } public IAquariumRuntime Runtime @@ -42,13 +49,24 @@ public sealed class ClientRuntimeLoader : IDisposable public void Reload(string assemblyPath, AquariumRuntimeOptions options) { + if (string.IsNullOrWhiteSpace(assemblyPath)) + { + throw new ArgumentException("Client runtime assembly path cannot be blank.", nameof(assemblyPath)); + } + + var fullPath = Path.GetFullPath(assemblyPath); + if (!IsExistingDll(fullPath)) + { + throw new FileNotFoundException($"Client runtime assembly must resolve to an existing .dll: {fullPath}", fullPath); + } + var previous = current; - var loadContext = new ClientAssemblyLoadContext(assemblyPath); + var loadContext = new ClientAssemblyLoadContext(fullPath); IAquariumRuntime? nextRuntime = null; try { - var assembly = loadContext.LoadFromAssemblyPath(assemblyPath); + var assembly = loadContext.LoadFromAssemblyPath(fullPath); var factoryTypes = assembly.GetTypes() .Where(type => typeof(IAquariumRuntimeFactory).IsAssignableFrom(type) && type is { IsAbstract: false, IsInterface: false }) @@ -74,7 +92,7 @@ public sealed class ClientRuntimeLoader : IDisposable } current = new ReloadedRuntime(loadContext, nextRuntime); - currentAssemblyPath = assemblyPath; + currentAssemblyPath = fullPath; previous?.Runtime.Dispose(); previous?.Unload(); } @@ -87,7 +105,7 @@ public sealed class ClientRuntimeLoader : IDisposable private void TryReloadFromPointer() { - if (string.IsNullOrWhiteSpace(clientReloadPointerPath) || reloadClock.Elapsed - lastReloadCheck < TimeSpan.FromMilliseconds(500)) + if (string.IsNullOrWhiteSpace(clientReloadPointerPath) || reloadClock.Elapsed - lastReloadCheck < reloadPollInterval) { return; } @@ -103,9 +121,22 @@ public sealed class ClientRuntimeLoader : IDisposable return; } - if (string.IsNullOrWhiteSpace(candidatePath) - || string.Equals(candidatePath, currentAssemblyPath, StringComparison.OrdinalIgnoreCase) - || !File.Exists(candidatePath)) + if (string.IsNullOrWhiteSpace(candidatePath)) + { + return; + } + + string fullPath; + try + { + fullPath = Path.GetFullPath(candidatePath); + } + catch + { + return; + } + + if (!IsExistingDll(fullPath) || string.Equals(fullPath, currentAssemblyPath, PathComparison)) { return; } @@ -113,8 +144,8 @@ public sealed class ClientRuntimeLoader : IDisposable try { current?.Runtime.FlushState(); - Reload(candidatePath, options); - Console.WriteLine($"Client runtime reload applied: {candidatePath}"); + Reload(fullPath, options); + Console.WriteLine($"Client runtime reload applied: {fullPath}"); } catch (Exception error) { @@ -122,6 +153,13 @@ public sealed class ClientRuntimeLoader : IDisposable } } + private static bool IsExistingDll(string path) => + string.Equals(Path.GetExtension(path), ".dll", StringComparison.OrdinalIgnoreCase) + && File.Exists(path); + + private static StringComparison PathComparison => + OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + private string RequireClientAssemblyPath() { if (!string.IsNullOrWhiteSpace(clientAssemblyPath)) diff --git a/src/Saga/README.md b/src/Saga/README.md deleted file mode 100644 index c10367e..0000000 --- a/src/Saga/README.md +++ /dev/null @@ -1,165 +0,0 @@ -# Saga - -**Planetary flow middleware for worlds that refuse to sit still.** - -Saga is Fensalir's stochastic planetary flow organ: a cube-sphere native system -for streaming atmosphere, ocean, gas, debris, heat, and other transport fields -across whole planets at arbitrary level of detail. - -It is built for studios that want living planets without hand-authoring a fake -weather loop, baking one heroic texture atlas, or stapling a particle system to -a skybox and calling it climate. Saga turns terrain, bathymetry, atmospheric -state, ocean reanalysis, arbitrary forcing sources, and learned stochastic -transport into compact flow packets the engine can stream, inspect, simulate, -and render. - -No poles. No flat-Earth texture tricks. No private renderer arrows pretending -to be physics. Just a planet-scale flow field with provenance, uncertainty, and -enough teeth to survive a camera dive from orbit to coastline. - -## The Pitch - -Modern games and simulation tools can render planets. They rarely make them -move like planets. - -Saga is the missing middleware layer between static world geometry and dynamic -planetary behavior: - -```text -planet domain + relief + state + forcing + learned transport --> stochastic advection packets --> streaming flow pages, particles, weather, debris, clouds, currents, debug -``` - -Use it for: - -- ocean surface currents and debris drift; -- atmospheric wind fields and gas-giant bands; -- volcanic, nuclear, magical, artificial, or stellar energy injection; -- multi-sun lighting and thermal forcing; -- tides, rotation, Coriolis-dominated flow, and exotic planetary regimes; -- gameplay-visible particles, clouds, smoke, spores, ash, foam, or pollutants; -- offline worldbuilding, cinematic previs, and realtime renderer guidance. - -Saga is not a weather forecast API wearing a costume. It is a reusable engine -organ for representing and streaming stochastic flow over Fensalir's planetary -domains. - -## What Makes It Different - -### Cube-Sphere Native - -Saga speaks Fensalir's optimized cube-sphere address space directly. Lat/lon -grids are source formats, not runtime truth. Every packet belongs to a tile, -LOD, projection, local tangent frame, and provenance chain. - -### Stochastic By Design - -Real flow is not one obedient arrow. Saga packets carry mean transport, -diffusivity/covariance, confidence, and optional transition kernels. Renderers -can draw clean vectors; simulations can keep the uncertainty instead of -throwing it into the sea and acting surprised later. - -### Arbitrary Forcing - -The evaluator is not Earth-locked. Saga conditions on explicit rotation and -Coriolis features plus variable-cardinality energy, mass, and momentum forcing -sources: - -- one sun, binary suns, or no sun worth trusting; -- moons and tidal drivers; -- eruptions, impacts, reactors, orbital mirrors, industrial heat, spellstorms; -- gas-giant internal heat and extreme atmosphere bands; -- transient shock events and persistent planetary gradients. - -Source count is data, not architecture. - -### Built For Streaming - -Saga is designed for camera-relative planet rendering: - -- coarse flow far from the camera; -- refined flow where the player, shot, simulation, or uncertainty demands it; -- parent/child LOD consistency; -- cross-face seam continuity; -- explicit stale-page and model-version checks. - -The renderer samples packets. It does not invent climate in a pixel shader -because the schedule got nervous. - -## Architecture - -Saga lives inside Fensalir because Fensalir already owns the machinery it needs: - -- `CubeTileKey` and cube-sphere projection math; -- field evidence layers, especially `Transport`; -- selected cuts and residency planning; -- GPU resource pages and debug telemetry; -- renderer/simulation lowering boundaries. - -Saga's live shape: - -```text -source manifests - -> cube-sphere dataset bakes - -> training shards - -> FlowNet-S / FlowNet-M / optional FlowNet-T - -> Saga stochastic advection packets - -> Fensalir Transport field claims - -> GPU pages, particle advection, weather visuals, debug probes -``` - -## Model Line - -Saga uses a staged neural architecture plan: - -- `FlowNet-S`: 8-15M parameters, local baseline for ingestion, calibration, and - export. -- `FlowNet-M`: 40-60M parameters, first serious runtime/distillation model with - local tile encoders, a cube-sphere graph processor, and stochastic heads. -- `FlowNet-T`: 150-300M parameters, optional global teacher for offline - distillation and ensemble behavior. - -The model emits stochastic advection parameters, not just velocity: - -- tangent mean velocity; -- positive-semidefinite 2x2 covariance/diffusivity; -- calibrated confidence; -- optional neighbor transition logits; -- provenance and model identity. - -## Data Spine - -Saga's first research targets: - -- ETOPO / GEBCO for relief and bathymetry; -- ERA5 for atmosphere; -- GLORYS / OSCAR / HYCOM candidates for ocean currents; -- PlasticAdrift and drifter transition matrices for stochastic debris - transport validation; -- synthetic analytic worlds for contract and seam tests before the ocean gets - expensive. - -Every source needs a manifest. No manifest, no training shard. The altar wants -receipts. - -## First Vertical Slice - -1. Define the Saga packet contracts. -2. Bake a synthetic cube-sphere flow world. -3. Export Transport field pages. -4. Render/debug vectors, covariance ellipses, confidence, and selected LOD. -5. Train FlowNet-S on synthetic + tiny ERA5 wind. -6. Add ocean surface current targets. -7. Add PlasticAdrift transition validation. -8. Promote FlowNet-M when the baseline has failed in useful, measured ways. - -## Boundary - -Saga owns reusable planetary flow mechanics. Clients own meaning. - -Fensalir clients may ask for currents, winds, debris drift, cloud motion, ash -transport, or gas-giant bands. They may not create a private flow authority that -bypasses Saga packets and Fensalir Transport claims. - -That is the deal: the planet can be wild, but the authority has to be clean. diff --git a/src/Saga/Saga.csproj b/src/Saga/Saga.csproj deleted file mode 100644 index 26dee97..0000000 --- a/src/Saga/Saga.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - net10.0 - enable - enable - - - diff --git a/src/Saga/SagaOrgan.cs b/src/Saga/SagaOrgan.cs deleted file mode 100644 index 89de3ea..0000000 --- a/src/Saga/SagaOrgan.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Aquarium.Engine.Fractal; -using System.Numerics; - -namespace Saga; - -public static class SagaOrgan -{ - public const string Name = "Saga"; - - public const string Description = - "Cube-sphere stochastic planetary flow for Fensalir Transport fields."; -} - -public readonly record struct SagaFlowDomain( - string DomainId, - double PlanetRadiusMeters, - string ProjectionId, - string GridVersion); - -public readonly record struct SagaFlowRequest( - SagaFlowDomain Domain, - CubeTileKey Tile, - int SampleResolution, - double TimeSeconds, - SagaCoriolisFrame Coriolis, - IReadOnlyList ForcingSources); - -public readonly record struct SagaCoriolisFrame( - Vector3 RotationAxis, - double AngularVelocityRadiansPerSecond, - double LocalF, - Vector2 LocalBeta); - -public readonly record struct SagaForcingSource( - string SourceId, - SagaForcingKind Kind, - SagaForcingGeometry Geometry, - Vector3 PlanetDirection, - Vector3 LocalTangentDirection, - double Intensity, - double RadiusMeters, - double Attenuation, - double TimePhase); - -public readonly record struct SagaAdvectionSample( - Vector2 MeanVelocity, - SagaCovariance2D Diffusivity, - double Confidence); - -public readonly record struct SagaCovariance2D(double C00, double C01, double C11); - -public enum SagaForcingKind -{ - Energy, - Mass, - Momentum, -} - -public enum SagaForcingGeometry -{ - Directional, - Point, - Area, - Volume, -} diff --git a/state/map.yaml b/state/map.yaml index 2258fa5..3a7327d 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -21,12 +21,6 @@ current_model: implementation: src/Aquarium.Engine.Fractal tests: tests/Aquarium.Engine.Fractal.Tests receipt_tool: tools/Aquarium.Fractal.Receipt - saga: - implementation: src/Saga - purpose: > - Stochastic planetary flow middleware for cube-sphere Transport fields, - arbitrary forcing, explicit Coriolis/rotation conditioning, and learned - atmosphere/ocean/debris advection packets. demos: fensalir_splash: src/Aquarium.Fensalir minimal: src/Aquarium.Sample.Minimal diff --git a/state/scratch-fractal-surface-visible.md b/state/scratch-fractal-surface-visible.md deleted file mode 100644 index 438d920..0000000 --- a/state/scratch-fractal-surface-visible.md +++ /dev/null @@ -1,18 +0,0 @@ -# Fractal Surface Visible Slice - -Objective: make the live Zyphos scene test authored fractal reservoir terrain instead of a decorative proxy. - -Kept: -- GPU-resident 2M splat reservoir field. -- Separate SDF, PBR, and radiosity reservoir layers. -- `.aquageo` selected-cut program lowering. - -Changed: -- Packed IFS transform rows now preserve cube-sphere tile face/level/x/y. -- Compute maps authored splats onto cube-sphere faces instead of a generic +Z cap. -- Visible splats render as tangent-frame surface patches, not camera-facing stickers. -- Zyphos camera targets the selected domain while keeping the parent as orbit anchor. - -Still not good enough: -- The live view is fast and the reservoir is populated, but the current surface-consumption pass still reads too abstractly under the noisy starfield. -- Next coherent cut is a real clustered surface resolve or ray-query style splat surface pass, not more billboard cosmetics. diff --git a/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj b/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj index 63d3d04..7937bdd 100644 --- a/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj +++ b/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj @@ -20,6 +20,7 @@ + diff --git a/tests/Aquarium.Engine.Tests/ClientRuntimeLoaderTests.cs b/tests/Aquarium.Engine.Tests/ClientRuntimeLoaderTests.cs new file mode 100644 index 0000000..e8ccc2c --- /dev/null +++ b/tests/Aquarium.Engine.Tests/ClientRuntimeLoaderTests.cs @@ -0,0 +1,173 @@ +using Aquarium.Engine; +using Aquarium.Engine.Input; +using Aquarium.Engine.Runtime; + +namespace Aquarium.Engine.Tests; + +public sealed class ClientRuntimeLoaderTests : IDisposable +{ + private static readonly AquariumRuntimeOptions Options = new(true, null); + private readonly string work = Directory.CreateDirectory( + Path.Combine(Path.GetTempPath(), "aquarium-loader-" + Guid.NewGuid().ToString("N"))).FullName; + + public void Dispose() + { + for (var attempt = 0; attempt < 5; attempt++) + { + try + { + if (Directory.Exists(work)) + { + Directory.Delete(work, recursive: true); + } + + return; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + Thread.Sleep(50); + } + } + } + + private string CopyValidRuntime(string directoryName, string fileName = "client.dll") + { + var directory = Directory.CreateDirectory(Path.Combine(work, directoryName)).FullName; + var path = Path.Combine(directory, fileName); + File.Copy(typeof(Aquarium.Sample.Minimal.MinimalRuntime).Assembly.Location, path); + return path; + } + + [Fact] + public void ValidDllLoadsAndExposesItsOwnLocation() + { + var first = CopyValidRuntime("slot1"); + using var loader = new ClientRuntimeLoader(Options, first); + + var runtime = loader.Load(); + + Assert.Equal(first, runtime.GetType().Assembly.Location); + } + + [Fact] + public void PointerReloadAppliesNewDllOnceAndLogsPlainPath() + { + var first = CopyValidRuntime("slot1"); + var second = CopyValidRuntime("slot2"); + var pointer = Path.Combine(work, "current.txt"); + using var loader = new ClientRuntimeLoader(Options, first, pointer, TimeSpan.Zero); + loader.Load(); + var initial = loader.Runtime; + + File.WriteAllText(pointer, second); + var stdout = CaptureOut(() => loader.Update(0.01f, new InputState())); + var reloaded = loader.Runtime; + + Assert.NotSame(initial, reloaded); + Assert.Equal(second, reloaded.GetType().Assembly.Location); + Assert.Contains($"Client runtime reload applied: {second}", stdout); + if (OperatingSystem.IsWindows()) + { + Assert.DoesNotContain(second.Replace("\\", "\\\\"), stdout); + } + + // Duplicate pointer update is ignored. + loader.Update(0.01f, new InputState()); + Assert.Same(reloaded, loader.Runtime); + } + + [Fact] + public void BlankMissingAndNonDllPointerTargetsAreIgnored() + { + var first = CopyValidRuntime("slot1"); + var pointer = Path.Combine(work, "current.txt"); + using var loader = new ClientRuntimeLoader(Options, first, pointer, TimeSpan.Zero); + loader.Load(); + var initial = loader.Runtime; + + // Missing pointer file + loader.Update(0.01f, new InputState()); + Assert.Same(initial, loader.Runtime); + + // Blank pointer file + File.WriteAllText(pointer, " \r\n"); + loader.Update(0.01f, new InputState()); + Assert.Same(initial, loader.Runtime); + + // Non-existent target + File.WriteAllText(pointer, Path.Combine(work, "missing", "client.dll")); + loader.Update(0.01f, new InputState()); + Assert.Same(initial, loader.Runtime); + + // Existing non-.dll file + var notADll = Path.Combine(work, "notes.txt"); + File.WriteAllText(notADll, "not a dll"); + File.WriteAllText(pointer, notADll); + loader.Update(0.01f, new InputState()); + Assert.Same(initial, loader.Runtime); + } + + [Fact] + public void BadDllInPointerKeepsPreviousRuntimeAlive() + { + var first = CopyValidRuntime("slot1"); + var badDll = Path.Combine(work, "bad.dll"); + File.WriteAllText(badDll, "not a valid assembly"); + var pointer = Path.Combine(work, "current.txt"); + using var loader = new ClientRuntimeLoader(Options, first, pointer, TimeSpan.Zero); + loader.Load(); + var initial = loader.Runtime; + + File.WriteAllText(pointer, badDll); + var stderr = CaptureError(() => loader.Update(0.01f, new InputState())); + + Assert.Same(initial, loader.Runtime); + Assert.Contains("Client runtime reload failed; keeping previous runtime.", stderr); + } + + [Fact] + public void MissingClientAssemblyOnHostStartupExitsNonZero() + { + var exitCode = 0; + var stderr = CaptureError(() => exitCode = AquariumHost.Run(["--headless"])); + + Assert.Equal(1, exitCode); + Assert.Contains("Client runtime failed to start", stderr); + } + + private static string CaptureOut(Action action) + { + var original = Console.Out; + using var captured = new StringWriter(); + Console.SetOut(captured); + try + { + action(); + } + finally + { + Console.SetOut(original); + } + + return captured.ToString(); + } + + private static string CaptureError(Action action) + { + var original = Console.Error; + using var captured = new StringWriter(); + Console.SetError(captured); + try + { + action(); + } + finally + { + Console.SetError(original); + } + + return captured.ToString(); + } +}