From d4322e1623f3c4598faf90103d0395e83e2ebd29 Mon Sep 17 00:00:00 2001 From: SPOOK_EXE <91944990+SPOOKEXE@users.noreply.github.com> Date: Tue, 22 Sep 2026 04:56:44 +0930 Subject: [PATCH 001/564] roadmap-edit --- ROADMAP.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 241ad9d44..416528c69 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,6 +95,8 @@ The milestone headings below are development labels. Not in line with project ve 7. Profile record bytes, allocations, readback latency, dropped records and GPU work in a release capture before adding another hook point. 8. Design separate typed observation hooks for physics and replication only after the render hook has two real consumers. Reuse the naming, bounded queue and polling rules, while keeping each subsystem's own tick, thread and lifetime contract. +- [_] LOD system billboard render support + ### v0.27 - [_] ```const char *CameraModeName(scene::CameraMode mode) { From 5220c65c52926675a3befb70071eb8a2c03a72a4 Mon Sep 17 00:00:00 2001 From: SPOOK_EXE <91944990+SPOOKEXE@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:08:46 +0930 Subject: [PATCH 002/564] roadmap-edit --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 416528c69..8f78e25f3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,6 +95,7 @@ The milestone headings below are development labels. Not in line with project ve 7. Profile record bytes, allocations, readback latency, dropped records and GPU work in a release capture before adding another hook point. 8. Design separate typed observation hooks for physics and replication only after the render hook has two real consumers. Reuse the naming, bounded queue and polling rules, while keeping each subsystem's own tick, thread and lifetime contract. +- [_] /docs/future-work/ui-system.md - [_] LOD system billboard render support ### v0.27 @@ -120,7 +121,6 @@ When you create a new world/scene, it auto appends the scripts in. - [_] expose automation tools (AutomationService) like mouse clicks and keyboard inputs to luau scripts (so we can create ai that plays for you) - [_] /docs/future-work/physics-expansion.md -- [_] /docs/future-work/ui-system.md - [_] /docs/future-work/world-streaming.md ### FUTURE From 5f5d59e4aa4e6ac5167b31b553242e0a3b831130 Mon Sep 17 00:00:00 2001 From: SPOOK_EXE <91944990+SPOOKEXE@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:15:17 +0930 Subject: [PATCH 003/564] roadmap-edit --- ROADMAP.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8f78e25f3..64fc0925d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -58,26 +58,27 @@ The milestone headings below are development labels. Not in line with project ve - [_] create two stress test demos: 100 unique 4k textures on material spheres with PBR (like the PBR demo), and 1 unique 4k texture on material spheres with PBR. tests instancing (for 1 duplicate item) and mem/compute usage for the uniques. - [_] add a "light path visualiser" that shows a visualisation of the spatial casting of light emitters so i can see what path they take, what they hit, etc. basically blue for empty space it travels, red for end of light, orange for pass-through or reflections. - [_] fix multi-select multi-property editing (when i select multiple objects, it should check all objects for the same component and value im editing and match them). - +- [_] add a override LOD distance per-item with default value being set to preference one. +- [_] separate the LOD component into LODAuto/LODCustom/LODSettings, LODCustom overlays LODAuto (so we can still have auto options but overriden by LODCustom options). +- [_] rename preferences LOD distance to "Default Mesh LOD distances". - [_] add typed, read-only physics observation hooks at declared fixed-tick boundaries. Use stable string discovery names, typed immutable per-hook contexts and bounded non-blocking records. Define whether each record observes pre-solve, completed-solver or post-integration state; retain exact tick, world, units and availability; and expose completed records to data-factory MCP without allowing a hook to mutate physics state. - [_] add typed, read-only replication observation hooks at declared exchange boundaries. Use stable string discovery names, typed immutable per-hook contexts and bounded non-blocking records. Preserve world, authority, client, baseline, tick and exchange-round identity; expose applied, rejected, repaired and dropped work without crossing a world boundary by pointer; and keep private payloads behind the existing permission boundary. - [_] optimise server startup time - [_] optimise and improve tests (particularly server and physics, can we add deterministic hooks so we can immediately wait for an update for a change instead of guessing with timestamps? test.solver, test.replication, etc) - - [_] add extensive (freecam) camera tests (like flying through portals) - [_] add extensive client character tests - [_] add extensive client character CAMERA tests (zooming out and projecting camera through portal) +- [_] fix camera detached in bladeborne aworld demo - [_] fix lights passing through portals not working -- [_] fix portals so they are seamless. really plan out how to make them seamless and how to handle "standing in the middle" so objects are visually there on both sides of the portal with no seam especially during movement (and how to make replication seamless too) - - [_] more lighting capabilities; god rays, blue, depth of field, fog fields (not global fog, more like "fog across area of ground") - [_] create a weather system demo using all the lighting capabilities (clouds, atmosphere, rain particles, etc). - [_] remake the tornado simulation demo using the C++ repository as a base. Check the existing documentation, add missing engine features that we need (ask user questions about it first, you'll need to swap into plan mode), then implement once you get the OK. - [_] pack multi-channel supporting render data in other channels, depth = r channel - ambient occulusion = g - anti-alias = b, for example. - [_] add a way to "virtually lock" the camera position, with a adornment visual, such that all camera behavior acts as if its from that location, this way i can test if culling works and other behaviors. - - [_] test studio and fix found bugs +- [_] fix portals so they are seamless. really plan out how to make them seamless and how to handle "standing in the middle" so objects are visually there on both sides of the portal with no seam especially during movement (and how to make replication seamless too) + ### v0.26 - [_] go through engine and consolidate and cleanup dead code branches. remove backport compatibilities with previous engine versions and ground this as the version. From f39f0167e67a8dcfa281b2e14d72a4dd96ed6322 Mon Sep 17 00:00:00 2001 From: SPOOK_EXE <91944990+SPOOKEXE@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:19:27 +0930 Subject: [PATCH 004/564] roadmap-edit --- ROADMAP.md | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 64fc0925d..76a023768 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -39,28 +39,33 @@ The milestone headings below are development labels. Not in line with project ve ### v0.25 -- [_] review over v0.24 and consolidate, improve, tweak, etc. -- [_] improve atomic-game-engine build file usage sizes. Takes over 120GB right now, needs to be reduced. Reduce hash for each mono repository to a reasonable size for each, cleanup old files, etc. +- [x] USER WORK: cleanup documents in `docs/`, maybe a `docs/systems` folder would be more suited for things like `RENDER-HOOKS.md`, `DEMOS.md`, `ECS_COMPONENTS.md`, `schema.toml` and `schema-data.toml`. + - [_] simplify down RUNNING.md, should be minimal, shows each available `just` job, how to build each, etc. Should not contain lots of descriptive information about how those systems work, just short descriptions and what they are aimed at to do. -- [_] USER WORK: cleanup documents in `docs/`, maybe a `docs/systems` folder would be more suited for things like `RENDER-HOOKS.md`, `DEMOS.md`, `ECS_COMPONENTS.md`, `schema.toml` and `schema-data.toml`. -- [_] Prune `PLAN-procedural-planets.md`, `PORTAL-HANDOFF.md`, `RENDER-POST-HOOK-REFACTOR.md`, `RENDER-REFACTOR-TASKS.md`, `RENDER-REFACTOR.md` and `TORNADOSIM.md`. -- [_] Prune old files in `docs/future-work/` as well. e.g. merge `FUTURE_COMPONENTS.md` components into relevent document files in `docs/future-work/`, then leave the remaining orphaned ones in `FUTURE_COMPONENTS.md`. - [_] improve `schema.toml` and `schema-data.toml` so its better laid out (schema is the general layout, schema-data is the actual useful information that we would grep and search specific classes, components and functions in). Like Roblox Studio Class API Reference. - [_] consolidate/improve `CONTRIBUTING.md`, `SECURITY.md`, `docs/THIRD_PARTY_NOTICES.md`, `CODE_ARCH.md`, `CODE_DOCUMENTING.md`, `CODE_FORMAT.md` and `CODE_QUALITY.md`, with small sentences at the start of the file describing what they contain in succinct detail. -- [_] cleanup documentation and layout -- [_] review and cleanup render pipeline (plan first) -- [_] plan a consolidation for the MCP-ADDITIONS.md systems. Super big, needs to ensure its properly implemented and looks good. Maybe even isolating code to a separate folder and then using hooks to ingest (and make those hooks hot loadable and unloadable so we can disable when we don't need to use them). -- [_] update and prune old content in documentation. check each statement, update, remove or replace. -- [_] create a "sky grid" of floating terrain balls with each one having one of 8 custom made shaders, then have the camera fly forward between the seams. this is a benchmark called BenchmarkSkyGrid.luau built-in demo example. We'll also use this as a performance profiler for editablemesh + terrain + etc. -- [_] add gpu resource constraining (freezes all other applications right now) +- [_] cleanup documentation doxy and layout +- [_] update and prune old content in documentation (doxy). check each statement, update, remove or replace. + - [_] check LOD is cleaned up when the mesh changes / is deleted / LOD properties are changed so they release and are recomputed -- [_] stress test all underlying engine systems (input, cdn, assets, parallel world, physics, hundreds of players + characters all moving around randomly, etc). for each, find at least 5 optimisations. -- [_] create two stress test demos: 100 unique 4k textures on material spheres with PBR (like the PBR demo), and 1 unique 4k texture on material spheres with PBR. tests instancing (for 1 duplicate item) and mem/compute usage for the uniques. -- [_] add a "light path visualiser" that shows a visualisation of the spatial casting of light emitters so i can see what path they take, what they hit, etc. basically blue for empty space it travels, red for end of light, orange for pass-through or reflections. - [_] fix multi-select multi-property editing (when i select multiple objects, it should check all objects for the same component and value im editing and match them). - [_] add a override LOD distance per-item with default value being set to preference one. - [_] separate the LOD component into LODAuto/LODCustom/LODSettings, LODCustom overlays LODAuto (so we can still have auto options but overriden by LODCustom options). - [_] rename preferences LOD distance to "Default Mesh LOD distances". +- [_] fix camera detached in bladeborne aworld demo + +- [_] add a "light path visualiser" that shows a visualisation of the spatial casting of light emitters so i can see what path they take, what they hit, etc. basically blue for empty space it travels, red for end of light, orange for pass-through or reflections. +- [_] create a "SkyGridPBR" demo of floating terrain balls with each one having one of 8 custom made shaders, then have the camera fly forward between the seams. this is a benchmark called BenchmarkSkyGrid.luau built-in demo example. We'll also use this as a performance profiler for editablemesh + terrain + etc. +- [_] create two stress test demos: 100 unique 4k textures on material spheres with PBR (like the PBR demo), and 1 unique 4k texture on material spheres with PBR. tests instancing (for 1 duplicate item) and mem/compute usage for the uniques. +- [_] add a way to "virtually lock" the camera position, with a adornment visual, such that all camera behavior acts as if its from that location, this way i can test if culling works and other behaviors. + +- [_] review over v0.24 and consolidate, improve, tweak, etc. +- [_] improve atomic-game-engine build file usage sizes. Takes over 120GB right now, needs to be reduced. Reduce hash for each mono repository to a reasonable size for each, cleanup old files, etc. +- [_] Prune `PLAN-procedural-planets.md`, `PORTAL-HANDOFF.md`, `RENDER-POST-HOOK-REFACTOR.md`, `RENDER-REFACTOR-TASKS.md`, `RENDER-REFACTOR.md` and `TORNADOSIM.md`. +- [_] Prune old files in `docs/future-work/` as well. e.g. merge `FUTURE_COMPONENTS.md` components into relevent document files in `docs/future-work/`, then leave the remaining orphaned ones in `FUTURE_COMPONENTS.md`. +- [_] review and cleanup render pipeline (plan first) +- [_] plan a consolidation for the MCP-ADDITIONS.md systems. Super big, needs to ensure its properly implemented and looks good. Maybe even isolating code to a separate folder and then using hooks to ingest (and make those hooks hot loadable and unloadable so we can disable when we don't need to use them). +- [_] stress test all underlying engine systems (input, cdn, assets, parallel world, physics, hundreds of players + characters all moving around randomly, etc). for each, find at least 5 optimisations. - [_] add typed, read-only physics observation hooks at declared fixed-tick boundaries. Use stable string discovery names, typed immutable per-hook contexts and bounded non-blocking records. Define whether each record observes pre-solve, completed-solver or post-integration state; retain exact tick, world, units and availability; and expose completed records to data-factory MCP without allowing a hook to mutate physics state. - [_] add typed, read-only replication observation hooks at declared exchange boundaries. Use stable string discovery names, typed immutable per-hook contexts and bounded non-blocking records. Preserve world, authority, client, baseline, tick and exchange-round identity; expose applied, rejected, repaired and dropped work without crossing a world boundary by pointer; and keep private payloads behind the existing permission boundary. - [_] optimise server startup time @@ -68,14 +73,11 @@ The milestone headings below are development labels. Not in line with project ve - [_] add extensive (freecam) camera tests (like flying through portals) - [_] add extensive client character tests - [_] add extensive client character CAMERA tests (zooming out and projecting camera through portal) -- [_] fix camera detached in bladeborne aworld demo - [_] fix lights passing through portals not working - [_] more lighting capabilities; god rays, blue, depth of field, fog fields (not global fog, more like "fog across area of ground") - [_] create a weather system demo using all the lighting capabilities (clouds, atmosphere, rain particles, etc). - [_] remake the tornado simulation demo using the C++ repository as a base. Check the existing documentation, add missing engine features that we need (ask user questions about it first, you'll need to swap into plan mode), then implement once you get the OK. - [_] pack multi-channel supporting render data in other channels, depth = r channel - ambient occulusion = g - anti-alias = b, for example. -- [_] add a way to "virtually lock" the camera position, with a adornment visual, such that all camera behavior acts as if its from that location, this way i can test if culling works and other behaviors. -- [_] test studio and fix found bugs - [_] fix portals so they are seamless. really plan out how to make them seamless and how to handle "standing in the middle" so objects are visually there on both sides of the portal with no seam especially during movement (and how to make replication seamless too) From b63f8cf00c8e67c29d4bd6415288ac3060b48944 Mon Sep 17 00:00:00 2001 From: SPOOK_EXE <91944990+SPOOKEXE@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:22:18 +0930 Subject: [PATCH 005/564] roadmap-edit --- ROADMAP.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 76a023768..8b6ec80bb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -53,14 +53,20 @@ The milestone headings below are development labels. Not in line with project ve - [_] separate the LOD component into LODAuto/LODCustom/LODSettings, LODCustom overlays LODAuto (so we can still have auto options but overriden by LODCustom options). - [_] rename preferences LOD distance to "Default Mesh LOD distances". - [_] fix camera detached in bladeborne aworld demo +- [_] fix lights passing through portals not working - [_] add a "light path visualiser" that shows a visualisation of the spatial casting of light emitters so i can see what path they take, what they hit, etc. basically blue for empty space it travels, red for end of light, orange for pass-through or reflections. - [_] create a "SkyGridPBR" demo of floating terrain balls with each one having one of 8 custom made shaders, then have the camera fly forward between the seams. this is a benchmark called BenchmarkSkyGrid.luau built-in demo example. We'll also use this as a performance profiler for editablemesh + terrain + etc. - [_] create two stress test demos: 100 unique 4k textures on material spheres with PBR (like the PBR demo), and 1 unique 4k texture on material spheres with PBR. tests instancing (for 1 duplicate item) and mem/compute usage for the uniques. - [_] add a way to "virtually lock" the camera position, with a adornment visual, such that all camera behavior acts as if its from that location, this way i can test if culling works and other behaviors. +- [_] add extensive (freecam) camera tests (like flying through portals) +- [_] add extensive client character tests +- [_] add extensive client character CAMERA tests (zooming out and projecting camera through portal) + +- [_] improve atomic-game-engine build file usage sizes. Takes over 100GB right now, needs to be reduced. Reduce hash for each mono repository to a reasonable size for each, cleanup old files, etc. Find what takes up all the space and try improve it. + - [_] review over v0.24 and consolidate, improve, tweak, etc. -- [_] improve atomic-game-engine build file usage sizes. Takes over 120GB right now, needs to be reduced. Reduce hash for each mono repository to a reasonable size for each, cleanup old files, etc. - [_] Prune `PLAN-procedural-planets.md`, `PORTAL-HANDOFF.md`, `RENDER-POST-HOOK-REFACTOR.md`, `RENDER-REFACTOR-TASKS.md`, `RENDER-REFACTOR.md` and `TORNADOSIM.md`. - [_] Prune old files in `docs/future-work/` as well. e.g. merge `FUTURE_COMPONENTS.md` components into relevent document files in `docs/future-work/`, then leave the remaining orphaned ones in `FUTURE_COMPONENTS.md`. - [_] review and cleanup render pipeline (plan first) @@ -70,10 +76,6 @@ The milestone headings below are development labels. Not in line with project ve - [_] add typed, read-only replication observation hooks at declared exchange boundaries. Use stable string discovery names, typed immutable per-hook contexts and bounded non-blocking records. Preserve world, authority, client, baseline, tick and exchange-round identity; expose applied, rejected, repaired and dropped work without crossing a world boundary by pointer; and keep private payloads behind the existing permission boundary. - [_] optimise server startup time - [_] optimise and improve tests (particularly server and physics, can we add deterministic hooks so we can immediately wait for an update for a change instead of guessing with timestamps? test.solver, test.replication, etc) -- [_] add extensive (freecam) camera tests (like flying through portals) -- [_] add extensive client character tests -- [_] add extensive client character CAMERA tests (zooming out and projecting camera through portal) -- [_] fix lights passing through portals not working - [_] more lighting capabilities; god rays, blue, depth of field, fog fields (not global fog, more like "fog across area of ground") - [_] create a weather system demo using all the lighting capabilities (clouds, atmosphere, rain particles, etc). - [_] remake the tornado simulation demo using the C++ repository as a base. Check the existing documentation, add missing engine features that we need (ask user questions about it first, you'll need to swap into plan mode), then implement once you get the OK. From aeb2e22468a4c6cf0b868fd649b58e90a4188a02 Mon Sep 17 00:00:00 2001 From: SPOOK_EXE <91944990+SPOOKEXE@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:37:25 +0930 Subject: [PATCH 006/564] Prune future-work plans and consolidate component notes --- docs/future-work/FUTURE_COMPONENTS.md | 331 +- docs/future-work/OPTIMISATIONS_PHYSICS.md | 633 +- docs/future-work/PLAN-procedural-planets.md | 1206 +-- docs/future-work/PORTAL-HANDOFF.md | 3108 -------- docs/future-work/RENDER-POST-HOOK-REFACTOR.md | 778 +- docs/future-work/RENDER-REFACTOR-TASKS.md | 555 -- docs/future-work/RENDER-REFACTOR.md | 3428 -------- docs/future-work/REVISIT_IDEAS.md | 6961 +---------------- docs/future-work/TORNADOSIM.md | 100 - docs/future-work/character-system.md | 16 + docs/future-work/physics-expansion.md | 5 + docs/future-work/procedural-generation.md | 8 +- docs/future-work/terrain-system.md | 5 + docs/future-work/vfx-system.md | 20 + .../examples/assets/scripts/TornadoSim.luau | 5 +- 15 files changed, 325 insertions(+), 16834 deletions(-) delete mode 100644 docs/future-work/PORTAL-HANDOFF.md delete mode 100644 docs/future-work/RENDER-REFACTOR-TASKS.md delete mode 100644 docs/future-work/RENDER-REFACTOR.md delete mode 100644 docs/future-work/TORNADOSIM.md diff --git a/docs/future-work/FUTURE_COMPONENTS.md b/docs/future-work/FUTURE_COMPONENTS.md index 095ea8f74..931efd563 100644 --- a/docs/future-work/FUTURE_COMPONENTS.md +++ b/docs/future-work/FUTURE_COMPONENTS.md @@ -1,286 +1,45 @@ -# The storage that ships before its feature - -**What this file is.** Ten component types landed at v0.19 that nothing in the -engine reads. This says why they are here, what each one gets wired to, and in -what order, so that v0.22 and v0.24 start from a decision instead of a blank -page. - -It is not a roadmap. `ROADMAP.md` decides what is in scope and when; -this decides what the storage those versions will need already looks like, and -records the arguments so they are not had twice. - -**The rule this sits under is decision 16**: *"a surface may ship complete and -frozen with its implementation deliberately unwired"*, revisited never, because -it is a state and not a stage. Root `AGENTS.md` says the same thing from the -other side: an unwired subsystem is not dead code. `just source-check`'s -`public-header` rule reports rather than gates for exactly this reason. - -**Why now rather than with the feature.** `ecs::Components::Seal()` is called by -the client and the server at start-up, so a component that first reaches -`Components::Of` after the seal aborts the process. A component declared and -left to register itself works in a unit test and takes down every host the first -time a game file carries one. That is the failure `scene.Sun`, -`scene.PortalProxy` and `physics.PoppercamState` were all found in at v0.19, and -declaring the storage up front is what makes the version that wires it a change -to behaviour rather than a change to the save format. - ---- - -## The ten, and where each is going - -| Component | Wired by | Reads it | Writes it | -|---|---|---|---| -| `scene.Skeleton` | v0.21 | the skinning palette build in `render` | an importer or author | -| `scene.Bone` | v0.21 | `scene::ResolveBones`, then the palette | the animation handler | -| `scene.AnimationClip` | v0.21 | the animation handler | an author, or a `.rbxl` import | -| `scene.Animator` | v0.21 | the animation handler | an author | -| `scene.AnimationTrack` | v0.21 | the animation handler | a script, through `Instance.new` | -| `scene.Constraint` | after v0.24 | a constraint solver in `physics` | an author | -| `scene.LevelOfDetail` | after v0.24 | `scene::SelectLevel`, from the draw-list build | the publisher, out of `bake` | -| `scene.Atmosphere` | v0.22 | a render-graph node, through `scene::WorldLighting` | an author | -| `scene.Clouds` | v0.22 | a render-graph node, through `scene::WorldLighting` | an author | -| `scene.Terrain` | FUTURE | a terrain generator node set | an author | - -Three of them already have a reader inside this module and are therefore not -fully unwired: `ResolveBones` fills every `Bone::WorldFrame`, `SelectLevel` is -the single statement of decision 19, and `LightingOf` resolves the atmosphere -and the cloud layer into `WorldLighting` beside the fog terms. Each has a suite. - ---- - -## The order, and why it is that order - -### 1. Skinning, completed at v0.21 - -`bake` preserves glTF `JOINTS_0` and `WEIGHTS_0`, the mesh format carries a -bounded skin-local palette size, and the renderer uploads resolved palettes -beside its resident instance rows. Imported bone-tree authoring remains a -separate model-import concern because the current bake graph exports one mesh -payload rather than a scene tree. - -**`scene::Skeleton` and `scene::Bone` are where the rig half lands.** The -per-vertex half is four joint indices and four quantised weights on -`assets::MeshVertex`; mesh format version two carries them without widening the -world-to-renderer instance payload. - -The order inside skinning is forced by what depends on what: - -1. `assets::MeshVertex` gains joint indices and weights; `Mesh::VERSION` is - bumped. Save-format break, which `docs/RELEASING.md` says is allowed - pre-release. -2. `bake` fills the per-vertex streams. A future scene-tree importer must emit - bones so that every `ParentJoint` is lower than its `Joint`; a glTF `joints` - array is not required to be sorted that way. -3. `render` builds a palette per rig from `SkinningFrameOf`, and skins in the - vertex shader. -4. The animation handler samples clips and writes `Bone::Transform`. - -Steps 1 to 3 give a rig standing in its bind pose, which is a visible, -testable result with no animation system in it at all. That ordering is the -point of the split. - -### 2. The animation handler, started at v0.21 - -The roadmap's line is "character controller + humanoid + character states + -state controller + bone controller, etc. More modular than roblox standard -humanoid", and the storage is shaped by that sentence rather than by Roblox's. - -**A track is an instance here and a userdata in Roblox.** Roblox's -`AnimationTrack` is opaque because Roblox's `Animator` is a black box; the -roadmap says in as many words that this engine's is not going to be one. A row -in the store saves, replicates, is readable from a script and shows up in a -debugger. The cost is that playing a clip is `Instance.new` rather than a method -call, which is the trade `Sound.Playing` already makes. - -The current handler covers the content-to-pose path: - -- **Sample a clip.** `.aanim` channels and keyframes live in `assets`, beside - `MeshData`. `AnimationClip::Asset` names one exactly as `Visual::Mesh` names a - mesh, and demand loading fetches only clips a world names. -- **Blend by priority and weight.** `AnimationTrack` carries both. Nothing about - the blend needs new storage. -- **Advance the play head.** `AnimationTrack::TimePosition` and fades advance on - the fixed simulation tick; presentation samples that stored position. -- **Root motion remains controller work.** `Animator::RootMotion` and - `RootMotionWeight` say what to do; applying sampled root deltas to a body stays - with the character-controller integration rather than the presentation pass. - -**`Humanoid` is not touched and must not be.** A component agent deleted -`Humanoid::Radius` at v0.19 for having two writers and no reader, and kept -`Height` and `Health` with reasons written beside them. Nothing here overlaps -it: an `Animator` may sit under a `Humanoid` and may equally sit over a door -hinge, which is the modularity the roadmap asks for, and requiring a humanoid to -reach an animator would be requiring a health bar to open a door. - -### 3. Atmosphere and clouds, at v0.22 - -**There is no `Fog` type and its absence is the decision.** -`docs/ARCH_REVIEW.md` D4 reads the tree as having no fog at all. It has: -`LightingServiceComponent::FogColor`, `FogStart` and `FogEnd` are authored on -the `Lighting` service, `LightingOf` resolves them into `WorldLighting`, and -`render::ViewRecording` puts them in a uniform. A `scene::Fog` component would -be a second answer to what a world's distance fade is, which is rule 2 and is -exactly what `Humanoid::Radius` was deleted for. - -What linear fog cannot express is scattering, which is why `Atmosphere` is a -separate type rather than more fields on the service: two distances and a colour -give a fade that is the same looking up as looking along the ground. Roblox -draws the same line, and lets an `Atmosphere` take over from the legacy fog -where one is present. - -**Both are per-world presentation state and neither reaches a simulation -input.** That is decision 20: *"render graphs may vary per platform. Anything -reaching a simulation input may not."* The test to apply to a field somebody -wants to add: if a body's trajectory would change, it does not belong here. -Nothing in `Atmosphere` or `Clouds` is read by physics, by a character -controller or by a query, and `just determinism` and `just replay-check` are -byte-identical with them registered. - -The wiring is a render-graph node that reads the `Air` and `Sky` members of -`scene::WorldLighting`, and the decision about which of the two fog models a given graph reads -is that graph's - which is what decision 20 permits and what carrying both makes -possible. - -**Dynamic ambient occlusion is in the same roadmap bullet and gets no component, -deliberately.** It is a property of a render pass rather than of a world: -strength, radius and sample count are node parameters, Roblox has no instance -for it, and a component would be a per-world number that a graph varying per -platform would have to override anyway. - -### 4. Level of detail, after v0.24 - -Decision 19 constrains this before anything is built: *"LOD selection targets -quad utilization. No virtualized geometry"*, revisited only when measurement on -this engine's own content contradicts it. So `scene::SelectLevel` compares -pixels of projected area per triangle and never a distance, and the component -stores that target rather than a distance ladder. - -The two disagree exactly where it costs. A hundred-metre tower and a coffee cup -at the same distance cover wildly different areas of the screen, so a distance -ladder either over-tessellates the cup or under-tessellates the tower - per -camera, per field of view, per resolution. Area per triangle is the same number -on a phone and on a workstation. - -What is left to wire: - -1. `bake` grows the two generated strategies. `Decimated` is edge collapse by - quadric error; `Reduced` orders collapses by how little surface area an edge - carries, which is the roadmap's "smart triangle reduction thinking of nanite - triangle surface area". Both fill `LevelOfDetail::Ratios` and publish the - coarse meshes under derived names. -2. The draw-list build calls `SelectLevel` and substitutes `LevelMesh`'s answer - for `Visual::Mesh`. - -**Which pass that is, is decided and it is not `client::CollectInstances`.** -That walk is `EachBatchParallel` over a fixed signature and cannot read an -optional column at all, which is why `SurfaceAppearance` and `Tags` are on every -part. Level selection is the opposite case: it runs over -`` and touches only the parts that have levels, which in -a world of four thousand plain cubes is none of them. Putting forty bytes on -every cube to save a join on the few hundred that are models is the trade -backwards. - -**The chosen level is not stored anywhere and must not become stored.** It is -derived, it changes per view, and a mirror looks at the same part from somewhere -else in the same frame. - -### 5. Constraints, after v0.24 - -`ROADMAP.md` has "constraints system" under FUTURE. `scene::Constraint` is one -generic six-degree-of-freedom joint rather than a struct per kind: two -attachments, six axes, and a motion mode per axis. Bullet calls the shape -`btGeneric6DofSpring2Constraint` and PhysX calls it a D6 joint. - -Roblox's family falls out of the modes rather than out of a `Kind` field, and -each class says which member of it by setting the modes as a **prototype -default** - which is `Light`'s three-classes-one-component trade at greater -width. A `Kind` field would make a `HingeConstraint` whose axes were all free -expressible, and the solver would have to decide which of the two statements it -believed. - -Seven classes are registered: `WeldConstraint`, `BallSocketConstraint`, -`HingeConstraint`, `PrismaticConstraint`, `CylindricalConstraint`, -`RopeConstraint` and `SpringConstraint`. `AlignPosition` and `AlignOrientation` -are the drive rather than classes of their own: an axis with a `Stiffness` is -pulled towards `Constraint::Target`, and an axis without one is clamped by its -limit. - -**`NoCollisionConstraint` is deliberately absent.** It is not a joint: it is a -broadphase filter, and `Collider::Layer` and `Collider::Mask` are already this -engine's answer to what may touch what. - -What is left to wire is entirely in `physics` at L8: - -1. `physics::PhysicsWorld` grows a joint array beside its contact manifolds, and - `SyncBroadphase`'s pass gathers `` into it the way it gathers - colliders. -2. The sequential-impulse solver gains a joint row per non-`Free` axis. A - `Locked` axis is a hard row, a `Limited` axis is a one-sided row at each - bound, and a driven axis is a soft row with `Stiffness`, `Damping` and the - force caps. -3. Warm starting keeps accumulated impulses **in `PhysicsWorld` and never on the - authored row**. That is the decision `RigidBody` already made once when it - refused a sleeping flag: solver state belongs where the solver's other - scratch is, and `PhysicsWorld` does not cross the wire for - `CollisionShapes`' reason. - -Nothing about the solver needs a change to `Constraint`. That is the test the -one-component design was chosen against. - -### 6. Terrain, FUTURE - -The roadmap asks for a "(procedural, node-based) terrain generator", so the -authored thing is a graph and a seed and **the chunks it produces are never -stored**. - -Two arguments, and the second is the stronger one: - -- A generated chunk is a derived fact stored beside its inputs, which is what - this module refuses everywhere - a world AABB off `Bounds`, a triangle count - off `Visual` - at a scale where getting it wrong costs gigabytes rather than - sixteen bytes. -- It is the only form that can cross a wire at all. `CollisionShapes` makes - exactly this argument for hulls: sending a conclusion instead of its input - hands an attacker the half they get to choose. Both ends run the same graph - over the same seed and get the same ground, which is decision 14's strict IEEE - arithmetic doing the work it exists to do. - -**A resource and not a component on a `Terrain` instance**, which is where -Roblox puts it. Roblox's `Terrain` derives from `BasePart` and is a singleton -under `Workspace` that `Instance.new` refuses to make a second of, and this -engine has no way to register a class that cannot be constructed. A resource is -one per world by construction, which is the property that mattered; -`WorldBounds` is the existing type with the same shape. - -What is left to wire: - -1. A terrain node set in `graph`, and the chunk store the generator owns - - exactly as the broadphase grids are `physics::PhysicsWorld`'s. -2. Residency driven by `Terrain::ViewDistance` around whatever holds an - `ActiveCamera`, plus a collider per resident chunk built through - `scene::CollisionShapes`, which already exists and already takes a triangle - soup. - ---- - -## Three things this work deliberately did not declare - -- **Per-vertex joints and weights**, for the reason under skinning above: they - are a mesh format change and belong with the importer that fills them. -- **A `Fog` component**, because the world already has fog and a second one - would be rule 2. -- **An ambient-occlusion component**, because it is a render-pass parameter and - decision 20 permits a graph to vary per platform. - -## Two script surfaces that are deliberately absent - -`Skeleton` and `LevelOfDetail` declare no property. Both are optional columns on -a `MeshPart`, so a property on that class would fail on every mesh part that is -not skinned and has no ladder - which is almost all of them - and a property -that usually fails is worse than one that does not exist. Both are written by -the publisher, which is C++. `AGENTS.md`'s "do not declare a property for -scripts alone" is the same rule read from the other end. - -`Bone::Joint` and `Bone::ParentJoint` are refused for a sharper reason: a script -renumbering a palette slot is a script that makes a vertex's joint index name a -slot nothing filled. +# Render work awaiting a dedicated plan + +The detailed plans for `scene::Skeleton`, `scene::Bone`, +`scene::AnimationClip`, `scene::Animator`, and `scene::AnimationTrack` live in +[the character plan](character-system.md). `scene::Constraint` lives in [the +physics plan](physics-expansion.md), and `scene::Terrain` lives in [the terrain +plan](terrain-system.md). Each destination records why the type registers before +`ecs::Components::Seal()` even while later runtime work remains unwired. + +The render work below remains here because it has no dedicated lower-case +future-work plan. + +## Mesh LOD + +LOD selection targets quad utilization. `scene::SelectLevel` compares pixels of +projected area per triangle and never a distance. A tower and a coffee cup at +the same distance cover different areas, so a distance ladder either overdraws +the cup or underserves the tower. The target remains per view, field of view, +and resolution. + +`render::AutomaticMeshLodUploader` builds and publishes `Decimated` and +`Reduced` ladders for `scene::LODAuto` rows. `scene::ResolveMeshLOD` combines +those artifacts with `scene::LODCustom` overrides into the derived +`LevelOfDetail` draw snapshot, and `SelectLevel` chooses its `LevelMesh` for a +view. + +The selected level is never stored. It varies between views, including mirrors +in the same frame. `LODAuto` and `LODCustom` own the authored ladder; the +resolved `LevelOfDetail` value exists only for draw selection. + +## `scene::Atmosphere` and `scene::Clouds` + +There is no `Fog` type. The Lighting service authors `FogColor`, `FogStart`, and +`FogEnd`; `LightingOf` resolves them into `WorldLighting`, and the view +recording sends them to the renderer. A separate fog component would create a +second answer to a world's distance fade. + +Atmosphere supplies scattering that linear fog cannot express. `Atmosphere` and +`Clouds` are per-world presentation state. They never reach physics, character +control, or queries, so render graphs may select their implementation per +platform without changing simulation. + +The render graph reads the `Air` and `Sky` members of `scene::WorldLighting`. +Dynamic ambient occlusion remains a render-pass parameter: strength, radius, +and sample count are graph settings, not world-authored component data. diff --git a/docs/future-work/OPTIMISATIONS_PHYSICS.md b/docs/future-work/OPTIMISATIONS_PHYSICS.md index 9b061c65c..a5a36dfe8 100644 --- a/docs/future-work/OPTIMISATIONS_PHYSICS.md +++ b/docs/future-work/OPTIMISATIONS_PHYSICS.md @@ -1,601 +1,78 @@ -# Physics and collision optimisations +# Physics and collision optimisation candidates ## Status -Research notes, not committed work. Each entry says whether we already have -it (`we have`), have part of it (`partial`), or do not (`candidate`). A -`candidate` becomes work only when a release-preset measurement names the -scene that pays for it. +This is a shortlist of work that remains after the current broadphase, +persistent contact data, speculative contacts, continuous sweeps, and +island-coloured solver paths landed. It is not a feature plan. See +[`physics-expansion.md`](physics-expansion.md) for product work. -Ideas are written whole and self-contained so any entry can be picked up -without reading anything else. +Each candidate needs a release-preset scene, a baseline, a bounded resource +cost, and a deterministic result before implementation. A plausible hot loop +is not evidence. ---- +## Candidates -## Broadphase +### Reuse narrowphase manifolds for settled pairs -### Fat AABB margins with incremental refit +The persistent pair and impulse data can avoid rebuilding a manifold only when +both transforms remain within an explicit position and rotation tolerance. The +cache must invalidate on shape and collision-layer changes. Measure a +sleep-heavy scene against the retained-byte cost and verify that contact events +remain unchanged. -Candidate. Our dynamic grid is rebuilt wholesale every tick, which is O(n) -even when almost nothing moved. +### Warm-start convex distance queries -Store each proxy twice: a tight world AABB recomputed from the transform -each tick, and a fat AABB written when the proxy was last inserted. On the -sync pass, if the tight box is still contained in the fat box, do nothing. -Only proxies whose motion escaped their fat box are re-inserted. Grow the -fat margin by a constant padding plus a term proportional to last tick's -velocity, so a slow crate rarely triggers work and a bullet always does. -Periodically shrink margins back toward tight so the structure does not -bloat permanently. +Cache a previous separating direction or simplex for hull-heavy pairs. Reject +it when its metric becomes degenerate or transform change invalidates it. This +is useful only if profiling attributes material time to convex support calls. -This needs an editable index (per-proxy slot with remove and insert), -which the current uniform grid deliberately refuses to be. Land it either -as a second structure beside the grid or as a replacement justified by a -release measurement. +### Cook a private mesh midphase -Tradeoffs: turns per-tick cost from O(n) into O(moved); fat boxes admit a -few percent extra candidate pairs near margins; an editable structure has -history-dependent iteration order, so the deterministic pair sort must -stay downstream of insertion order regardless. Pays off once the ratio of -static plus sleeping to awake bodies is high. Sleeping bodies are already -excluded from our rebuild by the archetype move, so measure against -awake-only populations before committing. +Immutable mesh colliders can carry a private deterministic triangle index +constructed at bake or load time. Compare it with the present path on a +triangle-dense scene, record retained bytes, and preserve stable triangle +feature identities for warm starts. -### Bounding-volume hierarchy with branch-and-bound insertion +### Split only measured oversized constraint islands -Candidate alternative to the grid, gated on the measurement the spatial -module already demands. +Independent islands and colour waves already provide the ordinary parallel +path. If a release scene exposes one large island as the limiting span, split +it into conflict-free batches and retain a serial straddler set. Keep the +batch order deterministic and prove that every conflicting row reaches the +serial set. -Build a balanced binary tree of AABBs over proxy bounds. Insertion walks -from the root choosing at each internal node the child whose union with -the new box adds least surface area, ties broken deterministically. The -high-quality version scores a candidate sibling by direct cost (area of -the new parent box) plus inherited cost (summed area increase of every -ancestor refitted on the way up), pruning subtrees whose lower-bound -inherited cost exceeds the best sibling found. After inserting, refit -ancestors back to the root, and at each ancestor consider tree rotations: -swap one child with a grandchild from the other side when doing so lowers -total surface area. Rotations are local operations that repair sorted-input -pathologies and animation drift without global rebalance. Track summed -internal-node surface area as the quality number in the benchmark. +### Add solver substeps only for a demonstrated stability failure -Tradeoffs: pointer-chasing walks beat the grid's flat array only when node -storage is pool-allocated contiguously; rotations must be bounded per tick -to keep worst-case time bounded and results deterministic. Grids win at -bounded scene densities, trees win when object size variance is extreme or -worlds become unbounded and streamed. Do not adopt without a scene that -exhibits the failure mode. +Substeps require contact anchors in local space and rescaled cached impulses +when the step length changes. They must improve a named stack, vehicle, or +fast-contact case at a bounded total solver cost. Do not make a global rate +change solely to add them. -### Lock-free broadphase modification with alternating roots +### Improve character grounding with a measured controller case -Candidate. Relevant only if queries ever contend with updates. +Evaluate a capsule controller and multi-ray support probe against the current +character path only when stairs, slopes, or moving supports fail a playable +demo. The controller keeps collision ownership in physics and publishes intent +through the existing character boundary. -Three cooperating mechanisms. First, a moving proxy never rewrites its -ancestors' boxes destructively: it widens them with atomic min/max -operations, so concurrent readers always see a correct-but-loose box, and -tightening happens later in a controlled pass. Second, structural changes -build a fresh subtree off to the side and swap the root pointer atomically; -two root slots alternate, and the discarded root survives until the next -update so queries still walking the old tree finish safely. Third, -modifications are batched: collect changed proxy ids during the tick, hand -them to a prepare job that runs concurrently with anything else, finalize -with a brief root swap. A per-node changed bit marks subtrees containing -movement so rebuilds touch only those paths. +### Consider wide traversal only after scalar traversal dominates -Tradeoffs: atomic min/max over six floats per node costs cache bandwidth; -loose intermediate boxes produce transient false positives, which narrow -phase absorbs anyway. Today our queries are reads over an immutable -between-ticks grid, so there is nothing to unlock yet. +Packed SIMD box tests and ray-order traversal are representation changes to a +tree that already has a deterministic scalar path. Adopt them only with a +query workload whose measured traversal cost repays the added layout and test +surface. -### Wide SIMD box tests and traversal child ordering +### Keep query/update concurrency out of scope until it exists -Candidate, aimed at tree traversal and mesh-triangle midphases rather than -the hash grid itself. +The current tick boundary owns updates and queries. Alternating roots and +atomic widening add complexity without a measured concurrent reader. Revisit +only when a real query path must overlap broadphase mutation. -Two pieces. Layout: store four child boxes of a node as six packed 4-float -vectors (all min-x together, all max-x together, and so on) so one slab -test covers four children with vector compares; a quadtree node then fits -exactly 128 bytes, two cache lines fully used. Traversal: evaluate children -front-to-back along the ray direction but push them onto the stack in -reverse order so the nearest child pops first, letting an early hit prune -the rest. Batch queries gain more than single ones: pack eight ray origins -and directions in structure-of-arrays form and intersect one node against -all eight lanes. +## Guardrails -Tradeoffs: the packed layout spreads a representation concern through -every place boxes are tested; scattered rays waste lanes. - ---- - -## Narrowphase - -### Persistent pair cache with manifold reuse - -Partial: the begin/end diff exists; manifold reuse is the candidate. - -Key a persistent map by the ordered body pair (pairs are already sorted by -entity id, so the key is free). Each entry stores last tick's manifold, -both colliders' world AABBs at the time it was made, and the touching -flag. Each tick, after broadphase emits candidates, merge-sort the new -pairs against cached ones (both sorted, linear merge). For a pair present -in both sets: if neither body's box moved more than a small epsilon and the -cached manifold's points still lie within tolerance of both surfaces, reuse -the manifold verbatim and mark the pair skipped; otherwise re-run narrow -phase. Pairs only in the old set are end events, only in the new set are -began events. Our existing `TouchingLast` / `TouchingNow` sorted lists -already implement the diff for events; the extension stores the manifold in -the cache and skips the pair function when the geometric precondition holds. - -Tradeoffs: skipped manifolds carry stale normals if bodies rotate in -place, so guard with a rotation-delta check or accept shallow error inside -the penetration slop. Invalidate explicitly on shape or layer edits. Saves -nearly everything for settled scenes, nothing for scenes where everything -moves every tick. - -### GJK warm starting with cached simplex and metric gate - -Candidate. Our general convex pair starts cold every call. - -Persist, per body pair, the last terminating simplex as vertex -correspondence pairs (index of the vertex used from each body; for implicit -primitives a canonical feature index such as sphere centre or rim point). -On the next call, re-evaluate support at the cached correspondences under -current transforms, rebuild the simplex from them, and compute a -degeneracy metric proportional to its length, area or volume. If the metric -collapsed or exploded versus its stored value (a factor-of-two band is -standard), discard the cache and start from a default direction; otherwise -the rebuilt simplex is usually optimal and termination confirms in one or -two support calls. Also cache the last separating direction and use it as -the initial search direction for separated pairs, which often proves -immediate separation on the first support call for slowly drifting bodies. -Normalize directions before support evaluation exactly as the current -implementation does. - -Tradeoffs: degenerate caches give wrong answers unchecked, hence the cheap -metric gate. Cache storage is a few dozen bytes per tracked pair and -belongs in the same sorted merged structure as the impulse cache. Gains -concentrate in hull-heavy scenes. - -### Four-point manifold reduction by maximized projected area - -Candidate alignment: we have a budget of four; this is the concrete -selection rule. - -Project every clipped contact point onto the plane through body one's -centre of mass perpendicular to the penetration axis. Pick point one -maximizing (projected distance from centre squared) times (penetration -depth squared), clamping both terms away from zero, preferring deep -contacts with long torque arms. Pick point two maximizing the same product -measured from point one, giving a line segment. Build the perpendicular of -that segment within the plane; pick point three minimizing and point four -maximizing signed dot against that perpendicular. The surviving tetrad -spans the patch in both planar directions weighted toward load-bearing -contacts. - -Cost is one pass plus three scans over at most eight points. Determinism -is exact because all comparisons are strict inequalities computed in fixed -order. Changing an existing reduction churns recorded replays, so pin the -new rule against the tower drift and sink benchmarks before swapping it in. - -### Contact persistence by proximity in body-local space - -Candidate companion to the pair cache; warm-start keys currently rely on -feature ids, which have no natural analogue on arbitrary hulls. - -When generating this tick's manifold for a cached pair, take last tick's -points transformed into each body's local frame. For each new point find -the nearest old point in local space; within a matching tolerance (a few -millimetres, scaled by contact size), inherit that old point's accumulated -impulse and identity. Unmatched new points start at zero; old points left -unmatched die. Both frames' transforms are known at match time, so no extra -storage is needed beyond last tick's local-space points, which the pair -cache already holds. - -Matching is O(old times new), trivially small at four by four. Tolerance -too large inherits impulses across genuinely different contacts (ghost -stickiness); too small loses warm starts constantly. Matters most once -hulls or compound shapes join the closed shape set. - -### Collision dispatch as a registered function table - -Pattern candidate. Current code selects pairs through explicit branching. - -Hold a two-dimensional table indexed by shape subtype on each axis, -initialized to a cell that asserts and reports nothing. Register exact -specialized implementations for one symmetric half of the matrix; register -a generic reversed wrapper on the other half that swaps arguments, calls -the specialized function, and swaps the result back (normal flip, point -side flip) so each pair function is written once. Register the general -GJK/EPA path as fallback wherever no specialization exists. Dispatch is one -indexed load per pair. Indirect call versus predictable branch is noise at -this granularity; the real value is auditability, because the table is the -coverage matrix and an unregistered cell is visible rather than implicit. -Adopt opportunistically if the shape set grows past the closed enum; do not -rewrite six working pairs for it alone. - -### Midphase acceleration for triangle meshes and heightfields - -Candidate. Mesh colliders currently answer by linear triangle scan. - -Keep the pure-geometry module exactly as it is (points in, shape out, -per-triangle bounds stored). Add the index in the physics layer, which -links spatial and owns the measurements: at collider build time construct -a private index over the mesh's triangle bounds. A coarse uniform grid in -mesh space suffices and never rebuilds since the mesh is immutable; a BVH -if triangle sizes vary hugely. Queries transform into mesh space, walk the -index to candidate triangles, and test exactly. Contacts report triangle id -as the feature, doubling as the warm-start key. Heightfields get the -cheaper variant: column lookup by horizontal coordinate yields the handful -of quads under the query footprint directly, no index structure at all. - -Index construction happens once at bake or load, memory proportional to -triangle count. Placement respects layer rules: geometry below, index -beside its consumer above. Pays off the moment any single mesh collider -exceeds a few thousand triangles or sits under many simultaneous queries. - ---- - -## Solver - -### Substepped solving with anchor tracking - -Candidate. The clock supports faster rates; the solver does not exploit it. - -Split the tick into n equal substeps and run one to two solver iterations -per substep instead of sixteen per tick, integrating velocities between -substeps. n small steps beat n iterations of one large step at equal total -work, with quadratic error reduction. What makes it affordable is not -re-running broad or narrow phase per substep: store each contact anchor in -both bodies' local frames at detection time, and at each substep reconstruct -world anchors, lever arms and separation by transforming the local anchors -out with current transforms. Separation updates reflect corrections earlier -substeps made, so the solver sees fresh constraints without fresh detection. - -Anchor reconstruction is approximate under large rotation between substeps -and excellent under the small motions substepping exists for. Friction -benefits especially: friction anchors persist across the whole tick and -resist tangential drift far better than per-tick re-derivation. Cost -profile shifts toward per-substep overhead, so substeps want cheap -iterations. Fits cleanly: the clock already decouples solver rate from -world tick, and substep count is a configured property like any rate, so -recorded-run replay is unaffected. - -### Warm-start impulse rescaling on step-length change - -Small candidate, essentially free. - -Cached impulses carry units of impulse, so when effective step length -changes (rate reconfiguration, adoption of substepping) last tick's -impulses are wrong by the ratio of lengths, and the first tick after the -change over- or under-corrects visibly. Track previous step length beside -the impulse cache; on the first step after a change scale every -warm-started normal and tangent impulse by (new length / old length) before -applying. The ratio should live next to the cache it governs. - -### Island building by union-find over active bodies - -Candidate complement or replacement for chunk-coloured grouping. - -During constraint setup link bodies: for each contact and joint, union the -two movable bodies' sets with path-compressed union-find over indices into -the gathered-body array (deterministic because the array is sorted by -entity). Unlinked bodies are singleton islands. Finalize by walking active -bodies in index order appending each to its island's list and recording -each contact under its root's island; islands emerge as contiguous runs -with end offsets. Sort island indices by descending constraint count so -the biggest island starts first. Solve islands independently and in -parallel, serially within each, preserving sequential impulse semantics -exactly because an island is the dependency closure. Sleep an island when -every member is below thresholds; wake floods instantly because membership -is explicit. - -Union-find over the gathered set is microseconds. Islands smaller than -chunks parallelize better (no border rows) and enable true island sleeping. -Worst case is one giant island, which no partition fixes; see splitting -below. Island visit order must remain a function of contents, which -index-ordered union-find guarantees. The chunk scheme is measured and -mutation-tested, so replacing it needs the same evidence trail. - -### Splitting oversized islands into parallel batches - -Candidate, the Amdahl term for island parallelism. - -One island containing thousands of constraints serializes the machine -under plain island parallelism. Threshold on island size (order of a couple -hundred items). For oversized islands assign contacts to up to thirty-two -splits greedily: process contacts in order, placing each into the lowest -indexed split where neither of its bodies has been claimed; a body claimed -by another split makes the contact a straddler, and straddlers land in a -reserved non-parallel split solved after all others. Each split carries an -atomic status word encoding iteration, split index and next item cursor so -workers fetch batches lock-free and mark completion by counted increments. -Iterations proceed barrier-style: every split completes round k before any -begins round k+1, news crossing splits once per round through straddlers. - -Straddler fraction is a surface-area effect: larger splits mean fewer -straddlers and less parallelism, tune toward target count per worker. -Correctness rests on the non-parallel split absorbing every conflict, -which is assertable directly. - ---- - -## Continuous collision - -### Speculative contacts with corrected restitution - -Candidate, explicitly listed absent today. - -Generate contacts for pairs separated by less than a speculative distance, -roughly the distance the pair can close in one tick taken from relative -velocity magnitude. Such a row carries negative penetration (separation -s > 0). Its bias becomes s divided by step length, so the constraint reads -"relative closing speed along the normal may not exceed s/dt": bodies stop -exactly at the surface instead of inside it. Restitution needs care: if -predicted impact speed exceeds the bounce threshold apply restitution now, -accepting one frame of bouncing from slightly-inside position, and -compensate the gravity applied earlier in the step by subtracting the -gravity-induced normal component from rebound speed; otherwise fall back -to the pure stopping bias. Ghost collisions are the known failure mode: a -grazing pair picks up an inclined normal from a distant corner and slides -up an invisible ramp. Mitigate with a tight speculative distance and -face-derived normals. - -Marginal cost per pair is near zero: same narrow phase, wider acceptance -radius, one different bias formula, acting at velocity level so it composes -with the correction-velocity design. Rows inflate for pairs that never -touch, so pair this with per-body flags letting only flagged bodies widen -acceptance. - -### Time-of-impact casting with fraction-ordered resolution - -Candidate extension of the existing fast-body sweep. - -Flag eligible bodies (speed high relative to own thickness) with a motion -quality bit. For each, compute time-of-impact fraction against candidates: -advance conservatively using the distance between convex shapes (already -implemented) to bound how far either can safely rotate or translate, -iterating until the fraction converges or falls back to discrete. Collect -all impacted fractions for the step, sort ascending with body-id tiebreak, -process earliest first: at each impact apply the response, then shorten -remaining travel of any other flagged body sharing an involved body so -later impacts involving deflected bodies re-evaluate. Order is total, so -deterministic. - -Conservative advancement iterates many times near-touching; cap iterations -and fall back. This is the most expensive collision path, hence eligibility -flags. Glancing rotational misses are accepted everywhere in practice. - ---- - -## Character controllers - -### Full kinematic capsule controller - -Candidate. Grounding is one ray today; walls are handled by clipping -commanded velocity. This is the largest single gap and decomposes into -shippable slices: slide-with-skin first, snap-down second, autostep third, -platforms last. - -Model the character as an upright capsule queried but not simulated. -Movement per tick: cast the capsule along desired displacement; on hit stop -at skin distance (a small margin kept to surfaces so casts never start -penetrating), project remaining motion onto the hit plane, repeat up to a -bounded iteration count. Autostep: only when grounded before the move, on -a wall hit whose contact point sits below knee height, cast up by step -height, forward by minimum ledge width, down by step height plus skin; -commit the up-and-over teleport only if the down cast lands within slope -limits and headroom existed throughout. Snap down: after a successful -grounded move, cast down a short snap distance and pull to the floor if -found, keeping contact downhill and over stair lips without triggering -airborne state. Platform carrying: sample the supporting body's velocity at -the contact point (linear plus angular cross lever), add it to desired -displacement, and express the character's own motion relative to the -platform so standing still rides along. Slope limit comes from ground -normal dotted against up; steep slopes cancel their downhill component -from input. - -Several casts per character per tick, bounded by iteration caps and by -characters being few relative to crates. Every cast excludes the -character's own colliders via the layer-mask route already in place. Skin -prevents stuck-on-seams. - -### Multi-ray ground probe with relative-velocity damped support - -Candidate soft-stance alternative where rigid capsule feel is wrong. - -Cast five short downward rays per character: centre plus four inset corner -rays of the footprint rectangle in the facing frame. Accept a ray as -support only if the hit normal satisfies slope limit; choose nearest valid -hit. Damp vertical error toward hip height with a mass-scaled PD force: -stiffness from tuned frequency, damping measured against relative vertical -velocity (character minus support-point velocity), clamped to maximum force -and unilateral (zero force means gravity takes over). Relative-velocity -damping is what makes moving platforms ride smoothly: damping toward -absolute velocity injects platform motion back as oscillation, damping -toward relative velocity does not. - -Five queries versus one is negligible at character counts. Spring -parameters belong in a tuning table, not constants. Corner rays double as -ledge-detection signal for grab mechanics. - ---- - -## Chunked world interplay - -The full chunk-border and streaming treatment lives in the render doc's -chunk section where it overlaps; the physics-specific pieces follow. - -### Interior/border solver split with longest-first dispatch - -We have, in the solve partition; the pattern generalizes to any per-chunk -phase. - -Contacts spanning two chunks cannot run beside anything touching those -chunks. Classify each manifold: same-chunk goes to that chunk's group, -movable-versus-immovable goes to the movable body's chunk because immovable -bodies are read-only during the sweep, and movable-in-two-chunks goes to a -dedicated border slot placed last. Run all interior groups in one fork-join -dispatch, then the border group alone afterward. Dispatch interior groups -sorted longest-row-count-first so the critical-path pile starts while -workers are free; break ties by first-row index so ordering is a pure -function of contents. Reordering disjoint groups changes no arithmetic -because no two groups write one body; order within a group is untouched -and is the part that matters. - -A dispatch costs roughly one microsecond per woken worker plus tens of -nanoseconds per range, so a scene whose border fraction exceeds about half -the work may run faster unpartitioned. Measure in release and keep the -number beside the constant. - -### Ghost/halo borders for chunk-local simulation - -Candidate. - -A cell update whose stencil reaches past the chunk edge reads neighbor -data; reading directly couples chunk storage layouts and breaks the -copy-per-boundary rule, skipping corrupts borders. Allocate each chunk's -cell array with a halo of width r (stencil radius) on every side stored as -read-only copies. Each tick phase one: every chunk copies its r-wide border -shells into messages addressed to neighbors, landing in receivers' halos. -Phase two: simulate interior-plus-owned cells using halo values, never -writing halo cells. Invariants that make schedule irrelevant: each owned -cell updates exactly once per step, copied border values refresh between -uses, no thread updates a cell it holds only as ghost. Halos arrive as -messages carrying copies, keeping thread-per-world and process-per-world -interchangeable. - -Halo memory is O(6rN^2) per N-cube. A deeper halo than correctness -requires allows exchanging every n steps instead of every step, trading -n-fold halo refresh for fewer synchronization points; worthwhile across -processes or when wake latency dominates. Halo contents are pure functions -of neighbor state at exchange, so determinism holds. - -### Corner cells folded into axis waves - -Candidate. - -Corner cells touch up to eight neighbors in 2D (26 in 3D); exchanging with -every diagonal multiplies messages and races on corner ownership. Exchange -in waves along axes. Wave one: horizontal exchanges send border strips -padded to include adjacent corner blocks. Wave two: vertical exchanges send -strips wide enough to carry corners received in wave one. Two waves fill -every diagonal ghost having travelled at most two hops, cutting 8 exchanges -to 4 in 2D and 26 to 6 in 3D. Corners are smaller than main blocks, so the -extra payload is noise while saved latency is not. - -Waves are sequential (a mini barrier between them), suiting our existing -phase-barrier shape. In-process, reading neighbor arrays directly during -simulation is faster but welds chunks into one address space and quietly -ends process-per-world. Prefer copies. - -### Canonical border ownership resolves disagreements - -Candidate. - -Two chunks computing something about a shared face (contact, merged quad, -flux, AO term) can disagree, double-simulate, or produce completion-order -dependent results. Define one total order on directed edges, lexicographic -chunk coordinate pair matching existing chunk ordering. The face belongs to -whichever chunk sorts first; the other treats it exterior. Any consumer of -the shared quantity asks the owner. Where both sides genuinely compute -(meshing wants both faces visible), each computes only its own outward side -so union covers the interface exactly once. Values that must agree derive -from world coordinates at the shared lattice position, never independently -accumulated local floats, so derivations return bit-identical results. - -Ownership query is one comparison; cache the winner per face pair in a -small table invalidated on repartition. Removes the last schedule -dependence from shared-face outcomes. - -### Chunk-local collision caches with owned border seams - -Candidate. - -Broadphase over every terrain triangle each tick is prohibitive, yet pairs -straddling chunk borders must not vanish or duplicate when chunks stream. -Per resident chunk publish one immutable collision artifact keyed by chunk -content signature: simplified heightfield or box soup chosen per chunk by -measured contact density. Flat terrain wants heightfield raycast-and-clamp; -built-up voxels want boxes. Physics consumes published artifacts without -knowing generation; a changed signature swaps the artifact in one atomic -publish at the barrier. Border queries consult owning artifact plus -neighbor's, resolved by canonical ownership so each candidate appears -exactly once. Keep the uniform HashGrid as the moving-body index and treat -chunk artifacts as static geometry behind per-chunk indirection refreshed -only on signature change; the standing refusal of per-chunk trees stays -until release measurement says otherwise. - -Dual representation doubles the query surface, gate behind one interface -and test both against reference cases. Heightfields misrepresent -overhangs; detect and escalate those chunks to soup during generation. -Collision hides LOD seams by always testing the higher-detail side of a -boundary. Artifact identity is content-derived so replay regenerates -identical collision inputs regardless of load timing. - ---- - -## Determinism discipline - -Mostly we have. Three refinements are candidates. - -Already enforced: no unordered-container iteration, no wall clock, no -address-derived keys, no thread-id dependence, total orders on pairs and -resting lists, fixed iteration counts chosen by scene properties, worker -output compacted deterministically through per-slot flags, input-order -quickhull. - -Refinements: - -- Floating-point contraction: compilers fuse multiply-add differently by - optimization level and target ISA, so identical source produces different - bits across builds. If cross-build replay ever matters, compile solver - and integrator translation units with contraction disabled explicitly and - record compiler flags in the recording header. -- Cross-platform honesty: transcendental functions differ by library. Keep - quaternion normalization and integration trig to IEEE-specified bit-exact - operations (add, multiply, divide, sqrt) wherever cross-platform promise - is contemplated, isolating unavoidable library calls behind one swappable - function. -- Quantization at boundaries: floats crossing processes in messages should - serialize bit-preservingly, never through text. - -Disabling contraction costs solver throughput; measure, apply per-file if -it bites. - ---- - -## Memory and layout - -Patterns worth extracting: - -- Fixed-size free lists for per-tick variable-population structures (tree - nodes, islands, contact rows): allocate blocks sized to historical - high-water marks, recycle indices, never return memory to the OS during - play. Extends the cleared-never-freed rule to element lifetimes shorter - than a tick. Introduce only where per-element recycling within a tick is - real (candidates: contact rows and manifold slots). -- Per-step temp allocator: one bump allocator owned by the step, freed - wholesale at step end, used for scratch lists. Allocation cost becomes a - pointer increment and no leak survives a step. -- Hot-field clustering: solver body layout at sixty-four byte alignment - with sweep-touched fields first is established; apply the same treatment - to new hot structures. -- Index-based handles everywhere: proxies, records and solver entries - reference each other by dense index rather than pointer. Preserve as a - review invariant whenever a new buffer appears. - ---- - -## Priority ranking - -1. Substepped solving and speculative contacts address the largest - behavioural-cost items: stack convergence and tunneling, both standing - on foundations the clock and distance function already provide. -2. Island building and oversized-island splitting convert the measured - border-row tail into parallel work and deliver instant wake propagation. -3. Kinematic capsule controller is the largest gameplay gap, decomposable - into slices. -4. Persistent pair and manifold caching plus GJK warm starting cut - steady-state cost in settled scenes and share one cache structure. -5. Fat-AABB incremental broadphase and mesh midphase indexing pay off at - scale thresholds our benchmarks can name precisely when crossed. +- Preserve deterministic pair and constraint order after every acceleration. +- Account for live and retained bytes beside timing improvements. +- Keep broadphase structures private to physics or spatial ownership. +- Do not replace a working path without a release-preset comparison and a + scenario that benefits. diff --git a/docs/future-work/PLAN-procedural-planets.md b/docs/future-work/PLAN-procedural-planets.md index 9612c3c2b..67d23189f 100644 --- a/docs/future-work/PLAN-procedural-planets.md +++ b/docs/future-work/PLAN-procedural-planets.md @@ -1,599 +1,24 @@ -# Procedural Planets: implementation plan +# Procedural planets: retained contracts -Feature set derived from the Sebastian Lague *Procedural Planet Generation* series -(E01 to E07, transcripts in `transcripts/`), re-targeted onto the Atomic Game Engine -at `~/Documents/GitHub/atomic-game-engine` (v0.22.0). +## Status -## Status and positioning +[`FULL-PLANET-DEMO.md`](FULL-PLANET-DEMO.md) owns the product slice, +[`terrain-system.md`](terrain-system.md) owns terrain progression, and +[`procedural-generation.md`](procedural-generation.md) owns generation requests, +identity, scheduling, and publication. This file retains planet-specific +contracts those plans do not spell out. It is not a second planet roadmap. -`ROADMAP.md` already carries this work as **v0.23.1: "quadsphere, quadtree planet"**, -listed beside the new-demo block. v0.26 wants it again at product scale ("space -engineers asteroids + planets full demo"), and the FUTURE band names the -"(procedural, node-based) terrain generator" that this eventually feeds. +## Deterministic cube-sphere contract -Two documents govern anything built here and this plan defers to both: - -- `docs/future-work/procedural-generation.md`, which owns request identity, seeds, - scheduling, cache keys and publication envelopes across every generating domain. -- `docs/future-work/terrain-system.md`, which proposes a `mono.engine/terrain` - module at **L8, shared** and owns field, meshing and chunk semantics. - -A planet is a terrain domain with a different topology, not a competing system. -`AGENTS.md` calls two ways to do one job the most expensive debt in the monorepo, -so this plan lands the quadsphere *inside* that lineage rather than beside it. - -This is a proposed build plan, not a claim that the listed planet APIs exist. -Local source review on 2026-09-07 checked the two governing plans and the -editable-mesh preparation and commit path. The source episode transcripts are -not beside this document; episode tags retain the earlier draft's attribution. -Other engine facts below must be checked against the checkout before building. - -The detailed contracts below refine the layer inventory. Proposed constants are -starting limits to measure, not existing engine limits or benchmark results. - -## House rules this document obeys - -- **No em-dashes.** `just em-dash-check` runs inside `just check`. -- **No AI co-author credits or generated footers**, per `CLAUDE.md`. -- A new module is an architectural change: it needs a row in - `mono.tools/architecture/expected_graph.json` with a `layer` and a `tier`, and it - must pass `just test-architecture` and configure-time tier enforcement. -- Every module carries `AGENTS.md`, `docs/` and `tests/`. Read the module's - `AGENTS.md` before touching it. -- One test file per public header, in that module's own `tests/`. A header needing - a GPU gets no unit suite and is checked by running the client. -- Benchmarks get a `just` job and never write to file. -- `just check` is the gate. `/run-checklist` before a pull request. - -## Reading order - -Layers below are the engine's real heights from `docs/CODE_ARCH.md` §4.1, bottom -up. Inside every layer, **Fundamentals** land before **Additions**. Creative work -is quarantined in the last section so the core pipeline is finished and provable -first. `(E0n)` traces a feature to its source episode; untagged items are -engine-port work with no video equivalent. - ---- - -## What the engine already provides - -The single largest change from the first draft of this plan: most of the -infrastructure exists, and the work is mostly composition rather than invention. - -| Video concept | Engine machinery that already exists | Where | -|---|---|---| -| `Mesh.vertices/triangles` assignment | `scene::EditableMeshGeometry`, `PrepareEditableMesh`, `CommitEditableMesh` | `scene` L7 | -| `mesh.Clear()` before reassign | `ReplaceEditableMesh`, revision-checked, no-op on identical content | `scene` L7 | -| Six `MeshFilter` children | `MeshPart` + `EditableMeshContentName` assigned to `MeshId` | `scene` L7 | -| Gradient asset | `core::ColorSequence::Evaluate`, `constexpr` | `core` L1 | -| Gradient baked to `Texture2D` | `scene::EditableImage`, row-major RGBA8, revision-tracked | `scene` L7 | -| Simplex noise script | a 3D Perlin already exists, `math.noise` compatible | `script` L9, private | -| Threaded generation | `script::EditableMeshJobs`, fork-joined, ticket-ordered commit | `script` L9 | -| Async noise grids | `script::ComputeJobs::SubmitNoise` | `script` L9 | -| Shader Graph PBR shader | `ShaderScript` holding GLSL, named by `Material.Shader` | `scene` L7 + `render` L12 | -| Settings as a shared asset | `scene::Terrain`, a recipe resource of seed plus generator name | `scene` L7 | -| Deterministic seeding | `core::Random`, indexed and pure, safe from `EachParallel` | `core` L1 | -| Change detection | `ecs::DirtyBits`, one bit per component column | `ecs` L3 | - ---- - -## Corrections the engine forces on the Unity design - -These are not preferences. Each one is a place where copying the video produces -something that compiles and is wrong. - -- **Winding flips.** `render/AGENTS.md` pins `CULLMODE_BACK` with - `FRONTFACE_COUNTER_CLOCKWISE`, so triangles are counter-clockwise seen from - outside. The video's clockwise order draws the planet inside out, and the symptom - is faces appearing and vanishing as it turns rather than anything that reads as a - winding bug. *(inverts E01)* -- **There is no uniform bag, so `_elevationMinMax` has no home.** - `scene::SurfaceAppearance` carries named maps and a shader name, not arbitrary - material parameters. Encode signed elevation around a fixed sea-level threshold - on the CPU while writing UVs. No elevation uniform is needed, deleting the `MinMax` to - `SetVector` path. *(replaces E05)* -- **`ShaderScript` is fragment-stage only**, because a vertex shader would have to - agree with the renderer's private instance layout. Every per-vertex quantity the - shader needs must ride a channel the built-in vertex stage already forwards, which - makes the video's "store it in the UV" trick mandatory rather than clever. - *(hardens E06, E07)* -- **`ecs::DirtyBits` is one bit per component column, marked automatically by - `GetMutable`.** Do not invent a bespoke bitfield of named stages. Split the - settings into separate components and the per-component bit gives the shape-versus-colour - invalidation split for free. *(supersedes the first draft's Layer A design; still - delivers E02's split)* -- **`EachBatch` and `EachBatchParallel` set no dirty bit**, by design. A consumer - needing row granularity over batch-written data folds a content signature, which - is exactly what `EditableMesh::Signature` is. -- **Vertex colours will not substitute for the LUT.** `render::BuildMeshData` - averages each triangle's three corners, so per-vertex colour is effectively - per-triangle. The gradient texture is the correct path, not an optional one. -- **`scene::LevelOfDetail` is a four-level discrete mesh ladder** selected by - `TargetQuadArea`, and decision 19 rules out virtualized geometry. A quadsphere - quadtree owns its own chunk selection; it may use the ladder per chunk, but it is - not the LOD system. *(corrects the first draft's D.2)* -- **Meshes are never replicated.** `scene::Terrain` states the rule: a derived - artifact is regenerated from its recipe on both ends, because sending a conclusion - instead of its input hands an attacker the half they choose. Replicate seed and - settings only, and lean on decision 14's strict IEEE arithmetic for agreement. -- **The noise is Perlin, not simplex, and it is in the wrong place.** The kernel in - `mono.engine/script/src/ComputeJobs.cpp` is private to `script`, has no seed - parameter, and wraps its inputs with `fmod(coord, 256.0)` so the field has period - 256. Any planet sampler must lift and seed that one kernel rather than vendor a - second. *(reshapes E03)* -- **The editor half is Studio, and Studio is client-only.** `mono.studio/nodegraph` - is in the program band precisely so no engine module can link it. E02's custom - inspector is Studio work, and it must not keep a second mutable copy of authored - recipe state. - ---- - -## Layer L1 `core`: values and determinism - -### Fundamentals - -- **Lift the Perlin kernel to a shared home.** Move the `Noise`, `Fade`, `Gradient` - and `PERLIN_HASH` block out of `script/src/ComputeJobs.cpp` so a generator below - L9 can call it. `ComputeJobs` then calls the shared one, and the duplicate is - deleted rather than left beside it. *(E03)* -- **Seed by offsetting the sample point, not by permuting the table.** The hash - table is what makes the kernel `math.noise` compatible, and Luau scripts depend on - that. Derive a per-layer `Vector3` offset from the seed through `core::Random` and - add it to the sample point. *(generalises E03's noise centre)* -- **Document the period and units.** The kernel repeats every 256 noise-space - units per axis. Planet noise samples a unit direction, so radius does not enter - its frequency unless a recipe explicitly selects metre-space sampling. Check - the full sampled span and every octave's frequency; `r * f < 256` alone cannot - guarantee a pattern without visible repetition. -- **Reuse `core::Random` for every derived value.** It is indexed and pure, so - `Float(index, salt)` is safe to call from `EachParallel` and gives the same answer - whether the loop ran or one entity spawned alone. A stateful generator would look - equivalent and quietly not be. -- **`core::ColorSequence` is the gradient type.** `Evaluate` is `constexpr` and - already the engine's answer for a colour ramp. Do not mint a planet-local gradient. - *(E05, E06)* - -### Additions - -- **Analytic derivative alongside the value.** An optional gradient return can - support field normals when propagated through the full sampler. Keep it separate - from the kernel move until parity and derivative checks pass. -- **A benchmark job for the sampler.** `just` recipe, executable under the build - directory, measurements printed to the terminal. Measure on the `release` preset - since first-party code is `-O0` by default. - -## Layer L2 `parallel` and L3 `ecs`: work and change - -### Fundamentals - -- **One component per independently invalidated concern.** `Planet`, - `PlanetNoise`, `PlanetColour` and `PlanetBiomes` as four components, so the - per-column dirty bit identifies candidate concerns. Compare canonical recipe - signatures per target before rebuilding: column dirtiness is not row-level - proof of a semantic change. This retains E02's shape/colour split. *(E02, E06)* -- **Stage dependency contract.** Validate, sample, build positions and normals, - encode surface UVs, prepare, then publish. LUT work depends on colour settings - and can run independently. Shading uses recipe-stable height bounds; measured - extrema are diagnostics, not changing inputs to every resident chunk. *(E05)* -- **Parallelise per face, per row.** The face grid is regular and every vertex is - independent, so `Jobs::For` over rows is the natural grain. `DEFAULT_GRAIN` is - 4096; below the crossover parallel is slower, so measure on `release` and put the - number in a comment, per rule 5. -- **Work inside a tick may be parallel, across ticks may not.** Decision 23. A - planet rebuild that spans ticks is legal only because the mesh is derived data; - the moment collision depends on it, publication has to land at a barrier. - -### Additions - -- **Content signature for batch-written state.** If any stage writes through - `EachBatch`, fold a signature the way `EditableMesh::Signature` does, because - those paths set no dirty bit. -- **Generation budget.** A cap on vertices rebuilt per barrier so a resolution-256 - planet spreads across several rather than stalling one. - -## Layer L4 `world`: barriers and replication - -### Fundamentals - -- **Replicate the recipe, never the geometry.** Seed plus the four settings - components go on the wire; every host runs the same generator and gets the same - planet. `scene::Terrain` makes this argument at length and a planet is that with - more vertices on it. -- **Generated state enters a world at an authority-approved barrier.** - `procedural-generation.md` decision 8. Visual-only chunks may appear as they - finish; anything physics reads may not. -- **Nothing crossing a world boundary is a pointer.** Rule 3. Every generation - request and result is an owned copy, which `EditableMeshJobs` already enforces by - taking ownership of the geometry at submit. - -## Layer L7 `scene`: what a planet is - -`scene` may see only `core`, `ecs`, `spatial` and `collision`, and holds no device -data and generates nothing. Everything here is storage plus resolvers. - -### Fundamentals - -- **`scene::Planet` component: the recipe.** `Seed` (u64, widest first), - `Radius`, `FaceResolution`, `Enabled`. Modelled field for field on `scene::Terrain`, - including the `Enabled` flag rather than an invalid generator name, so switching a - planet off does not lose its settings. *(E01, E02)* -- **Recipe ownership needs an explicit extension.** `scene::Terrain` is currently - a one-per-world resource. The proposed per-body component above must become an - instance of the same terrain recipe schema, not an independently owned copy of - the world's seed and generator. Multi-body persistence and authority are an M0 - decision; one cannot obtain them just by registering a `Planet` class. -- **`scene::PlanetNoise` component: the layer table.** Bounded array of layer - records rather than an array of objects, so the sampler walks one contiguous - allocation. Per layer: `Enabled`, `FilterKind`, `Strength`, `BaseRoughness`, - `Roughness`, `Persistence`, `Centre`, `MinValue`, `OctaveCount`, - `UseFirstLayerAsMask`, `WeightMultiplier`, and a stable layer identity for seed - derivation. *(E03, E04)* -- **A declared ceiling on layers and octaves.** The editor bounds controls; - decoders refuse invalid counts before allocation. Do not silently clamp a - replicated recipe into a different planet. Charge the product of sample count, - layers and octaves at admission. *(hardens E03's 1 to 8 range)* -- **`scene::PlanetColour` component.** LUT width, the ocean `ColorSequence`, and - the smoothness the ocean mask drives. *(E05, E07)* -- **`scene::PlanetBiomes` component.** Bounded array of `{ Gradient, StartHeight, - Tint, TintPercent }`, ordered by start height, plus `BlendAmount`, `NoiseOffset` - and `NoiseStrength`. *(E06)* -- **`Planet` authoring class.** Parents six `MeshPart` faces, one `Material`, one - `EditableImage` for the LUT and optionally one `ShaderScript`. Register it through - the ordinary class machinery so `Instance.new("Planet")` works and the schema dump - picks it up. -- **Resolution ceiling.** The video's 2 to 256 came from Unity's 65k vertex limit, - which does not apply here. Pick the ceiling from the geometry transaction's own - cost and state the number: six faces at 256 is 393,216 vertices per rebuild. - *(revises E01)* -- **Faces are `MeshPart`s named by `EditableMeshContentName`.** A generated mesh and - a published one are interchangeable from the renderer's point of view, which is - what `examples/EditableMesh.luau` exists to prove. - -### Additions - -- **`scene::PlanetFace` component** on each face entity: `LocalUp`, face index, - and the quadtree node it represents once chunking lands. Keeps face identity out - of child order. -- **Published mesh bounds from tracked vertex extrema.** Unbuilt chunks instead - need conservative field bounds for selection and culling. The host adapter - writes derived publication bounds; property getters do not regenerate them. - -## Layer L8: the generator module - -### Fundamentals - -- **Answer `CODE_ARCH.md` §8's six questions before minting anything.** Join the - proposed **`mono.engine/terrain` at L8, shared**. Its governing plan explicitly - excludes ECS, scene, render and VM dependencies. Accept owned values and return - neutral artifacts; a higher host adapter reads scene state and publishes meshes. - Do not turn permission to depend downward into a need to depend on `scene`. -- **The cube-sphere generator.** Six planar grids inflated to a sphere. Triangles - stay near-uniform, resolution is finely controllable, and faces subdivide cleanly - for the quadtree the roadmap actually asked for. *(E01)* -- **Face basis derivation.** From `localUp`, `axisA` by component swizzle and - `axisB` as `cross(localUp, axisA)`. An orthogonal basis per face with no lookup - table. *(E01)* -- **Vertex grid mapping.** `percent = (x, y) / (resolution - 1)`, then - `point = localUp + (percent.x - 0.5) * 2 * axisA + (percent.y - 0.5) * 2 * axisB`. - *(E01)* -- **Flat index addressing.** `i = x + y * resolution`, so no running counter and - every row is independently computable. *(E01)* -- **Triangle emission, counter-clockwise from outside.** Two triangles per cell, - skipping the right and bottom edges whose triangles fall outside the grid. The - index pairs are the video's with the winding reversed. *(E01, inverted)* -- **Exact buffer sizing.** `resolution^2` positions and `(resolution - 1)^2 * 6` - indices, allocated once. *(E01)* -- **Spherified-cube mapping, not plain normalisation.** The video flags the even - distribution as the better method and skips it; there is no reason to inherit the - worse one at the point the code is first written. *(E01, noted but not implemented - there)* -- **fBm filter.** `OctaveCount` octaves; frequency multiplies by `Roughness`, - amplitude by `Persistence`, each octave remapped from `[-1, 1]` to `[0, 1]` before - weighting. *(E03)* -- **Min-value threshold.** Preserve `value - MinValue` as signed field data. - Clamp only the final visible radius at sea level for the initial ocean-covered - surface. Clamping individual layers destroys depth before ocean shading can use - it. *(E03, refined by E07)* -- **Ridged filter.** `1 - abs(noise)`, squared, for sharp peaks with valleys - between. *(E04)* -- **Ridge detail weighting.** Each octave multiplied by a running weight seeded from - the previous octave's value and clamped to `[0, 1]` through `WeightMultiplier`, so - detail concentrates on high ground. *(E04)* -- **Filter dispatch by enum, not by interface.** The video's `INoiseFilter` plus - factory becomes a switch on `FilterKind`, keeping the hot loop allocation-free and - branch-predictable. *(E04, restructured)* -- **Layer masking.** Layers flagged `UseFirstLayerAsMask` multiply by the clamped - first-layer mask specified below, so negative depth cannot invert them. *(E03)* -- **Evaluate layer zero once.** Cache it as both the elevation base and the mask, - and start the accumulation at index one. This is the video's own optimisation and - it matters more here, where the sampler runs on a worker under a budget. *(E03)* -- **Split unscaled from scaled elevation.** The raw signed value is what ocean - shading needs; clamping at zero and applying `Radius * (1 + elevation)` happens - only in the scaled form. Filters must not clamp. *(E07)* -- **Elevation range tracked during sampling** in derived diagnostics. It validates - recipe bounds and supports the inspector. UVs use the fixed encoding contract - below, so loading a mountain cannot recolour previously resident chunks. *(E05)* -- **Strict IEEE throughout.** Decision 14. No fast-math, no reassociation, no - reliance on FMA contraction, or two hosts disagree about where the ground is. -- **Publish through the geometry transaction in the host adapter.** Convert neutral - artifacts to `EditableMeshGeometry`, prepare on a worker, then commit with the - observed revision. A single-mesh commit is not a multi-mesh transaction. Group - validation and publication are specified below. *(replaces E01)* - -### Additions - -- **Face render mask.** Generate one face only, as `All`, `Top`, `Bottom`, `Left`, - `Right`, `Front` or `Back`. Roughly a sixfold iteration speedup at high resolution - and the single most valuable authoring affordance in the whole series. *(E04)* -- **Skip inactive faces**, so the masked-out five cost nothing rather than being - generated and hidden. *(E04)* -- **Seam normal repair.** Evaluate normals from the same direction-space field on - both sides of an edge. Halo samples are derivative inputs, not rendered skirts. - Cross-face remapping and coarse/fine topology need separate rules below. - *(E01, explicitly deferred by the video)* -- **Shared index buffers.** Indices depend only on resolution, never on the noise. - Cache CPU templates by resolution and stitch pattern. The current geometry - transaction owns its vectors, so copying a template is the initial bridge; - actual shared GPU index storage needs a measured renderer change. -- **Quadtree chunking.** Subdivide each face by camera distance, which is what - `ROADMAP.md` v0.23.1 names. Chunks are derived, never stored and never sent, per - `scene::Terrain`. Selection is the quadtree's own; `LevelOfDetail` is a per-chunk - mesh ladder at most. -- **Collision through `scene::CollisionShapes`.** A decimated surface published by - the one conversion that already exists, so client, studio and headless server - agree about where the ground stops. Never build a hull in a property setter. -- **Domain warping** on the sample point, breaking up fBm's repetitive signature. - -## Layer L9 `script`: scheduling and the script surface - -### Fundamentals - -- **Adapt scripts to the shared generation request.** `EditableMeshJobs` supplies - the existing single-mesh bridge and script resumption pattern. Headless native - generation must not require a VM, and planet-wide atomic publication still needs - a host-level batch path. *(replaces E01's synchronous rebuild)* -- **`editableMesh:SetGeometry(vertices, indices)` is the script-facing path.** One - VM crossing for a complete face; the call yields and resumes when its ticket - commits. A Luau planet demo needs nothing else to publish geometry. -- **Respect `ComputeJobs`' declared limits** if noise grids are dispatched through - it: 1,048,576 samples maximum, eight pending requests, 4,096 samples served per - heartbeat. Six faces at resolution 256 is 393,216 samples, which fits the cap but - not one heartbeat. -- **Script property surface on `Planet`.** `Radius`, `FaceResolution`, `Seed`, - `Enabled`, `FaceRenderMask` as scriptable writable properties, following the - existing `class_property` conventions and the capability-parity requirement across - both VMs. *(E02)* -- **`Planet:Generate()`** for scripts that batch many writes and want one rebuild. - *(E02)* -- **`Planet:GetElevationAt(direction)`** returning scaled elevation along a unit - vector, so content is placed on the surface without a raycast. - -### Additions - -- **`Planet:GetBiomeAt(direction)`** returning the resolved biome index and blend - weights, for gameplay that reacts to terrain type. *(E06)* -- **Completion signal** when an async regeneration publishes, so scripts can place - content afterwards rather than guessing. -- **Capability parity across Luau and JavaScript**, which decision 4 makes - CI-enforced rather than optional. - -## Layer L12 `render`, client tier: shading - -### Fundamentals - -- **The proposed planet shader is a fragment `ShaderScript`**, named by `Material.Shader` - and resolved first against a `ShaderScript` in the world, then against a built-in. - An author's shader is an override rather than a separate mechanism. M0 must - settle the shipping compiler policy and prove the material bindings. *(E05)* -- **Signed height arrives in `UV.y`, with sea level fixed at `0.5`.** Recipe-stable - depth and land bounds encode each side separately on the CPU. The shader can - recover the shoreline test without an unavailable elevation uniform. See the - exact surface encoding contract below. *(replaces E05)* -- **Biome coordinate in `UV.x`.** Computed per vertex and interpolated for free. - *(E06)* -- **The LUT is a `scene::EditableImage`**, bound as `SurfaceAppearance::ColourMap` - through `EditableImageContentName`. Row-major RGBA8, uploaded by - `client::UpdateEditableImages` when the revision moves. *(E05)* -- **LUT layout: width `2 * resolution`, height `biomeCount`.** Ocean ramp in the - first half, land in the second, one row per biome. One texture, one bind, one - sampler, which is the video's own packing and is still the right call. *(E06, E07)* -- **Mipmaps off.** Filtered lower-resolution mips smear adjacent biome rows - together and produce visible banding at distance. The video hits this bug on - camera and the fix is the same here. *(E07)* -- **Clamped sampling.** Wrapping bleeds the top of the height range into the - bottom. *(E05)* -- **Split-range selection in the fragment shader.** Decode the fixed shoreline - threshold, then address texel centres inside the selected ocean or land half. - Use a clear comparison; branchless syntax is not a performance requirement. - *(E07)* -- **Ocean smoothness mask.** The same shoreline value raises smoothness on water - only, so the ocean catches a sun specular and the land does not. *(E07)* -- **Biome tint.** Blend each biome's gradient toward a solid tint by `TintPercent`, - so one gradient serves several biomes. *(E06)* - -### Additions - -- **Biome boundary noise.** Perturb the latitude percent before biome selection, - scaled by `NoiseStrength` and shifted by `NoiseOffset`. Straight latitude bands - read as obviously artificial. *(E06)* -- **Biome blending.** Weight per biome as - `inverseLerp(-blendRange, +blendRange, distanceFromStartHeight)`, accumulated with - the running index scaled by `1 - weight` first so it cannot overshoot. *(E06)* -- **Blend-range epsilon.** Add `0.001` so a blend amount of zero does not collapse - the inverse lerp. *(E06)* -- **LUT allocation and repaint are separate.** Allocate or resize for missing - images and dimension changes. Repaint when any gradient, tint or packed material - value changes, even at identical dimensions. Resize clears the image. *(E05, E06)* -- **Colour updates reuse terrain samples and topology.** Gradient edits repaint - the LUT; biome boundary edits update UVs. The current mesh transaction may still - upload an entire changed mesh for a UV-only edit. Do not promise partial uploads - before verifying or extending that path. *(E06)* -- **Triplanar detail and slope shading**, so the surface holds up closer than the - series ever goes. - -## Layer L12 `examples` and the program band: demos and authoring - -### Fundamentals - -- **`examples/Planet.luau`.** The demo the roadmap actually asks for, in the shape - `examples/EditableMesh.luau` established: a header comment saying what it proves - and cannot be proven otherwise, then the scene. Run with - `client --script Planet.luau`. -- **Update `docs/DEMOS.md`**, which is currently a TODO, and attach a GIF as - v0.23.1's demo block asks. -- **Studio owns the authoring UI.** E02's nested inspector, change-check scope, - auto-update toggle and manual generate button are Studio features over the - recipe components. Studio must not keep a second mutable copy of authored state. - *(E02)* - -### Additions - -- **A planet node set for the node graph editor**, once v0.23.1's `NodeCanvas` - lands. Engine modules cannot link `mono.studio/nodegraph`, so the nodes are Studio - side and the evaluator is the shared generator. -- **Face and quadtree overlay** through the existing `gui.Adornment` handles, to - see chunk boundaries and the active render mask. -- **Per-stage timing readout** so the expensive stage is obvious while tuning. -- **Seed randomise**, for surveying the space one settings asset covers. - ---- - -## Expressive additions, last - -Only after everything above is complete and passing. - -- **Crater filter**, a third `FilterKind` producing impact craters with raised - rims, for airless bodies. Feeds v0.26's asteroid demo directly. -- **Gas giant variant**, banded and animated in the fragment shader with no - displacement, driven by latitude and flow noise. -- **Polar caps by axial tilt**, deriving the biome axis from the planet's own - orientation rather than world Y. -- **Rivers and erosion**, a post-pass carving drainage into the height field so the - terrain reads as weathered rather than merely additive. -- **Vegetation scatter**, density-driven and filtered by biome, slope and altitude, - published through the placement domain in `procedural-generation.md`. -- **Night-side city lights** as an emissive mask where the surface faces away from - the sun. -- **Atmosphere binding.** `scene::AtmosphereProcedural` already carries - `PlanetRadius`, `AtmosphereHeight`, `Rayleigh`, `Mie` and `Samples`; drive them - from the planet's own radius and elevation range so the shell always matches the - surface. -- **Cloud shell** through `scene::Clouds` and `scene::CloudCompute`. -- **Planet-relative gravity and orientation**, so a character walks the surface. - This is the point at which chunk collision becomes a simulation input and the - barrier rule stops being theoretical. -- **Ring systems**, a textured shadow-receiving plane with the planet's own shadow - across it. -- **Seeded variant generator**, randomising the whole settings space under - plausibility constraints to populate a system in one call. - ---- - -## Detailed build contracts - -The layer inventory says where work belongs. This section says what a working -result must do. Keep the first vertical slice small, but settle the seams before -building more surface area. Grug has seen six pretty faces hide twelve cracks. - -### Scope and ownership - -The first planet is a radial heightfield: each direction from the centre has -one ground radius. Caves, overhangs and detached islands require the later SDF -domain. Do not promise those through a height query that cannot represent them. - -The initial sea is the clamped outer surface of that field. It supplies colour -and smoothness, but no underwater ground mesh, refraction, buoyancy or fluid -simulation. A later separate ocean shell must state how seabed collision differs -from the visible water surface. - -| Concern | Owner and boundary | -|---|---| -| Seed, generator identity, authored parameters | One terrain recipe schema, instanced for each body if M0 approves that extension | -| Planet radius, axis, noise and biome values | Planet-specific parameters in that recipe, exposed through scene properties | -| Canonical bytes and generation identity | Shared procedural-generation contract | -| Direction sampling and cube-face topology | Terrain domain, pure owned inputs and outputs | -| ECS reads, target revisions and accepted activation | Host adapter at the world mutation barrier | -| Job execution and cancellation | Existing shared request coordinator and fork-joined job system | -| Physical contact geometry | Collision artifact consumed by the ordinary physics path | -| GPU upload, material binding and retirement | Render/client consumers | -| Inspector, undo and preview state | Studio over canonical recipe operations | - -Do not add a graph evaluator merely to generate the first sphere. A typed -generator recipe is already a supported form in the procedural-generation plan. -Later terrain graph nodes call the same samplers and mesher. - -### Recipe fields and admission - -Use named values with explicit units. Defaults below are proposed fixtures for -the first build. Engine ceilings may force lower limits; larger defaults need -release measurements and an updated resource estimate. - -| Field or group | Proposed initial rule | -|---|---| -| Schema and generator version | Required, separate versions for encoding and numeric behaviour | -| Seed | Full unsigned 64-bit value, serialized without floating-point loss | -| Radius | Finite, strictly positive world metres; no physical maximum claimed until precision tests pass | -| FaceResolution | Samples per axis, default 33; full-face preview accepts 2 through 256 | -| ChunkResolution | 33 samples, hence 32 cells; alternate values must be `2^k + 1` | -| Noise layers | At most 8, stable identities, explicit order | -| Octaves per layer | 1 through 8; disabled layers incur no sample cost except the explicit first-layer mask case | -| Strength and frequency | Finite and nonnegative; reject overflow in octave frequency and amplitude products | -| Persistence | `[0, 1]` for the first supported filters | -| Roughness | Finite, at least 1; reject recipes exceeding the coordinate precision profile | -| Ridge WeightMultiplier | Finite and nonnegative; each resulting feedback weight clamps to `[0, 1]` | -| Biomes | 1 through 16; an empty authored list canonicalizes to a documented default biome | -| Biome StartHeight | `[0, 1]`, strictly increasing in serialized order | -| TintPercent and BlendAmount | Finite, `[0, 1]` | -| LUT ramp resolution | Default 256 per half, allowed 2 through 1024, with image pixel limits checked too | -| Depth and land encoding bounds | Finite, strictly positive dimensionless extents from sea level | -| Maximum quadtree depth | Initial safety ceiling 16, also limited by integer and numeric coordinate precision | -| Transform | Translation and rotation; positive uniform scale only for the first physical planet | - -The editor may constrain a slider. A decoder or script API returns a structured -error for invalid input instead of silently producing different canonical bytes. -Canonicalization of defaults is versioned and runs before signatures are made. - -Reject NaN, infinity, unknown filter kinds, duplicate layer identities, malformed -gradients and invalid transforms. Bounds checks happen before allocating arrays. -The same validation serves saves, replication, scripts and Studio imports. - -An unchanged property assignment is a semantic no-op. An auto-update edit captures -one immutable recipe after the current edit transaction, not one request per -property setter. Dragging a slider coalesces superseded previews. - -### Coordinate space and stable sampling - -Noise uses planet-local unit directions. Changing radius scales the body without -moving continents. Rotation and translation change placement without changing -the planet's field signature; transforms still update world bounds and collision -placement through the existing instance path. - -Keep these quantities distinct in APIs and diagnostics: - -| Quantity | Meaning | -|---|---| -| Cube point | Coordinates on a canonical face before sphere mapping | -| Direction | Unit vector from planet centre, independent of radius | -| Raw elevation | Signed, dimensionless layered field value relative to sea level | -| Surface radius | `Radius * (1 + max(0, rawElevation))` in the initial ocean mode | -| Surface position | Direction multiplied by surface radius, in planet-local metres | -| World position | Transformed local position, used by physics and presentation | -| Biome latitude | `(dot(direction, biomeAxis) + 1) / 2`, before boundary noise | - -Normalize a finite nonzero direction once at the query boundary. Reject zero, -nonfinite or overflowed length inputs. The internal sampler accepts only the -validated direction representation and performs no ECS access. - -Compute chunk sample locations from integer face coordinates and dyadic ranges. -Avoid repeated floating-point accumulation across rows or down the quadtree. -Parent samples that coincide with child samples must take the same canonical -coordinate path, including identical operand ordering. - -Define face order as `+X, -X, +Y, -Y, +Z, -Z`. Face indices are topology values, -not child creation order. Saved symbolic names must not depend on an enum's -declaration index or `core::Name::Id()`. - -For a cube point `(x, y, z)`, the selected mapping is: +- A planet is a radial heightfield over six cube faces. It cannot represent + caves, overhangs, or detached islands. Those require the later SDF terrain + domain. +- Face identity is topological and serialized by name: `+X`, `-X`, `+Y`, `-Y`, + `+Z`, `-Z`. It never derives from declaration order or a process-local id. +- Requests use integer face coordinates and dyadic ranges. Parent samples that + coincide with child samples take the same arithmetic path, so a level change + cannot introduce a different edge value. +- The selected spherified-cube mapping is evaluated in the documented order: ```text s.x = x * sqrt(1 - y*y/2 - z*z/2 + y*y*z*z/3) @@ -601,564 +26,39 @@ s.y = y * sqrt(1 - z*z/2 - x*x/2 + z*z*x*x/3) s.z = z * sqrt(1 - x*x/2 - y*y/2 + x*x*y*y/3) ``` -Pin the evaluation order and any final normalization in the generator version. -Clamp only tiny negative radicands caused by rounding inside the validated cube -domain. A materially negative radicand is an invalid coordinate, not a value to -hide with a clamp. - -### Noise and layer semantics - -Moving the shared kernel must preserve the old script result for positive, -negative, integer and period-boundary inputs. Seed offsets are an adapter around -that kernel, not a change to `math.noise` semantics. Huge integer seeds must not -first become a float. - -Derive bounded seed offsets from stable layer identity and a named stream. Keep -them in a documented noise-space interval so large offsets do not erase sample -precision. Reordering layers may change accumulation and masking, but it must -not accidentally change each surviving layer's seed stream. - -The initial filter contract is explicit: - -1. Begin octave amplitude at 1 and frequency at `BaseRoughness`. -2. Sample direction times frequency, plus authored centre and seed offset. -3. For fBm, remap the kernel value to `[0, 1]` before amplitude weighting. -4. For ridges, square `1 - abs(noise)`, multiply by the previous ridge weight, - and derive the next clamped weight from that weighted ridge value. -5. Multiply frequency by `Roughness` and amplitude by `Persistence` each octave. -6. Subtract `MinValue` after the octave sum, then multiply by `Strength`. - -The initial recipe does not divide by the amplitude sum. Changing that convention -later changes terrain and requires a generator version. Zero strength produces -zero contribution and can skip its noise work unless an independently defined -mask needs the underlying sample. - -Layer zero contributes its signed filtered value only when enabled. When another -enabled layer requests its mask, evaluate layer zero even if its direct -contribution is disabled. The mask is `clamp(firstFilteredValue, 0, 1)`; an empty -layer list produces zero elevation. This deliberately fixes mask range rather -than letting values above one amplify mountains without an explicit strength. - -Sum enabled contributions in authored order. No parallel reduction across -layers. Worker parallelism distributes sample locations, preserving the scalar -sampler's arithmetic order at each location. - -An analytic noise derivative is optional. It must include octave frequency, -strength, mask product and any later warp chain rule before it becomes a surface -normal. An isolated Perlin gradient is not the planet normal. - -### Normals and geometric seams - -Begin with direction-space finite differences using a deterministic tangent -basis. Sample nearby directions, construct displaced surface positions and take -an outward-oriented cross product. Choose and record a derivative step in the -numeric profile; it is independent of the currently visible LOD. - -Identical directions use the same basis, step, field version and samples on both -faces. This gives shared edge normals without averaging across separately -published meshes. Validate the numerical error near basis-axis changes and at -the clamped shoreline, where the surface itself has a slope discontinuity. - -The topology suite covers all 12 cube edges and all 8 corners. Each directed -edge needs a neighbour face, neighbour edge and parameter reversal flag. Derive -and verify this table from the face bases once; never guess orientation while -walking a live tree. - -A one-ring halo must remap to the adjacent face or sample directions directly. -Applying the spherified formula blindly outside its cube-face domain is not a -halo policy. Rendered skirts cannot repair a normal mismatch and are not -collision geometry. - -### Surface encoding and material contract - -Let `e` be raw elevation, `D` the fixed depth extent, and `H` the fixed land -extent. Store the following scalar in `UV.y`: - -```text -e < 0: h = 0.5 * (1 - clamp(-e / D, 0, 1)) -e >= 0: h = 0.5 + 0.5 * clamp(e / H, 0, 1) -``` - -Store the continuous biome row index `b` in `UV.x`, mapped to the row centre as -`(b + 0.5) / biomeCount`. The fragment shader uses `UV.x` for texture Y and -decodes `UV.y` for texture X. Names and axis swaps belong beside both encoder -and shader; an unlabelled `texture(lut, uv)` is wrong here. - -For ramp width `W` and total width `2W`, map ocean `t = 2h` to -`(0.5 + t * (W - 1)) / (2W)`. Map land `t = 2h - 1` to -`(W + 0.5 + t * (W - 1)) / (2W)`. Select ocean for `h < 0.5` and land otherwise. -These coordinates sample texel centres and avoid accidental horizontal blending -across the two packed ramps. Exact sea level selects the land shoreline texel. - -Linear interpolation between biome rows is intentional. Mips remain disabled, -and addressing clamps on both axes. Verify the actual material sampler supports -these settings; if not, add the narrow sampler support before marking M4 done. - -Use recipe-stable `D` and `H`, authored or conservatively derived before chunk -sampling. Saturated samples increment a diagnostic counter. Never renormalize -all chunks from the extrema of whichever faces happen to be resident. - -Proposed packing: RGB carries the gradient colour, alpha carries smoothness, -and the planet material is opaque. Ocean smoothness fills ocean texels; land -smoothness fills land texels. This is a proposed ShaderScript contract that must -be proved by the renderer probe. If alpha is consumed as opacity before the -custom shader, add a built-in material path or a supported property binding; -do not silently make the ocean transparent. - -Specify the gradient's working colour space and editable-image upload decode in -M4. Encode and decode once. A two-colour known-value ramp checks against double -gamma conversion. No per-triangle vertex colour approximation substitutes for -this test. - -Biome boundaries use local latitude plus bounded boundary noise. Clamp the -selection coordinate, compute the continuous row index in stable order, and -return the same normalized blend weights from gameplay queries. At an exact -weight tie, the lowest authored biome index wins the dominant-biome query. - -The initial shoreline is interpolated across triangles. Very coarse triangles -can blend across a narrow island; this is a resolution limitation to measure in -the demo, not evidence that the shader can reconstruct unsampled terrain. - -### Dependency and invalidation matrix - -Each row describes the narrowest required rebuild. Existing whole-mesh upload -behaviour can make publication more expensive, but must not force resampling. - -| Changed input | Reused | Rebuilt or updated | -|---|---|---| -| Seed, noise values, layer order | Index templates, unchanged LUT | Field, positions, normals, UVs, bounds, collision | -| Radius | Direction samples, raw elevation, LUT | Scaled positions, metric bounds, collision, LOD error scale | -| Translation or rotation | Object-space fields and meshes | Instance placement, world bounds, interests | -| Gradient, tint, smoothness | Fields, topology, positions, UVs | LUT pixels and material revision | -| Biome starts, axis or noise | Elevation and topology | Biome samples, UVs, gameplay biome data | -| Biome count or ordering | Elevation and positions | LUT dimensions/content and matching UV encoding together | -| Depth/land encoding bounds | Raw elevation, positions, collision | Encoded UVs | -| Chunk resolution or stitch pattern | Compatible field cache entries, LUT | Requested sampling grid or indices, mesh preparation | -| Camera movement | Recipe and resident artifacts | Visual interest and selected chunks | -| Collision interest movement | Existing canonical artifacts | Collision residency requests and activation set | -| Face preview mask | Full-world recipe and authoritative collision | Preview interest and visible debug faces | -| Enabled becomes false | Authored recipe | Cancellation and barrier-controlled removal of generated state | - -Keep field, topology, material and collision signatures separate inside the -shared cache contract. Do not add a second private dirty-bit system to express -this table. A component dirtiness signal only triggers comparison of inputs. - -### Request identity, lifecycle and publication - -Use the shared generation envelope. The planet scope adds topology version, -face, depth, integer chunk coordinates, sample resolution and halo. Output keys -include field parameters, generator version, normal profile, encoding version -and requested output kind where each affects that output. - -Target world, entity generation, ticket and expected publication revision are -lifetime checks, not content identity. Priority and camera distance do not change -the mesh. Hash canonical fields, never struct padding or process-local names. - -```text -Captured -> Validated -> Queued -> Building -> Prepared -> Published - -> Rejected -Queued/Building/Prepared -> Cancelled | Superseded | Failed -Prepared -> DroppedStale -``` - -These are shared request states or an adapter view of them, not a new scheduler. -Every ticket reaches exactly one terminal outcome. A cached result still passes -the target and revision checks before publication. - -Workers own snapshots and output buffers. They never retain an ECS pointer, -material pointer or script stack reference. Cancellation checks occur between -bounded rows or blocks and before each expensive downstream stage. - -Before publishing a group, the world owner checks all destinations, entity -generations, recipe revisions, image revisions, counts, index ranges, finite -attributes and output signatures. `PrepareEditableMesh` currently checks matching -array sizes and indices; it does not prove finite coordinates or a planet budget. -Those checks belong in artifact validation before preparation. - -The current geometry representation requires normals, UVs, colours and alphas -to match the position count. Fill neutral colours and opaque alphas even though -the shader's colour comes from the LUT. Empty optional-looking arrays would fail -the actual preparation contract. - -Multi-object publication must have an all-or-none path. Prepare replacement -meshes, image data and collision artifacts before entering the mutation barrier; -preflight all destinations, then swap a complete generation through a group -primitive that cannot fail midway. Alternatively publish a fully staged hidden -generation by swapping its root references at the barrier. Neither guarantee -comes from simply calling `CommitEditableMesh` six times. - -Whole-recipe replacement, changed biome row layout and a parent-to-children LOD -swap each define a publication group. Independent visual chunks of an already -accepted recipe can publish separately when coverage and edge constraints hold. - -If a group fails, retain the prior accepted generation and report the failure. -If a target was destroyed or disabled, drop its results and release ownership. -On shutdown, cancel coordinators, join owned work and reject late completions. - -Identical content emits a no-op receipt without changing mesh, material or -collision revisions. Do not repeatedly enqueue work just to discover this at -the final byte comparison. - -### Quadtree identity and selection - -Each of six roots covers one face. A node key is `(face, depth, x, y)`, with -`0 <= x,y < 2^depth`. Children are assigned a fixed quadrant order. The recipe -digest and topology version qualify this spatial key in caches. - -Use 32 cells per chunk initially. Four children therefore share every other -boundary sample with their parent. Keep full-face preview resolution separate -from chunk resolution; 256 preview samples are not a stitchable 256-cell chunk. - -Each chunk records conservative bounds and a geometric error estimate relative -to the finer field. A sampled maximum alone is not a proven bound on unsampled -noise. Use a documented conservative bound or keep refining with a clearly -labelled heuristic until the bounded estimator is ready. - -Select visual LOD from projected geometric error using camera projection and -the nearest conservative chunk distance. Start with split above 2 pixels and -merge below 1 pixel as tunable defaults. Orthographic views need their own pixel -scale; a camera inside a bound uses the highest allowed demand, not division by -zero. Clip depth and demand against hard limits. - -Merge demand from active main, portal, surface and editor views by taking the -finest requested level per region. Hidden views submit no interest. Apply -frustum culling first; add horizon culling only when relief-aware bounds prove it -safe for the current observer position. - -Neighbour leaves differ by at most one level, including across cube faces. -Balance the selected tree before scheduling. Use fixed key order for ties and -reserve capacity for balancing neighbours, since a split may require more than -four new chunks. - -### Crack-free transitions and residency - -At equal LOD, shared edge positions must match exactly in canonical local -coordinates. At a one-level boundary, select a transition index pattern on the -fine edge so it joins the coarse edge's polyline. Simply sampling the same -smooth field at different densities still leaves T-junction cracks. - -With four edges there are 16 coarse-neighbour masks. Verify each pattern and -corner combination at the fixed chunk resolution. Transition triangles must -retain outward winding and have no degenerate or duplicate triangles. Shared -positions, normals and biome encoding need separate checks. - -Pin the parent while its children build. Once all four children, required -neighbour transitions and draw resources are ready, swap coverage as one group. -Merging reverses this: prepare and pin the parent before retiring its children. -Never draw both complete surfaces indefinitely and rely on depth testing to -hide overlap. - -Initial split/merge swaps may pop while remaining watertight. Geomorphing is a -later visual improvement with its own seam and shadow checks. Skirts are an -explicit visual fallback for exceptional unavailable neighbours, with a bounded -depth and a visible diagnostic count. They cannot be the normal crack solution. - -On a teleport, keep coarse coverage while high-priority chunks load. On memory -pressure, stop new refinements and merge only into ready parents. Eviction cannot -remove the only visible coverage, active collision or an in-progress transition -dependency. If even the minimum root set cannot fit, reject activation cleanly. - -The scheduler merges identical chunk requests across views. Cache accounting -includes pinned, building, prepared, visible and retiring bytes. Cancellation of -one viewer must not cancel an artifact still required by another viewer. - -### Collision, queries and authority - -Visual demand follows cameras. Collision demand follows authoritative bodies, -their movement envelopes and the world's interest policy. A server without a -camera must still generate safe ground. - -Choose a fixed collision sampling profile initially, independent of visual LOD. -Pin neighbouring collision chunks around moving bodies and prefetch enough for -the declared speed and generation latency budget. Teleports use an explicit -readiness gate; movement cannot proceed into a missing collision region. - -The coarse render fallback is not permission to replace collision with a sphere. -Collision replacements and matching accepted recipe revisions activate at the -authority-selected tick. If preparation is late, retain the old accepted state -or delay activation according to the shared readiness policy. Worker completion -time cannot choose a simulation tick independently on each peer. - -Triangle collision must agree on edges and winding, including cube corners. -Give simplification a maximum radial error in world metres. Character and ray -tests determine that bound; arbitrary decimation ratios do not prove safe ground. -No visual skirts enter collision output. - -Split query semantics explicitly: - -| Query | Contract | -|---|---| -| `GetElevationAt(direction)` | Proposed compatibility convenience returning surface radius in metres; document the name's ambiguity | -| `SampleSurface(direction, revision)` | Radius, local position, normal, signed raw elevation and biome weights for an identified accepted recipe | -| Active ground query or raycast | Uses currently active collision, returning its accepted revision | -| Preview sample | Uses the pending authored recipe and is explicitly labelled non-authoritative | - -Analytic surface radius can differ from a decimated collision triangle between -vertices. Return source/revision information and state the approximation error; -gameplay needing contact uses active collision. Do not imply the two are exact. - -Large query batches run through bounded native requests. Script callbacks never -execute once per sample. Both VMs expose the same limits and result meanings. - -### Precision and reproducibility gates - -Strict compiler arithmetic is necessary, but it alone does not establish -bit-identical `sqrt`, vector normalization or library behaviour on every target. -Declare `BitExact` only after canonical artifact vectors match across the -supported platform matrix. Otherwise adopt the shared `Quantized` profile with -an explicit grid before hashing and collision use. - -Record the profile's numeric types, operation order, FMA policy, normalization, -noise offset algorithm and encoding rules. A profile change invalidates caches -and requires a generator compatibility version. Never fix a numeric mismatch -by suppressing the digest comparison. - -Planet-local construction avoids distant-world translation error but does not -by itself solve a huge radius stored in floats. Before advertising walking on -planet-scale bodies, measure vertex and contact error versus radius and depth. -Chunk-relative render origins may help rendering; their support must be proved -in the existing instance layout. Physics needs its own supported origin policy. - -Translation-only rebasing must not regenerate noise or change content signatures. -Test tangent motion, near-pole motion and cube-corner crossings at the largest -supported radius. State the tested radius and maximum positional error in the -demo documentation. Reject unsupported nonuniform or mirrored physical scale. - -### Resource accounting and overload behaviour - -Count allocations before submission using checked wide arithmetic. Admission -reserves output and scratch capacity, not only the final mesh's size. - -For a full planet at `N` samples per face: - -```text -vertices = 6 * N * N -triangles = 12 * (N - 1) * (N - 1) -indices = 36 * (N - 1) * (N - 1) -``` - -At `N = 256`, that is 393,216 vertices, 780,300 triangles and 2,340,900 indices. -Assuming 48 bytes per vertex across position, normal, UV, colour and alpha, plus -32-bit indices, the base CPU geometry payload is 28,237,968 bytes, about 26.93 -MiB. This excludes vector overhead, field samples, halos, collision, staging, -GPU buffers and the previous live generation. Use actual `sizeof` values in the -implementation's estimator rather than assuming this layout. - -For eight eight-octave layers, that full-face grid alone can require 25,165,824 -kernel evaluations before normals or biome noise. A vertex cap by itself is not -a CPU budget. Finite-difference normals multiply sampling work substantially. - -Start with the following configurable service policies, subject to measurement: - -| Resource | Initial policy | -|---|---| -| Rebuilds per planet | One active recipe request plus one newest coalesced replacement | -| Expensive generation work | Charge estimated kernel evaluations, cells and output bytes | -| Worker cancellation unit | Bounded row/block with a measured worst-case duration | -| Owner-thread publication | Bounded bytes and groups per barrier, reserving a complete indivisible group | -| Visual refinement | Limited requests per frame with fair service across planets | -| Preview work | Lower priority than active collision and main-view coverage | -| CPU cache and scratch | Separate byte and entry ceilings, with live pinned bytes visible | -| GPU residency | Separate upload, live and retirement budgets | -| Collision | Reserved capacity independent of visual cache pressure | - -Set hard byte ceilings and latency targets on named desktop and headless-server -hardware before M7 exits. Do not invent a universal millisecond promise in this -document. A request whose indivisible publication exceeds the maximum barrier -budget is refused or rebuilt with smaller chunks; it must not wait forever. - -Backpressure yields an explicit queued, rejected or degraded-visual outcome. -No path silently exceeds a hard ceiling. Queue cancellation releases reservations -exactly once, and repeated edits cannot accumulate unbounded prepared buffers. - -### Save, replication and API completion - -Save canonical recipe parameters, generator/profile versions, stable body -identity, transform and supported edit references. Do not save GPU handles, -worker state, tickets or the current camera's selected quadtree as authored data. -Baked cache artifacts remain optional and verifiable against the recipe. - -Replicate full-width seeds and stable names without lossy number conversion. -Luau and JavaScript need a shared full-width seed representation, such as the -engine's existing integer codec or canonical decimal text. Numbers above -`2^53 - 1` must not silently round through either scripting surface. - -A late join receives the canonical recipe and active revision/activation state. -Version mismatch produces a clear unsupported-generator result. Do not let an -older peer approximate a newer physical field with whatever sampler it has. - -`Generate()` returns or awaits the shared ticket contract. Completion reports -accepted revision and outcome, including unchanged, superseded and failed. -Setting `AutoUpdate = false` makes explicit generation the publication trigger; -queries must distinguish the authored draft from the last accepted recipe. - -Studio undo/redo records recipe operations. It cancels superseded preview work -and restores canonical values without storing a second editable planet model. -Face masks and debug overlays are editor/view state unless the author explicitly -chooses a supported saved presentation setting. They never remove server ground. - -The authoring view follows the project's visual defaults: true black background, -white primary text, dense controls and minimal copy. Show invalid fields beside -their controls, retain the last valid preview, and stop preview submissions when -hidden. Progress uses stage names and counters without continuously repainting -spinners, shimmer or pulse effects. - -### Failure matrix - -| Trigger | Required result | -|---|---| -| Invalid recipe or overflow estimate | Refuse before expensive allocation; retain accepted generation | -| Recipe changes during generation | Supersede old ticket; reject its late publication | -| One face or child fails preparation | Retain prior complete coverage; publish no partial group | -| Entity destroyed and handle index reused | Entity generation check drops old completion | -| LUT row count changes mid-build | Mesh and LUT revision checks prevent mismatched row encoding | -| Cache exhausted | Preserve pinned coverage and collision; stop refinement or refuse admission | -| Device lost | Keep CPU recipe/artifacts, rebuild residency through renderer recovery | -| World stops | Cancel, join owned work and retire resources without script callbacks into a dead world | -| Unsupported numeric or generator version | Fail explicitly before authoritative activation | -| Collision misses activation deadline | Keep previous accepted state or delay through authority policy | -| Finite field exceeds shading extent | Clamp encoding, report saturation; preserve true field and bounds | - -### Verification and profiling - -Tests belong with the public behaviour they prove. Use table-driven topology and -numeric cases in the relevant header suites, and a few integration scenarios for -publication, streaming and authority. Do not create dozens of one-line smoke -tests or tests that merely assert deleted implementation details stay absent. - -| Suite area | Required evidence | -|---|---| -| Shared noise | Existing script vectors unchanged; seeded offsets stable; negative and period-boundary inputs covered | -| Recipe codec | Round trip, full-width seeds, canonical defaults, unknown versions, nonfinite values and checked overflow | -| Cube topology | Outward nondegenerate triangles, exact counts, all face adjacencies and corners | -| Field sampler | Empty layers, disabled first-layer mask, signed depth, ridges, stable layer order | -| Normals | Outward unit normals and bounded edge difference across faces and LOD | -| Surface encoding | Ocean-only, land-only, zero elevation, saturated extrema, one biome and row-centre addressing | -| Invalidation | Gradient edit performs zero noise sampling; radius change reuses dimensionless field | -| Publication | Partial failure, stale target, destroy/reuse, cancellation, no-op and one accepted revision | -| LOD topology | All 16 transition masks, cross-face balancing, split/merge coverage and winding | -| Collision | Body crosses face and chunk borders without falling, launch impulses or contact holes | -| Reproducibility | Serial/multiple worker counts, cold/warm cache, supported platforms and saved replay | -| Lifecycle | Repeated edits, world stop and constrained-cache traversal release all reservations | -| Script adapters | Same errors, ticket outcomes, seed values and query results in both VMs | - -Use one curated visual scene with fixed seed and camera poses. Include a smooth -sphere, ocean planet, ridged planet, polar biome and deliberately sharp shoreline. -Inspect face edges under grazing light, transitions during motion and texture -filtering at distance. GPU behaviour is checked by running the real client. - -Benchmark cold generation, warm cache, LUT-only edits, biome-UV edits and sustained -chunk traversal separately. Record release preset, hardware, worker count, -backend, resolution, layer/octave counts and cache state. Benchmark executables -live under the build output; measurements print to the terminal per house rule. - -Use the engine's profiling scopes for validation, queue wait, sampling, normals, -meshing, preparation, collision, upload and publication. Report owner-thread -wall time separately from summed worker work. Expose stale drops, cancellations, -cache bytes, pinned chunks, kernel evaluations and upload bytes. - -An idle accepted planet must submit no generation, upload no geometry or LUT -bytes, and dirty no collision state. A moving camera may update selection while -resident chunks remain unchanged. Measure those paths explicitly. - -### Build slices and review boundaries - -Each slice leaves a working demo or a directly callable headless path. Proposed -file names follow the module's conventions once those are read; do not create -public headers solely to mirror every paragraph in this plan. - -| Slice | Concrete reviewable change | -|---|---| -| Contract alignment | Recipe owner decision, module graph edges, shader probe and numeric profile | -| Shared sampler | One moved noise kernel, compatibility tests, measured sampler job | -| Pure sphere | Neutral terrain mesh artifact, fixed six-face topology, headless numeric checks | -| Scene bridge | Owned conversion and publication adapter, neutral vertex attributes, no-op behaviour | -| Signed field | fBm, ridges, masks, bounds and surface queries using one sampler | -| Material path | Fixed UV encoding, LUT pixels, real shader/material binding and visual fixture | -| Full authored planet | Both VM adapters needed by the demo, save/load, face preview mask | -| Chunk topology | Integer keys, neighbour table, balanced tree and verified transition indices | -| Streaming | Shared requests, bounded cache, parent/child publication and multi-view demand | -| Physical activation | Camera-independent demand, collision groups and authority readiness | -| Authoring completion | Undo/redo, hidden-preview stop, diagnostics and demo documentation | - -The scene bridge may begin with one mesh. It cannot claim planet-wide atomicity -until the group path lands. Likewise, a six-face render proves the sphere, while -the quadtree milestone requires actual chunk selection and transition evidence. - ---- - -## Milestones, mapped to the roadmap - -| # | Scope | Target | -|---|---|---| -| M0 | Ownership, shader transport, numeric profile, architecture edges and limits agreed through concrete probes | prerequisite | -| M1 | Perlin kernel lifted and seeded, `ComputeJobs` calls the shared one, duplicate deleted | prerequisite | -| M2 | Cube-sphere geometry, correct winding, spherified mapping, published via `EditableMeshJobs` | v0.23.1 | -| M3 | fBm and ridged filters, masking, signed threshold, measured extrema | v0.23.1 | -| M4 | LUT in `EditableImage`, proved material binding, sea-level-preserving height encoding | v0.23.1 | -| M5 | Biomes, boundary noise, blending, packed ocean ramp, ocean smoothness | v0.23.1 | -| M6 | `examples/Planet.luau`, `DEMOS.md` entry with GIF, face render mask | v0.23.1 | -| M7a | Quadtree selection, balanced neighbours, stitched transitions, bounded visual residency | required for v0.23.1 quadtree claim | -| M7b | Collision demand, physical seam checks, grouped authority-approved activation | before walkable planets, aimed toward v0.26 | -| M8 | Extended script queries and authoring tools; basic API parity lands with each earlier exposed feature | v0.24 | -| M9 | Expressive additions, selectively | v0.26 and after | - -M1 through M6 deliver the procedural sphere demo. M7a is required before marking -"quadsphere, quadtree planet" complete. If the terrain roadmap cannot accommodate -that work in v0.23.1, update the release scope explicitly instead of calling six -fixed faces a quadtree. M7b gates physical use rather than an orbit-only demo. - -| Milestone | Exit evidence | -|---|---| -| M0 | Decision records identify owners; a minimal shader probe proves channel and sampler behaviour; resource estimates exist | -| M1 | Old noise vectors pass; seeded vectors match across worker counts; release timing printed | -| M2 | Six faces have correct winding, counts, bounds and shared edges; headless and client publication work | -| M3 | One pure sampler drives vertices and queries; mask and signed-depth fixtures pass | -| M4 | Known LUT values render correctly; ocean threshold is fixed; no double colour-space conversion | -| M5 | One-biome and multi-biome fixtures pass; tint edits repaint; biome layout changes publish coherently | -| M6 | Reproducible saved demo, documented command and GIF; idle and face-preview behaviour measured | -| M7a | Recorded traversal crosses all face and LOD edges without holes; constrained-cache teleport retains coverage | -| M7b | Headless moving-body case and replay pass; late collision cannot activate opportunistically | -| M8 | Both VMs expose matching semantics; Studio undo, cancellation and hidden-preview checks pass | -| M9 | Each chosen extension has its own resource estimate, persistence semantics and acceptance evidence | - -Run applicable module suites, architecture/tier checks and `just check` for code -delivery, followed by the repository checklist before a PR. This document edit -does not itself implement those milestones or require engine runtime tests. - ---- - -## Decisions to close before implementation - -These are proposed defaults and required evidence, not permission requests for -this document edit. Investigate each with a bounded probe before asking for an -architectural choice. Ordinary build details should not wait on a human. - -| Decision | Proposed direction | Evidence or approval needed | -|---|---|---| -| Per-body recipe ownership | Reuse the terrain recipe schema for planet instances; retain the world terrain entry point | Resolve the governing plan's one-per-world rule, save identity and authority for multiple bodies | -| Module timing | Pure planet generator joins terrain at L8; a thin demo calls it | Reconcile early roadmap scope with terrain's later planet phase and approve dependency edges | -| Shader policy and transport | Prove fragment ShaderScript first; built-in material if shipping policy requires it | Inspect runtime compilation policy, alpha handling, UV precision and sampler controls | -| Mesh transaction groups | Host-level preflight and indivisible accepted-generation swap | Demonstrate failure of one destination leaves every live destination unchanged | -| Numeric compatibility | CPU canonical generation with a declared supported-platform profile | Compare canonical artifacts; choose explicit quantization if bit-exact parity is not achieved | -| Resolution and byte ceilings | Small fixed chunks, 256-sample full-face preview maximum | Measure preparation, upload, collision and peak overlapping generations | -| Noise period | Preserve existing kernel and use direction-space sampling | Inspect high-octave repetition; wider-period noise, if needed, is a separately versioned terrain mode | -| Large-body coordinates | Local geometry first, explicit tested radius ceiling | Prove render and physics precision before adding chunk-relative origins or advertising planetary walking | -| Physical ocean meaning | Initial clamped sea surface, no submerged gameplay | Separate seabed and water contracts before swimming, underwater placement or buoyancy | -| Collision simplification | Fixed profile with measured radial error bound | Walking/raycast traversal at intended speeds and chunk borders | - -## Completion definition - -The first full quadtree planet delivery is complete when an author can save a -recipe, regenerate it deterministically, orbit across every face and LOD boundary, -edit shape or colour through the appropriate narrow rebuild path, and recover -from cancellation or resource pressure without losing valid coverage. - -It also requires bounded queues and memory, verified seam topology, coherent -mesh/material publication, both-VM parity for exposed APIs, an idle path doing -no generation, and the documented demo plus applicable engine checks. - -Walkable planets additionally require M7b: authoritative collision readiness, -supported precision, consistent accepted revisions and contact tests across -chunk boundaries. Atmospheres, rivers and vegetation cannot substitute for that -evidence. Grug wants ground that stays under feet before adding more clouds. + Clamp only a tiny negative radicand caused by rounding within a validated + cube domain. A materially negative value rejects the request. +- Direction-space sampling is planet-local. Radius, rotation, and translation + do not alter a graph's field identity. Normalize finite nonzero directions at + the request boundary once. +- Every cube edge has a tested neighbor face, neighbor edge, and parameter + reversal. Normals use the same direction-space basis and sample rule across + a seam. Skirts may hide a visual crack but cannot repair a normal or + collision mismatch. + +## Publication and authority + +- Replicate and save the recipe, generator version, and request identity, never + generated mesh bytes. Collision and gameplay artifacts publish only at the + world mutation barrier. +- A request identity includes body name, recipe digest, face, dyadic patch + coordinate, level, output, and epoch. A completed result commits only while + that exact identity is still desired. +- A patch reports a fixed mesh resolution, deterministic bounds, generation + revision, and explicit residency state. Neighbor levels differ by at most + one. Resource admission accounts for samples, layers, octaves, target bytes, + and outstanding requests before allocating. +- Floating origin changes render-space representation only. Body-space graph + inputs, orbit state, saved bookmarks, and canonical recipe bytes remain in + Float64 metres. + +## Required proof + +- Fixed recipe output is identical for body, face, patch, and level across + worker counts. +- All twelve face edges and eight corners preserve positions, normals, and + index ownership. +- Parent and child boundary samples match exactly, stale work cannot publish, + and cancellation releases bounded resources. +- A release scene records patch count, generated bytes, queue age, retained + bytes, visible triangles, and seam failures before any scale claim. diff --git a/docs/future-work/PORTAL-HANDOFF.md b/docs/future-work/PORTAL-HANDOFF.md deleted file mode 100644 index 03a540239..000000000 --- a/docs/future-work/PORTAL-HANDOFF.md +++ /dev/null @@ -1,3108 +0,0 @@ -# Portal handoff - -Updated 2026-09-08. Render work resumed from the committed checkpoint. - -- Objective remains product endpoint discovery and continuous, seamless player crossing. -- Concise status: [ROADMAP](../../ROADMAP.md). Detailed design and evidence: [render plan](RENDER-REFACTOR.md) and [task list](RENDER-REFACTOR-TASKS.md). -- The Terrain BVH change, benchmark job and initial handoff were committed as `cbe7a6ed`. The user subsequently explicitly requested committing all remaining working-tree changes together, including earlier changes of uncertain ownership. - -## Verified work - -- Terrain BVH construction caches centroids, partitions medians and preserves canonical leaf order. Release-derived bench: 8,192 triangles, 984 to 858 microseconds. Full Terrain worker cost remains unmeasured. -- Topology recovery accepts an authenticated current renewal after cache expiry, while retaining request deadlines. Ready topology replies are consumed before camera route selection. -- Product camera matrix passes all 16 variants: 30/60 Hz, first/third person, explicit/automatic Humanoid subject, held/released movement. `topology-ready-camera-matrix.log`: 136,117 assertions. -- Opt-in render-stage probe copies images before later stages overwrite them. Raw pixels, BMPs, metadata and an HTML index are saved. `render-stage-probe-final-gpu.log`: 756 assertions in two cases. -- Probe and topology changes are included with their wider renderer/client dependencies in the full checkpoint. No fresh full-suite validation was run for that checkpoint. - -## Resumed lease retirement - -- `LeaseAdopted` is a bounded claim-only world-bus reply. The destination renews - its retry window and reports completed adoption on repeated lease requests. - The source checks the attempt, endpoint and exact accepted claim before - removing its departure. Its presentation connection is not closed. -- Reproduced both missing behaviors before the server fix: destination still - returned `LeaseRoute`, and source still renewed after adoption. The focused - run failed four assertions in two cases. -- After the fix, codec/lease tests pass 2,660 assertions in seven cases. Server - lease and real-process crossing tests pass 748 assertions in six cases, - including 30/60 Hz and Datagram/QUIC crossings. Source tests hold the old - connection open, reject stale claims and replay the completed adoption reply. -- Full game suite passes 4,124 assertions in 93 cases; full server passes - 1,543 assertions in 76 cases. `test_game`, `test_server` and `server` build, - and changed C++ files pass clang-format 21. Evidence is under - `.cache/build/dev/tests/portal-lease-*.log`. No GPU or release performance - claim accompanies this host-lifetime change. - -## Resumed source observation and content - -- Client adoption now retains one admitted source connection, socket, replica - and content session. Its snapshots keep advancing; gameplay scripts, local - input and prediction are stopped. Old session callbacks only accept content - traffic. The observer retires on link loss, a new successor, departure of both - the eye and visible portal demand from that world, or shutdown. -- Content pumping has one implementation in `ClientContent.cpp`, with explicit - session and world inputs. Active and observed sessions keep separate signed - catalogues, relays and pending requests, sharing one frame intake budget. - Relay callbacks bind their owning connector rather than the replaceable - active connection slot. -- The product content fixture holds the source manifest until destination input - proves adoption, then publishes new texture references in both worlds. Each - admitted route serves exactly one distinct texture bundle. Local fallback and - cached content are disabled. This passes 95 assertions; the initial fixture - failed two assertions because automatic local CDN discovery bypassed its relay. -- Final `client` and `test_client` builds pass. Full headless Client passes - 10,215 assertions in 172 cases. Successor and observation checks pass 3,866 - assertions in five cases; the 30/60 Hz product image handoff passes 17,098 - assertions in one case. Logs are `portal-observer-*.log` under the test build. - Selected PNGs and metadata live in `portal-observer-evidence/`; inspected - outbound 30 Hz and return 60 Hz adoption frames show the body and world floor. -- This slice does not select a new local eye renderer. Complete per-world - presentation preparation and same-name asset isolation across publishers - remain open. The texture fixture uses distinct names. Moving-camera parity, - release profiling, sanitizers and interactive Studio were not rerun here. - -## Shared world and camera packets - -- `render/WorldView.hpp` now owns the shared collection boundary used by the - portal producer. One world packet copies the published pose, joint palette, - lighting, surface slots, seams, portals and detached particle inputs. It does - not rebuild replica transforms or run presentation again. The packet cannot - be copied because its particle batches refer to its own detached arrays. -- Ready cameras collect their own light selection, facing ribbons, spatial GUI - commands and canvas placements. Waiting nested captures keep the existing - preparation gate. `InterfacePass` can submit this packet without reopening - the store; another camera cannot replace its billboard placements. The - producer now submits spatial packets after leaving the world. Snapshot byte - accounting includes the copied collector placements. -- New host coverage checks ownership after store destruction, reuse for an - empty destination, published replica poses, light-budget selection, ribbons, - billboard sizing and unchanged active-camera state. The first light fixture - incorrectly expected sorting below the light budget; it was corrected to - exercise camera-dependent selection above the budget. -- Final `test_render`, `client` and `test_client` builds pass. Full headless - render passes 46,592 assertions in 465 cases; full headless Client passes - 10,215 in 172. Device-backed `[portal-runtime]` passes 24,161 assertions in - 18 cases, covering complete layers and requested-camera captures. Evidence: - `world-view-final-build.log`, `world-view-final-host.log`, - `world-view-client-host.log` and `world-view-final-gpu.log` under the test build. - Formatting and whitespace checks pass. The producer build still reports - existing missing-field-initializer warnings. No sanitizer or release profile - was run for this slice. -- This moves the producer's collection into the engine's shared API. The next - slice below binds the Client's retained source eye; content namespace - isolation and the complete moving-camera image gate remain unfinished. - -## Direct observed-world eye - -- Client now presents its retained source replica and binds its owned world and - camera packets when the eye remains there after player adoption. Geometry and - palettes follow the received pose; lighting, lights, particles, ribbons, - surfaces and spatial UI come from the observed world. The former input world - does not supply those layers. Foreign straddlers keep their source identities - and rebased palettes. -- `WorldViewInterface` routes spatial recording to the observed world's - interface and screen recording to the active player's interface. Its host - checks cover readiness refusal, separate ownership and a shared hook prepared - only once. Captures record `observed_world` and `observed_tick`; product image - walks require a direct observed frame with geometry and no whole-eye image. -- The first product run failed three landmark assertions. At initial adoption, - source-player removal changes body-layer demand to complete-room demand. The - direct path displayed the pane before the replacement capture arrived. It now - retains the admitted eye until the nested image is ready and refuses a failed - presentation phase. The original three-failure log is - `observed-eye-product.log`; this does not establish that every intermittent - landmark loss or the earlier valid-handle black frame has been resolved. -- After the readiness gate, cold 30/60 Hz image handoff passes 16,244 assertions - and warm handoff passes 16,323. The 16-variant 30/60 Hz, first/third-person, - explicit/automatic-subject, held/released-input matrix passes 131,965 - assertions. Logs: `observed-eye-readiness-product.log`, - `observed-eye-camera-matrix.log` (warm only; an incorrect extra filter matched - no cases), and `observed-eye-full-matrix.log`. Full headless Client passes - 10,215 assertions / 172 cases; world-view and interface routing checks pass - 90 / 3. Builds, formatting and whitespace checks pass. -- `observed-eye-evidence/` preserves the failed adoption frames, successful - direct frames, and selected samples from all 20 completed product runs. Bulk - captures were removed. Inspection shows the destination floor and body in the - direct path, but `ready/60-179.png` still shows gray around a retained portal - image. The directly rendered room does not fix parallax inside that image. -- Resource names still share the renderer's process-wide mesh/texture tables. - Per-world shader, editable-resource and viewport-widget preparation also needs - completion. These are explicit limits of the new binding, not completed - foreign-world rendering. No release profile or sanitizer run accompanies it. - -## Admitted local portal producers - -- `UpdatePortalImages` accepts an explicit admitted destination replica. It - must be snapshot-ready, match the authored destination, and differ from the - source. Merely discovering a staged replica preserves the authenticated - remote producer. Host routing coverage passes 33 assertions in one case. -- The observed source eye selects the active admitted replica for its nested - portal. The previous world remains available while either the eye or a - visible demanded portal needs it. Native presentation presents that observer - before selecting it as the local destination producer. Retention stays bounded - to one previous world; new successors and link loss still retire it. -- The earlier gray border in `observed-eye-evidence/ready/60-179.png` used a - remote capture from a different camera. The inspected local-producer image - in `observed-local-evidence/60-182.png` removes that large border. Product - image checks now require the admitted producer, position within 1 mm, and - equivalent rotation for the fixture's identity seam. This does not establish - disocclusion correctness for remote or unadmitted worlds. -- The first local-routing run failed one return landmark assertion: - `observed-local-product.log`, 16,531 / 16,532 assertions. Keeping the observer - while its portal remains visible then passed cold/warm image handoff with - 38,707 assertions in two cases (`observed-visible-product.log`). Full - headless Client passes 10,232 / 172 (`observed-visible-client-host.log`). -- Final validation added the rotation assertion and combined the 16 camera - variants with cold/warm image handoff. It still fails one return-adoption - landmark check: 192,211 / 192,212 assertions, two of three cases pass - (`observed-local-final-product.log`). At 30 Hz cold frame 270, blue pixels - fall from 334 to 132, below the required 167. The whole-eye fallback swaps - remote requests 10 and 11, captured at substantially different camera - positions, before native portal readiness. Frame 271 uses native geometry - and the retained local destination producer. Do not report seamless handoff - as passing or relax the landmark check. All new producer/pose checks pass. -- `observed-local-final-evidence/` preserves PNG/JSON samples from all 20 runs, - including failed frames 268 through 271. Frames 269 and 270 were inspected; - both show the brown source floor and body, with reduced blue floor behind it. - Bulk captures were removed. Builds, formatting and whitespace checks pass. - These are dev, offscreen Vulkan, 128-pixel fixtures. Release profiling, - sanitizers, interactive Studio and `[eye-current-camera]` were not rerun. - -## Current-camera successor presentation - -- Local admitted portal demands now capture the complete world and body - together. `ResidentDestinations` bypasses the delayed body-layer profile, - preserving the requested recursion and pixel budgets. The producer can use - its existing same-device resident image path instead of reading back separate - body layers. Third-person includes the body; first-person retains the selected - account identity. Remote and unrelated destinations keep their prior profile. - Demand coverage passes 1,351 assertions in ten cases. -- Complete local captures fixed the native return camera lag, but did not by - themselves close adoption: `resident-portal-product.log` fails two landmark - checks out of 40,650 assertions. The preceding frame still used a remote eye. -- The Client now uses one `PortalWorldView` packet/preparation path for retained - observers and authenticated successors whose player rig is ready. Both bind - the live eye camera, world lighting, effects and spatial interface. Screen UI - stays with the current input world. The selected packet is borrowed only for - the draw and cleared when its session retires. Captures mark - `observed_successor`, and image tests require actual pre-adoption direct frames - with authenticated readiness and a drawable rig. -- Rendering the successor exposed a second discontinuity. Its replica body was - behind the continued source prediction, so the body grew at adoption and - obscured the floor. `successor-world-view-product.log` fails one of 40,792 - assertions; saved warm 60 Hz frames 246/247 show the size change even though - both portal captures match the live camera. Successor preparation now copies - the authenticated prediction continuation before presentation and refuses an - unsuccessful application. Adoption takes over that same continued pose. -- With continued prediction, cold/warm 30/60 Hz handoff passes 40,831 assertions - in two cases (`successor-prediction-view-product.log`). Inspected warm 60 Hz - frames 244/245 in `successor-prediction-view-evidence/` retain body size and the - blue destination floor. The combined 16 camera variants plus cold/warm handoff - then pass 170,301 assertions in three cases - (`successor-view-final-product.log`). All 20 runs have selected PNG/JSON - evidence in `successor-view-matrix-evidence/`; bulk captures were removed. -- First-person foreign views also resolve their native body identity in the - destination store, while keeping copied source rows separately hidden. This - matters when the authenticated successor and source use different rig IDs. -- Full headless render initially aborted because the empty-particle-world test - implicitly registered `ParticleSystem` before the world-view fixture installed - its stable component name. The ordered two-test reproduction is in - `resident-portal-registration-repro.log`. The empty-world fixture now registers - its accessed effects components first. The formerly failing full-suite seed - passes 46,633 assertions in 466 cases (`successor-view-final-render-host.log`). - Full headless Client passes 10,232 / 172. -- With destination body lookup, all 24 product runs pass 202,963 assertions - in four cases (`successor-view-body-product.log`): the 16 camera variants, - four camera-clear walks and four cold/warm image walks. Selected artifacts - from every run live in `successor-view-body-evidence/`, including 1,186 direct - foreign frames and 163 authenticated successor frames counted in the summary. - Bulk captures were removed. Final warm 60 Hz frames 276/277 were inspected: - body size and the floor persist, but frame 277 has a thin vertical edge above - the body's left side. These landmark checks do not establish pixel-perfect - continuity; that edge still needs attribution. -- The final demand adjustment preserves first-person account selection even - after the source's player row retires. Final builds and format/whitespace - checks pass. Full headless render passes 46,636 / 466, full headless Client - 10,232 / 172, and the device-enabled body/shadow/portal checks 967 / 9. - Logs: `resident-body-selection-build.log`, - `resident-body-selection-render-host.log`, - `resident-body-selection-client-host.log`, and - `resident-body-selection-gpu.log`. The product matrix above precedes only - this final account-selection adjustment; its demand and rendering behavior - are covered by the final host and focused device checks. -- These are dev, offscreen Vulkan, 128-pixel checks. They do not close the remote - moving-camera gate, same-name resource isolation, or per-world shader, - editable-resource, viewport-widget and staged-content preparation. Release - profiling, sanitizers and interactive Studio remain unrun for this slice. - -## Scoped texture residency - -`TextureTable` now keys residency and pending arrivals by content owner and asset -name. The default empty owner preserves the shared namespace. Scoped lookups -never fall back to shared content or another owner. Upload, adoption, replacement, -dimensions, flipbook lookup and removal use the same key. `DropOwner` releases -that owner's textures and cancels its pending arrivals while retaining shared -entries. The existing byte limit remains shared across all owners. - -This initially established the texture table contract only. Client uploads and -render consumers still use the shared namespace. Same-name product asset -isolation requires carrying session ownership through those paths, including -material maps, environment, particles and UI, before this gate can close. - -- Focused host/device checks pass 70 assertions in two cases. They cover same-name - uploads, replacement, adoption, independent pending arrivals, animation and - owner retirement. The first GPU run failed six accounting assertions because - initialization installs a built-in texture; the corrected fixture measures - count and byte deltas from that baseline. Both logs remain available. -- Full headless render passes 46,651 assertions in 467 cases; full headless Client - passes 10,232 in 172. Client, Studio and their test targets build successfully. - Formatting and whitespace checks pass. -- Logs under `.cache/build/dev/tests/`: `texture-owner-gpu.log` records the initial - fixture failure; `texture-owner-final-gpu.log`, - `texture-owner-final-render-host.log`, `texture-owner-final-client-host.log`, - `texture-owner-final-build.log` and `texture-owner-studio-build.log` record the - final checks. No product portal matrix, release profiling, sanitizers or - interactive Studio check was run for this table change. - -## Scoped mesh residency and renderer calls - -`MeshTable` now uses the same owner/name namespace for registration and lookup. -Retiring an owner removes its entries while returning their vertex/index ranges -to the existing deferred reuse queue. Other owners and shared built-ins remain -registered. Missing scoped meshes use the normal fallback instead of another -owner's same-name mesh. - -`Renderer` exposes the owner on mesh/texture upload and lookup operations, pending -texture arrivals and texture removal. `DropContentOwner` retires both tables and -pending arrivals, advancing the resource revision only when something changed. -These calls prepare the product boundary; Client uploads and draw consumers -still need a content-session owner carried through them. Do not close the product -same-name isolation gate from these table/API checks. - -- Mesh host checks pass 301 assertions in 12 cases (`mesh-owner-host.log`), - including independent same-name bounds, replacement, invalid replacement, - scoped absence, retirement and deferred range reuse. -- The first device run failed at renderer initialization in both device cases - (`content-owner-gpu.log`). The built-in fallback lookup still used the old - numeric key; the empty owner's nonzero sentinel made it miss. The lookup now - uses the compound key. Final offscreen Vulkan checks pass 106 assertions in - three cases (`content-owner-final-gpu.log`), exercising both tables through the - renderer and verifying resource revision changes and unaffected owners. -- Full headless render passes 46,682 assertions in 468 cases - (`content-owner-final-render-host.log`). Client passes 10,232 in 172 - (`content-owner-client-host.log`, before the final fallback-lookup correction). - Client, Studio and their test binaries build successfully - (`content-owner-final-build.log`). This build reports existing initializer - warnings in portal runtime/tests and Client replication, plus a structured - binding copy warning in PortalImageImport tests. These files were not changed - by the mesh/renderer ownership slice. Formatting and whitespace checks pass. -- Product portal walks, interactive Studio, sanitizers and release profiling - were not rerun for this slice. Next, attach a session-owned namespace to view - preparation and carry it through mesh/submesh material bindings, skybox, - particle/ribbon and UI texture lookup before migrating Client uploads. A - publisher key alone is insufficient because one publisher can serve distinct - manifests with the same authored names. - -## Draw-time content bindings - -`View` now carries a native content owner and explicit foreign-world owner -bindings. Authored resource names and `DrawInstance::SourceWorld` remain intact. -The unloaded-mesh filter passes the complete source row to its residency test; -mesh lookup, draw metadata and material texture lookup select that row's owner. -Draw runs split when owners differ even when their mesh pointer and texture name -match. Built-in meshes and the built-in checker keep shared residency. - -Native environment, particle and ribbon texture bindings use the active view's -content owner. Owner/world bindings and resource revision changes invalidate -retained object metadata and force scene work, even if the caller supplied a -quiet-frame damage mask. Client content-session assignment, UI callbacks and -foreign packet binding still need wiring before the product isolation gate can -close. No resource names are rewritten in ECS storage or serialized as ids. - -The first scoped image fixture caught a quiet-frame integration fault: view -preparation marked the new bindings dirty, but node registration still read the -original damage mask and installed idle handlers. Registration now reads the -prepared request. The initial failure is retained in `content-binding-gpu.log`; -the corrected run passes 184 assertions (`content-binding-fixed-gpu.log`). - -Final evidence: - -- The scoped fixture now compares rendered albedo against distinct-name reference - images for shared built-in geometry and named meshes with submesh textures. - It checks native/copy binding, a native owner swap, a foreign-only owner swap - under a quiet damage mask, and retirement that removes only the absent mesh. - The final focused run passes 240 assertions (`content-binding-foreign-gpu.log`). -- The broader offscreen Vulkan camera/resource/particle sweep passes 8,397 - assertions in 13 cases (`content-binding-final-gpu.log`). It precedes only the - final foreign-only fixture extension; renderer code did not change afterward. - Native environment/particle/ribbon scope plumbing is present, but those paths - do not yet have the same owner-specific pixel proof as object albedo. -- Full headless render passes 46,682 / 468, scene 518,302 / 550 and Client - 10,232 / 172 (`content-binding-final-{render,scene,client}-host.log`). The focused - source-world filter suite passes 151 / 29 (`content-binding-scene-host.log`). -- Client, Studio and all affected test targets build - (`content-binding-final-build.log`). A new test initializer warning was removed; - `content-binding-test-build.log` and `content-binding-foreign-build.log` are clean. - The broader build retains initializer warnings in game PortalSession and Client - Replicated code outside this slice. Formatting and whitespace checks pass. -- Product content-session wiring, spatial/screen UI callbacks, staged content, - per-world shaders/editable resources/widgets, the full portal matrix, release - profiling, sanitizers and interactive Studio remain open. These renderer - fixtures do not prove end-to-end same-name product asset isolation. - -## Portal capture content owners - -Local portal producers now accept a native content owner and copied foreign-world -bindings. `PortalImageHost::SetContentOwner` configures existing producers and -producers opened later; removing a world or clearing the host retires its binding. -Both the camera preparation and capture draw use those owners. Spatial UI image -lookup uses the producer's native owner, including dimensions and flipbook cells. -Bindings contribute to the portal content revision, so changing an owner without -uploading an asset still prevents renewal of the preceding content version. - -Renderer mesh/texture lookup APIs now resolve built-in assets through shared -residency, matching the draw path. Ordinary scoped names retain strict lookup. -Client uploads and session-to-view/UI assignment remain shared until they are -migrated together; this producer adapter is a prerequisite for that migration. - -The spatial image fixture reproduced an additional renewal defect: when UI was -the only visible layer, texture replacement, owner changes and flipbook frames -changed pixels without changing `ContentRevision`. `ScenePresentationSignature` -deliberately excludes UI. The producer now folds resource and animation inputs -into the complete capture revision as well, leaving the scene-layer contract -unchanged. The failing run recorded ten assertions in -`portal-content-owner-final-gpu.log`; the earlier mesh-only run passed 319 -assertions in `portal-content-owner-gpu.log`. - -- Final offscreen Vulkan checks pass 1,006 assertions in five cases - (`portal-content-owner-renewal-gpu.log`). The portal fixture covers direct and - hosted producers with ordinary surfaces and spatial image labels. It checks - owner switches without asset writes, texture replacement/removal/restoration, - flipbook advancement, configuration before producer creation and binding - retirement. Changed-image requests carry the previous known version and must - return fresh pixels instead of a renewal. Renderer binding and built-in lookup - checks are included in that run. -- Full headless render passes 46,682 / 468 - (`portal-content-owner-signature-host.log`). Client passes 10,232 / 172 - (`portal-content-owner-final-client-host.log`, before the final complete-capture - signature correction). Client, Studio and their test targets rebuild - (`portal-content-owner-signature-build.log`); the final known-version test-only - extension builds in `portal-content-owner-renewal-build.log`. Existing missing - initializer warnings remain in portal runtime/test and Client replication code. - Formatting and whitespace checks pass. -- No product portal matrix, release profiling, sanitizers or interactive Studio - check was rerun. Client session assignment, owner-scoped delivery, editable - uploads and main/observed UI callbacks remain the next integration work. - -## Editable resource upload scopes - -Editable image and mesh uploaders accept a content owner and track revisions by -store identity, owner and entity handle. Generated editable names contain the -entity handle, which can repeat in another world. Callers must assign distinct -owners to those worlds even when they share a delivery session. Alternating -between prepared worlds preserves each scope's upload stamps. - -`ForgetWorld` and `ForgetOwner` retire upload stamps explicitly; they do not -release GPU resources. The renderer's existing owner retirement controls device -lifetime. Existing product calls retain the shared owner default until Client -assignment, lookup and retirement migrate together. - -- Offscreen Vulkan checks pass 54 assertions in two cases - (`editable-owner-gpu.log`). They cover colliding entity handles and content - names, distinct mesh bounds/image dimensions, unchanged refreshes, changed - image revisions, world cache retirement, owner cache/device retirement and - rebinding to another owner. -- Full headless render passes 46,681 assertions in 468 cases - (`editable-owner-host.log`). The render target builds in - `editable-owner-build.log`. -- Client host checks pass 10,232 assertions in 172 cases - (`editable-owner-client-host.log`). Client, Studio and their test targets build - without warnings in `editable-owner-consumers-build.log`. Only header comments - changed after that build. Formatting and whitespace checks pass. -- No product portal matrix, release profiling, sanitizers or interactive Studio - check was run for this slice. These uploader contracts do not establish - end-to-end Client asset isolation. - -## Portal editable preparation - -Portal producers now refresh editable images and meshes in their native content -owner before collecting the world and checking capture revisions. Preparation -runs once for the demanded capture batch. Each producer keeps its own upload -stamps; changing its owner or clearing the producer retires those stamps without -releasing resources owned by other views. - -The device fixture reproduced the missing preparation before the change: all -four direct/hosted and ordinary/spatial image variants returned a capture with -no editable texture in the configured owner (`portal-editable-before-gpu.log`, -four failed assertions out of 224). The first implementation run passed the -image variants, including known-version requests after edits. Its mesh pixel -check failed twice (`portal-editable-gpu.log`) while scoped upload, changed -bounds and changed capture revisions passed. The mesh fixture now changes its -shape at fixed bounds and includes both face windings. - -- Final offscreen Vulkan checks pass 1,386 assertions in four cases - (`portal-editable-lifetime-gpu.log`). They cover scoped editable image/mesh - preparation, no repeated uploads on unchanged captures, changed pixels and - revisions after edits, known-version replies, image owner rebinding and - producer clearing/reopening. Existing upload-owner and draw-binding checks - are included. -- Full headless render passes 46,681 assertions in 468 cases - (`portal-editable-final-host.log`). Client, Studio and their test targets - rebuild (`portal-editable-final-build.log`); existing missing-initializer - warnings remain in portal runtime and test code. The final test-only lifetime - extension builds in `portal-editable-lifetime-build.log`. Formatting and - whitespace checks pass. -- No product portal matrix, release profiling, sanitizers or interactive Studio - check was rerun. Per-producer preparation is still outside graph execution; - the graph-owned residency requirement remains open. - -Client delivery ownership and staged content remain open. Preparing staged -uploads in the current shared namespace would allow successor assets to replace -source assets, so the content pump must migrate with its view/UI bindings. -Per-world shader and viewport-widget preparation also remain open. - -## Client world residency bindings - -Client uses each local world's name as its mesh/texture residency owner. Delivery -decodes once and uploads to the worlds served by that content route. Pending -texture markers follow the same owners. Adding a served world replays demand for -its missing resident copies and catalogue facts while preserving outstanding -requests; removing a served world clears its pending markers. - -Native and copied-world views, main/observed image callbacks, portal producers -and main viewport widgets use those bindings. Editable preparation runs before -interface compilation and separately for observed/staged world packets. Dropping -a portal replica retires its upload stamps and renderer owner. Authored replica -names also map to their local residency names for copied rows. - -A staged successor now owns a content client and relay before adoption. Its -directory and content replies are consumed while it is staged, and its intake -shares the frame budget with the active and retained source routes. Adoption -moves that content session with its existing connection instead of rebuilding -it. Retry destroys the content borrower before the old connection. - -- The broader product run passes 30,694 assertions in two cases / three crossing - runs (`client-world-owner-final-product-gpu.log`): the new editable room-colour - fixture at 60 Hz and the existing warm-image fixtures at 30/60 Hz. Both legs, - source retention and staged eye drawing are exercised. These are offscreen - Vulkan dev runs; the full product matrix was not rerun. -- Final review connected observed editable uploads to the Client resource-change - flag, matching main-world preparation. The final textured product repeat passes - 10,349 assertions (`client-world-owner-observed-gpu.log`) and Client headless - remains 10,232 / 172 (`client-world-owner-observed-host.log`). Client/Studio and - their tests rebuild in `client-world-owner-observed-build.log`. Textured captures - now have a separate `-warm-owned` directory suffix; the earlier artifact-only - repeat passed 10,329 assertions (`client-world-owner-artifact-gpu.log`). -- Viewport/resource device checks pass 368 assertions in four cases - (`client-world-owner-viewport-final-gpu.log`). The viewport fixture compares - same-name scoped textures to separate-name reference images, including an - owner switch in the same scene slot. -- Full Client headless passes 10,232 / 172 (`client-world-owner-final-host.log`); - render headless passes 46,681 / 468 (`client-world-owner-render-host.log`). - Client, Studio and affected tests build; the broader implementation build is - clean (`client-world-owner-final-check-build.log`). Formatting and whitespace - checks pass. -- Failed development evidence is retained. The first product fixture used - `TextureID` on a Part instead of a MeshPart (`client-world-owner-product-gpu.log`). - The next oracle incorrectly expected the source colour even when its sampled - camera ray crossed the portal first (`client-world-owner-meshpart-gpu.log`, - 19 colour assertions). The corrected oracle intersects the captured camera ray - with the aperture and floor (`client-world-owner-oracle-gpu.log`, 10,373 passed, - before the final pending-marker bookkeeping adjustment). The viewport fixture - needed renderer warm-up and separate-name reference images instead of assumed - raw primary channel values (`client-world-owner-viewport-gpu.log`). - -Same-name published-asset delivery and failure/retirement still need end-to-end -proof. Shaders remain shared; foreign viewport-widget preparation and graph-owned -residency remain open. No release profiling, sanitizers or interactive Studio -verification was run. The per-world copies and full binding list are correctness -plumbing, not a claim of minimal residency or cache invalidation cost. - -## Published texture ownership proof - -The existing retained-route fixture passes on the current Client (96 assertions -in `published-owner-baseline.log`). Its new rendered variant uses the same -texture name in two distinct manifests signed by one publisher identity. A -destination wall references its texture before adoption. The fixture holds the -commit reply until the destination bundle is served, so delivery must progress -while the successor is staged. The source manifest remains withheld until -destination input proves adoption, then the retained source asks for its texture. - -The final captured frame must report two accepted texture arrivals, a native -destination view with its destination content owner, and blue destination pixels -after the source's red texture arrives. Each route requests its bundle exactly -once. This checks actual signed delivery and Renderer uploads, not only a table -API or a served network reply. Capture JSON now includes `content_owner`, -`delivered_meshes` and `delivered_textures`; the latter two count accepted asset -arrivals, not GPU upload operations or live resources. - -- Final offscreen Vulkan dev run: 210 assertions in two product cases - (`published-owner-final-gpu.log`). The first rendered run with staging enforced - passed 110 assertions (`published-owner-staging-gpu.log`), before the accepted - asset metadata and exact request-count assertions were added. -- Client, Studio and their test targets build without warnings - (`published-owner-final-build.log`). Formatting and whitespace checks pass. - No broad headless suite was rerun for this test/diagnostic-only change. -- The first rendered launch mistakenly removed `--headless`, causing an early - signal exit under the offscreen driver (`published-owner-gpu.log`). Restoring - the Client's existing headless render mode corrected the fixture. This was - not diagnosed or reported as a renderer defect. -- The final image and JSON sequence is `portal-published-owner-frames/` under - `.cache/build/dev/tests/`. Published mesh isolation, failed delivery and owner - retirement still need product proof. Shader isolation and graph-owned - residency remain open. No release profiling, sanitizers or interactive Studio - check was run. - -## Published mesh, refusal and per-owner demand - -The rendered delivery fixture now includes same-name meshes. The destination -publishes a blue quad and the late source publishes a red triangle with the same -bounds. Refusal variants serve the destination normally and refuse the source -bundle after adoption. The final frame must keep destination pixels, report only -the accepted assets, retain the source world and have no pending content requests. -The new `pending_content` capture field sums issued/pending asset requests across -active, staged and retained content routes; `retained_world` records that world's -local name even while the native destination is drawn. - -The wider run reproduced a timing defect in Client demand history. When the -destination asset completed while staged, adding the local world at adoption -cleared the session's entire `Asked` set and fetched the destination asset again. -The failing run recorded six assertions across texture success/refusal variants -(`published-mesh-refusal-gpu.log`), including two bundle requests and excess -accepted asset arrivals. Earlier runs had moved still-pending requests and missed -this ordering. - -Attempts are now keyed by owner and asset name. New worlds get catalogue facts -and their own demand scan without invalidating existing worlds' history. Pending -requests are coalesced and marked for their current owners. A later local-world -reference still requests an already-delivered name when that world lacks its own -copy. The fixture delays commit acknowledgement by 200 ms after serving the -destination bundle to force the completed-before-adoption ordering; a separate -variant creates its local reference three seconds into the run and requires the -second request to occur afterward. - -- The first corrected sweep passes 584 assertions in three cases / five product - runs (`published-owner-demand-gpu.log`). Full headless Client passes 10,232 / 172 - (`published-owner-demand-host.log`). Client, Studio and their tests rebuild - (`published-owner-demand-build.log`); the strengthened test fixture builds in - `published-owner-demand-test-build.log`. Formatting and whitespace checks pass. -- Final bounded sweep passes 680 assertions in four cases / six product runs, - including the existing retained-route case (`published-owner-bounded-gpu.log`). - The capture-cadence test change builds in `published-owner-bounded-build.log`. -- Capture transitions and final frames are retained in - `portal-published-owner-{10,11,12,13,14}-frames/`; bulk frames were removed. - The fixture now uses `--uncapped --max-fps 60` to bound subsequent capture output. -- GPU owner retirement, shader isolation and foreign viewport-widget preparation - remain open. These checks do not establish graph-owned residency or minimal GPU - copies when a new world needs an existing asset. No release profiling, - sanitizers or interactive Studio check was run. - -## Submitted-draw owner retirement - -The existing native/copied owner fixture now retires the source owner immediately -after submitting a draw, before its readback wait. The submitted image still -matches the two-owner reference. The next quiet view removes the retired mesh, -and reloading the same owner restores the reference without explicit damage. -Twelve retire/reload cycles preserve the other owner's texture handle and pixels. -Each retirement releases one four-byte texture in the logical GPU counters; -texture residency returns to its preceding level after reload, and mesh buffer -bytes remain flat after four warmup cycles. - -- Final Vulkan offscreen checks pass 1,283 assertions in 16 cases, including the - existing texture-owner and mesh-table checks (`owner-retirement-final-gpu.log`). -- Full headless render passes 46,682 assertions in 468 cases - (`owner-retirement-host.log`); build passes (`owner-retirement-final-build.log`). -- The first attempt failed because an unchanged restored view correctly skipped - its next draw (`owner-retirement-gpu.log`, 692 passing assertions and one failure). - The fixture now explicitly requests that submission, then clears damage before - retirement to preserve the invalidation check. No production fix was needed. -- These are renderer device checks, not Client-driven teardown proof. Submitting - before retirement does not guarantee the tested GPU was still executing at the - moment of release. Delayed-completion stress, driver heap commitments, complete - world teardown and graph-owned residency remain unproven. No release profiling, - sanitizers or interactive Studio run was performed. - -## Client observation expiry and texture retirement - -The published-content fixture now also closes the source UDP transport one -second after replying with its late texture. The successor connection keeps -running while the retained source times out. Capture metadata records logical -GPU live/buffer/texture bytes, texture count and cumulative released bytes. -These counters exclude driver heap commitments and include capture transfers. - -The first offscreen product check passes 123 assertions -(`client-owner-retirement-gpu.log`). Both same-name textures arrive before -expiry. The observed transition reduces residency from 47 textures and -19,661,832 texture bytes to 46 textures and 19,661,828 bytes. The final frame keeps -the successor owner and blue pixels. The final assertions require exactly one -four-byte texture to disappear, unchanged buffer bytes and at least one second -of successor rendering after the last retained-world capture. Both content -routes request their bundle once and the final pending request count is zero. - -Full headless Client checks pass 10,232 assertions in 172 cases -(`client-owner-retirement-host.log`). Client and test builds pass in -`client-owner-retirement-build.log`; the tightened fixture builds in -`client-owner-retirement-final-build.log`. The final device sweep passes 357 -assertions in two cases / three product runs, covering retained texture/mesh -owners beside texture expiry (`client-owner-retirement-final-gpu.log`). Transition -and final captures remain in `portal-published-owner-{10,11,15}-frames/` under the -build's `tests/` directory; bulk frames were removed. - -This covers Client-driven observation expiry for published textures. Product mesh -range reclamation, staged cancellation with resident assets, repeated world -teardown, delayed GPU completion and shader ownership still need proof. It does -not establish graph-owned residency or driver memory release timing. - -## Owner-scoped shader compiler cache - -`ShaderLibrary` now accepts a residency owner on material/lens refresh and lookup. -Each module key includes its owner, and a refresh removes stale demand only from -that owner's module family. Alternating worlds can retain independently accepted -SPIR-V under the same name without recompiling unchanged sources. Failed edits -retain only that owner's accepted code. Scoped misses never borrow shared modules. -`DropOwner` removes both families and reports their removed names through the -changed lists; the empty owner preserves the shared namespace. - -Headless shader checks pass 550 assertions in 16 cases -(`shader-owner-library-tests.log`). New checks cover both families, alternating -same-name worlds, steady refresh, shared/scoped separation, failed edits, empty -demand, re-demand after eviction and owner retirement. The initial build caught -a Catch expression needing parentheses (`shader-owner-library-build.log`); -the test expression was corrected. Client, Studio and both test binaries build -(`shader-owner-library-final-build.log`). Full headless render passes 46,768 -assertions in 469 cases (`shader-owner-library-host.log`), and Client passes -10,232 in 172 (`shader-owner-library-client-host.log`). Formatting and diff checks -pass. No device run or release profile was added for this host-cache change. - -These compiler-cache checks alone do not establish device isolation. The material -and Client migration below uses this contract. Interface and postprocess -device isolation, Studio migration, product shader isolation, graph-owned -preparation and cooked-only migration remain open. - -## Material shader device ownership and Client cache migration - -Renderer material variants now use owner/name keys for registration, replacement, -lookup and removal. Native and copied draw runs resolve through their existing -slot content owner, including HDR opaque and transparent portal draws. A missing -scoped variant uses the engine default, never a shared same-name variant. -`DropContentOwner` releases that owner's material variants after the existing -frame wait and invalidates quiet views while preserving other owners. - -Client now refreshes and queries compiler modules under the presented world's -residency name, uploads material variants into that namespace and drops compiler -entries when a portal replica retires. Returning to a cached owner preserves its -unchanged material pipelines. Interface, lens and postprocess device slots are -still shared, so an owner switch explicitly restores their selected programs -from that owner's cache. This is not simultaneous foreign-view shader isolation. -Shader preparation still runs only for the presented world. - -The offscreen Vulkan device sweep passes 1,350 assertions in five cases -(`shader-owner-device-reference-gpu.log`). Same-name constant-colour programs are -compared with distinct-name references through portal draws, in both opaque and -transparent modes. Checks cover owner swaps on quiet views, replacement, refused -empty replacement, individual shader removal, strict scoped fallback, restoration -and surviving pixels after complete owner retirement. The earlier retirement -reference was stale because the fixture did not request a draw after changing -its instance span: two checks failed out of 1,352 -(`shader-owner-device-final-gpu.log`). Explicit reference damage fixes the fixture; -the subsequent retirement still relies on automatic resource invalidation. - -Client, Studio and both test binaries build (`shader-owner-device-final-build.log`, -`shader-owner-client-cache-build.log`); the corrected device fixture builds in -`shader-owner-device-reference-build.log`. Headless render passes 46,768 assertions -in 469 cases (`shader-owner-device-host.log`). No release profiling, delayed-GPU -stress, sanitizer or interactive Studio run was added. Native deferred custom -material coverage and product same-name shader crossing still need explicit proof. - -The remaining shader work includes owner-scoped interface/postprocess device -consumers, preparation for retained/staged/foreign worlds, Studio migration and -product shader lifecycle checks. Those are required before the resource ownership -gate can close. - -Final Client headless checks pass 10,232 assertions in 172 cases -(`shader-owner-client-cache-host.log`). The owned editable-room round trip and -published-texture observation expiry pass 10,493 assertions in two offscreen -product cases (`shader-owner-client-cache-gpu.log`). These establish compatibility -with the cache migration, not product custom-shader isolation. Transition/final -frames remain in `portal-client-walk-60-third-explicit-held-clear-image-frames-warm-owned/` -and `portal-published-owner-15-frames/`; bulk captures were removed. Formatting and -diff checks pass. - -## Lens shader device ownership - -Lens registration, lookup and removal now include the residency owner. The -`shader-lenses` node selects each pipeline with its recorded view's content owner, -so two views sharing a shader name can execute different programs in one frame. -There is no shared-name fallback for a scoped miss. Whole-owner retirement also -releases lens pipelines through the existing frame-wait boundary. - -Client uploads and removes lens programs under the presented world's owner. -Returning to an unchanged owner does not rebuild its accepted lens pipelines; -changed modules and missing device entries still upload. The compiler cache and -material/lens device tables now agree on that namespace. Interface and postprocess -device isolation, foreign-world preparation and Studio migration remain open. - -Offscreen Vulkan checks pass 620 assertions in three cases (`lens-owner-gpu.log`). -The new two-view case verifies distinct same-name outputs, quiet owner swaps, -refused empty replacement, successful replacement, individual removal, strict -scoped misses, restoration and surviving pixels after owner retirement. The sweep -also includes material shader ownership and the existing portal check proving -opaque lighting is unaffected by later lenses. Headless render passes 46,767 -assertions in 469 cases (`lens-owner-host.log`). Headless Client passes 10,232 -in 172 (`lens-owner-client-host.log`). Client, Studio and both test binaries build -(`lens-owner-build.log`); formatting and diff checks pass. - -These checks prove native view/lens pipeline ownership on the tested device. -Product same-name lens crossing and preparation for retained/staged/foreign views -remain unproven. No release profiling, delayed-GPU stress, sanitizer or interactive -Studio run was added. - -## Postprocess device ownership - -Postprocess selection now keeps one shader/pipeline pair per residency owner. -The tonemap node selects from its recorded view's exact owner, with the engine -tonemap as fallback. Shared grades cannot fill scoped misses. A successful -replacement waits before releasing that owner's old pipeline; failed replacement -keeps the accepted program. Clearing a selection and whole-owner retirement both -preserve other owners. The plain-tonemap portal preview branch is unchanged. - -Client sets, queries and clears the presented owner's postprocess slot. Returning -to a cached unchanged grade keeps its device pipeline. The remembered selection -used by presentation signatures follows the current owner's device slot. Portal -producer clock invalidation also queries its own owner rather than the shared -selection. The Client owner field is now named `LastShaderOwner`, since it covers -material, lens and postprocess preparation. - -Offscreen Vulkan checks pass 823 assertions in four cases -(`postprocess-owner-gpu.log`). The new two-view case verifies distinct same-name -grades, quiet owner swaps, refused empty replacement, successful replacement, -clear/fallback, restoration and surviving output after owner retirement. The -sweep also covers lens/material ownership and the existing portal lens boundary. -Headless render passes 46,768 assertions in 469 cases -(`postprocess-owner-host.log`). Client, Studio and both test binaries build in -`postprocess-owner-build.log`. The Client owner-field rename builds in -`postprocess-owner-client-build.log`; final headless Client checks pass 10,232 -assertions in 172 cases (`postprocess-owner-client-host.log`). Formatting and -diff checks pass. - -Interface shader device ownership, foreign-world preparation, Studio migration -and product same-name shader/grade crossing remain open. These device checks do -not prove complete foreign-view preparation or the full render refactor. No -release profiling, delayed-GPU stress, sanitizers or interactive Studio run was -added. - -## Screen interface shader ownership - -`InterfacePass` screen shader variants now use owner/name keys. `SetContentOwner` -selects the submitted world's namespace without rebuilding geometry; callers -invalidate their interface image when switching owners. Scoped misses use the -pass default rather than shared same-name variants. Registration, replacement, -lookup, individual removal and whole-owner retirement all preserve other owners. - -Client selects the presented interface world's owner and uploads changed or -missing screen shader variants into that namespace. Returning to a cached owner -keeps its accepted pipelines. Replica retirement drops that owner's interface -variants beside compiler and renderer resources. Direct portal packets and portal -producer interface passes also receive their content owner at submission. - -The Vulkan device sweep passes 953 assertions in four cases -(`interface-owner-gpu.log`). A real screen rectangle checks distinct same-name -programs, owner switching with zero geometry upload, refused empty replacement, -successful replacement, strict fallback, restoration and retirement. The sweep -includes material, lens and postprocess ownership. Headless render passes 46,768 -assertions in 469 cases (`interface-owner-host.log`). Client, Studio and both test -binaries build (`interface-owner-build.log`). Final headless Client checks pass -10,232 assertions in 172 cases (`interface-owner-client-host.log`). Formatting and -diff checks pass. - -Spatial interface rendering currently uses fixed pipelines and does not select -custom `DrawCommand::Shader` variants. Screen ownership does not close that gap. -Custom spatial shader support, foreign-world shader preparation, Studio migration -and product same-name shader crossing remain open. No release profiling, -delayed-GPU stress, sanitizers or interactive Studio run was added. - -## Spatial interface shaders and fragment clipping - -The interface owner fixture reproduced ignored spatial shader selection: red and -green programs produced identical spatial output, with two failed checks out of -266 (`spatial-shader-missing-gpu.log`). Shader registration now builds a coherent -set of screen, depth-tested spatial, always-on-top spatial and supported HDR -variants. `RecordWorld` selects the owner-scoped variant for its target and depth -mode. Partial pipeline creation is refused without replacing the accepted set; -replacement, owner retirement and shutdown release every variant. - -A stronger clipping check reproduced a second defect. Both default and custom -interface shader creation declared zero fragment uniform buffers even though the -fragment shader reads the collector clip block. Screen GPU scissors concealed -the omission; spatial pixels outside the clip remained green. The probe records -outside green `(0,255,0)` against background `(23,15,13)` in both spatial modes -(`spatial-shader-clip-probe-gpu.log`). Both creation paths now declare one fragment -uniform buffer, matching the pushed clip data and shader interface. Header and -implementation comments describe that contract. - -Final offscreen Vulkan checks pass 1,382 assertions in five cases -(`spatial-shader-clip-binding-gpu.log`). Screen and display-format spatial modes verify -distinct same-name output, ownership/lifetime, geometry reuse and actual inside/ -outside clip pixels against a background frame. The sweep includes material, -lens, postprocess and the existing portal lens boundary. This checkpoint originally -called those spatial checks HDR. That was incorrect: `DefaultPbrDocument` writes -the transparent pass to display-format `display`. The follow-up below adds the -missing HDR execution proof. -Headless render passes 46,768 / 469 (`spatial-shader-host.log`) and Client passes -10,232 / 172 (`spatial-shader-client-host.log`). Client, Studio and both test -binaries build (`spatial-shader-clip-binding-build.log`). The owned editable-room -portal round trip passes 10,365 assertions in one product case -(`spatial-shader-client-gpu.log`); this is compatibility evidence, not product -custom-shader crossing proof. Transition and final captures remain in -`portal-client-walk-60-third-explicit-held-clear-image-frames-warm-owned/`; bulk -frames were removed. Formatting and diff checks pass. - -Fixture corrections are retained in the evidence: the first attempt aborted on -late GUI component registration (`spatial-shader-repro-gpu.log`); registration now -precedes the screen section too. The initial clip edit used a nonexistent Rect -field (`spatial-shader-clip-build.log`); its accidentally executed older binary -is recorded as `spatial-shader-preclip-old-binary-gpu.log` and is not clip proof. -The corrected clip probe compiled before the reported binding failure and fix. - -Foreign-world shader preparation, Studio migration and product custom-shader -crossing remain open. These checks do not establish graph-owned preparation, -minimal pipeline residency, delayed-GPU safety or release performance. No -sanitizer or interactive Studio run was added. - -## Interface target formats and depth modes - -The owner fixture now runs screen, depth-tested spatial and always-on-top spatial -sections through both `DefaultPbrDocument` and `DefaultWorldHdrDocument`. It asserts -the authored `display` resource is respectively RGBA8_SRGB or RGBA16F. The existing -pixel checks cover clipping, same-name owner isolation, accepted replacement, -refused replacement, retirement and zero geometry upload on owner changes in all -six combinations. A foreground wall additionally proves depth-tested UI is hidden -while always-on-top UI remains visible at the same sample. - -Offscreen Vulkan passes 1,959 assertions in five cases -(`interface-format-depth-gpu.log`), including the material, lens, postprocess and -portal lens boundary checks. The test target builds -(`interface-format-depth-build.log`); formatting and diff checks pass. Only the -fixture and checkpoint documents changed, so the earlier headless and product -runs were not repeated. This closes the spatial target-format evidence gap, not -product custom-shader crossing or foreign shader preparation. - -Preparation tracing confirms Client still refreshes shaders only for its main -presentation world. Sharing that work with retained/staged views and portal -producers must account for independently retained InterfacePass pipelines: a -consumer can miss another consumer's ephemeral `ShaderLibrary::Changed` list. -Source revision alone is insufficient across source replacement and store reuse. -The next checkpoint implements persistent accepted-program identity and interface reconciliation. Shared world preparation is still incomplete. - -## Independent interface shader preparation - -`ShaderModule::CodeHash` identifies accepted SPIR-V bytes, including built-ins. -It is computed when words are accepted, retained on a failed edit and cleared -when no accepted program remains. Source replacement, store reload and identical -revisions cannot make different accepted words compare equal by revision alone. -The existing host source-identity and reload cases now check this identity. - -`InterfacePass::RefreshShaders` reconciles GUI demand against the shared library's -current accepted modules. Each pass retains its own accepted and attempted hashes. -Unchanged accepted programs reuse pipelines; failed device attempts retain the old -pipeline and are not retried for the same words. Demand removal or missing source -retires only that consumer's owner-scoped variants. Client GUI preparation uses -this path each frame, replacing its changed-list-driven interface upload block. -Material, lens and postprocess preparation still use the existing Client path. - -The GPU fixture drives two independent interface consumers, clearing the library's -changed list before the delayed consumer prepares. Both receive the edited pixels. -Fresh consumer demand, steady reuse, failed source edits, demand removal, redemand -and source deletion are checked through screen, depth-tested and always-on-top -placements in display and HDR graphs. The final Vulkan sweep passes 2,631 / 5 -(`interface-shared-preparation-final-gpu.log`). Headless render passes 46,802 / 469 -and Client 10,232 / 172 (`interface-shared-preparation-host.log` and -`interface-shared-preparation-client-host.log`). Client, Studio and both test -binaries build (`interface-shared-preparation-checked-build.log`). The first build -caught a missing ContentHash include; no test was run against that failed build. - -The owned editable-room product round trip passes 10,290 assertions -(`interface-shared-preparation-client-gpu.log`). This remains compatibility -evidence rather than a custom-shader crossing test. Transition and final frame -pairs are retained in the owned-roundtrip directory; bulk captures were removed. -Formatting and diff checks pass. Device-pipeline creation failure caching has not -received fault-injection coverage. No release profiling, sanitizer or interactive -Studio check was run. - -Next: share material/lens/postprocess preparation with retained/staged worlds and -portal producers, using accepted identities rather than ephemeral change lists. -Their independently owned interface passes can now reconcile the shared modules, -but those foreign-world preparation calls are not wired yet. Graph ownership and -published shader delivery remain required by the full refactor plan. - -## Idempotent device shader registration - -Material variants, lens pipelines and postprocess selections now retain the hash -of their accepted words. Registering the same owner, name and words succeeds -without rebuilding pipelines, waiting for a submitted frame or advancing the -renderer resource revision. Different programs still take the existing atomic -replacement path. Hashes are published only with accepted pipelines and retire -with their owner. Lens pipeline storage now keeps the handle and hash together; -draw lookup, shutdown and owner retirement use that same entry. - -The owner fixtures explicitly check unchanged resource revisions after repeated -material, lens and postprocess registration. Existing replacement, refusal, -strict owner lookup and retirement pixel checks remain in the sweep. Offscreen -Vulkan passes 2,639 assertions in five cases (`shader-device-identity-gpu.log`). -Headless render passes 46,802 / 469 and Client 10,232 / 172 -(`shader-device-identity-host.log`, `shader-device-identity-client-host.log`). -Client, Studio and both test binaries build (`shader-device-identity-build.log`). -Formatting and diff checks pass. No release timing, sanitizer or interactive -Studio check was added; no speedup is claimed from these correctness checks. - -The next implementation still needs to consolidate the Client's shader loop and -invoke preparation for retained/staged views and portal producers. Device -registration is now safe to repeat for accepted programs, but this checkpoint -does not itself add those callers or establish graph-owned preparation. - -## Shared shader preparation for direct Client views - -`PrepareWorldShaders` now owns the common CPU resolution and device preparation -sequence for the Client's main viewport, retained source and staged successor. -The Client's old shader loop and `LastShaderOwner` bookkeeping are removed. -Each direct world view prepares its own material/lens programs, optional grade -and InterfacePass before collection. The helper carries a `world shaders prepare` -profile scope and reports changed resources to Client damage tracking. - -`Renderer::PrepareShaders` reconciles current demand against accepted program -hashes. It retires vanished material/lens demand, clears missing or disabled -grades and updates programs even if another library refresh consumed the changed -list. GUI-only and postprocess-only programs no longer get offered as material -shaders. Failed device attempts are cached by family, owner, name and code hash; -removing demand or retiring the owner clears those refusal entries. Missing-source -diagnostics still log on the source transition. Each interface consumer uses its -existing hash reconciliation. `SetContentOwner` now returns a damage signal so a -switch between warm owners still repaints the cached screen image. - -The material, lens, grade and interface fixtures now drive this shared helper. -They check delayed refreshes, edits, failed source edits, demand/source removal, -strict owner isolation, zero material residency for GUI/grade-only demand and -postprocess disable/reenable. Warm interface-owner switches change damage without -changing the renderer resource revision or uploading geometry. Display and HDR -screen/spatial variants remain in the sweep. - -Final offscreen Vulkan checks pass 3,135 assertions in five cases -(`world-shader-owner-damage-gpu.log`). Headless render passes 46,801 / 469 and -Client 10,232 / 172 (`world-shader-owner-damage-host.log` and -`world-shader-owner-damage-client-host.log`). Client, Studio and both test binaries -build (`world-shader-owner-damage-build.log`). The owned editable-room Client round -trip passes 10,940 assertions in one case -(`world-shader-owner-damage-client-gpu.log`). Transition and final frame pairs are -retained in the owned-roundtrip directory; bulk images were removed. This product -run checks compatibility with direct retained/staged preparation, not authored -custom-shader crossing. Formatting and diff checks pass. - -The producer preparation gap described at this checkpoint is addressed below. -Studio migration, actual product custom-shader crossing, device-failure fault -injection, graph-owned preparation and release performance remain open. - -## Shared portal-producer shaders and deferred opaque colour - -PortalImageHost now shares one ShaderLibrary across producers, using the supplied -Client library when available. Standalone producers create a library on demand. -They run PrepareWorldShaders before world collection and capture signatures. -The Client postprocess setting reaches producers so they cannot reenable a disabled -grade for the same owner. Native producer residency defaults to the local world -name; custom fixture meshes/textures now carry the owners of their consuming worlds. -Host Clear preserves content bindings until producer removal has retired owned -compiler modules. - -Complete-world capture signatures include demanded GUI names and accepted code -hashes. Every producer InterfacePass reconciles those hashes independently. -Successful spatial shader edits therefore invalidate renewal even when the -renderer resource revision is unchanged. Material edits, source removal, malformed -edits retaining accepted words, unchanged renewal and disabled postprocessing all -have direct producer and host-driven coverage. - -This reproduced a separate deferred-rendering defect: authored opaque programs -compiled and replaced successfully but did not change portal pixels. The GBuffer -node now draws authored HDR colour and depth first into its existing emissive/depth -outputs. Cleared normal alpha marks those fragments as already shaded. Ordinary -geometry writes all GBuffer fields when nearer; discarded authored fragments leave -background depth available. The lighting resolve returns authored colour directly. -DrawSlots skips those authored runs only in its GBuffer family, retaining indirect -argument positions. No extra graph node or undeclared resource was added. - -The new cutout fixture checks blue authored pixels between green background and -red foreground, with exact reference depths outside the authored region. Its first -oracle incorrectly required byte-identical ordinary colour after adding a wall; -readback showed changed lighting with correct material and depth. That failure is -retained in producer-cutout-diagnostic-gpu.log. The final oracle checks visible -material channels separately from depth. Custom fragment discard in shadow passes -is not implemented by this change. - -Final offscreen Vulkan portal/owner checks pass 34,171 assertions in 32 cases -(producer-shaders-final-gpu.log). Headless render passes 46,801 / 469 and Client -10,232 / 172 (producer-shaders-final-host.log and -producer-shaders-final-client-host.log). Client, Studio and both test binaries build -(producer-shaders-final-build.log). All 35 staged shaders pass SPIR-V and translated -MSL resource checks (producer-opaque-shadercheck.log). C++ formatting and diff -checks pass. Build output retains the existing DrawList::JointFrames initializer -warning in PortalImageRuntime.cpp. - -Actual product custom-shader crossing, Studio migration and graph-owned -preparation remain open. No release profiling, -sanitizer or interactive Studio run was added. - -The owned editable-room Client round trip also passes 10,968 assertions in one -case (producer-shaders-final-client-gpu.log). This checks crossing compatibility -with shared producer preparation; the fixture does not author custom shaders. -Twelve transition/first/final frame pairs remain in -portal-client-walk-60-third-explicit-held-clear-image-frames-warm-owned; bulk -successful captures were removed. - -Authored opaque occlusion coverage now passes 125 assertions in one case -(authored-occlusion-final-gpu.log; authored-occlusion-final-build.log). Large and -small authored/ordinary rows exercise both phases, including a half-screen discard. -Colour and depth match the ordinary GBuffer path on initial and repeated draws. -Removing authored programs changes both reference images, and the occlusion path -must issue more draws than the baseline, preventing a silent one-pass fallback -from satisfying parity. This is dev/offscreen Vulkan functional evidence, not a -performance measurement. - -## Product material shaders across adoption - -The real Client round-trip fixture now authors a ShaderScript named RoomShader in -both worlds, with red source-world code and blue destination-world code. White -floor materials select that same name. A missing shader therefore cannot pass the -room-colour oracle. Camera-ray checks cover native, retained and staged views, -including room pixels seen through portal apertures. The run requires samples of -both colours and of a retained-world view, plus the existing two-adoption camera, -input and landmark checks. - -The first product run stopped in the expanded fixture on a null capture descriptor -before the first image arrived (product-shader-owner-gpu.log). The descriptor guard -was corrected. The next run reproduced white floors throughout source viewing and -failed the destination landmark (82 assertions; product-shader-owner-capture-gpu.log). -Those complete failed captures are retained separately in -product-shader-owner-null-capture-evidence and product-shader-owner-white-floor-evidence. - -A headless replica test then reproduced the cause: collect-replicated read an empty -SurfaceAppearance shader because BuildReplicatedWorld never scheduled material -resolution. Replica presentation now runs ResolveMaterials before collection, as -other presented worlds already do. The new test checks selection and clearing in -an adopt-only store. The original failing headless evidence is -replica-material-reproduce.log. - -After the fix, the dev/offscreen Vulkan product run passes 11,292 assertions in one -60 Hz case (replica-material-final-gpu.log). Full headless Client passes 10,237 / 173 -(replica-material-final-host.log). Client, Studio and test_client build; the existing -NativePlayerPrediction::Sample initializer warning remains in the log. Formatting -and whitespace checks pass. Thirteen first/final/transition/sample frame pairs are -retained in portal-client-walk-60-third-explicit-held-clear-image-frames-warm-shaders. -Frames 190 and 599 were inspected: the former has the blue room beyond the aperture -and red foreground, while the latter has red returned-room ground and a blue portal. -PNG copies exist only to make those BMP readbacks viewable by the inspection tool. - -This closes the reproduced material-shader selection gap in replicated views and -provides actual material-shader crossing evidence. Product spatial GUI/lens/grade -shader crossing, shader edits during transfer, Studio migration and release -profiling remain open. No sanitizer or interactive Studio run was added. - -## Reproduced spatial GUI omission before adoption - -The Client crossing fixture now selects a typed RoomShader mode: none, material or -spatial GUI. The spatial case places a depth-tested SurfaceGui/ImageLabel across -the white floor, using the same RoomShader name with red/blue code in the two -worlds. It retains the material case's camera-ray colour and two-adoption checks. -The landmark threshold is now a nonfatal CHECK rather than REQUIRE, retaining the -same pass condition while allowing the rest of the sequence to report failures. - -The first combined run passes the material case but fails the spatial case at -outbound adoption (product-spatial-shader-gpu.log: 12,981 assertions, one failure -across two cases). Frame 148 has only 16 blue landmark pixels; frame 149 has 4,702. -Both images were inspected and PNG viewing copies retained in -product-spatial-shader-pre-adoption-evidence. The full second run confirms exactly -one failure across 11,285 assertions (product-spatial-shader-full-oracle-gpu.log). -All later room-colour, retained-view, camera and return-adoption checks execute. -Both build logs pass; C++ formatting and diff checks pass. No runtime fix is claimed. - -The metadata identifies the cut: before adoption, the portal uses an -opaque-lighting ordered-layer capture from walk.destination. After adoption it -uses a complete-world capture from client.portal.1. The producer deliberately -creates/submits its InterfacePass only for CompleteWorld; the ordered-layer graph -stops at opaque lighting and peels ordinary transparent geometry. Therefore the -remote room omits spatial GUI until its admitted local replica can render it. -This is broader than shader compilation or owner lookup. - -The next implementation must carry spatial presentation through remote body -composition while preserving depth, transparency and current-body ordering. -Changing the request to CompleteWorld alone would bypass the layer contract that -keeps the local body current. Adding GUI colour to OpaqueLighting alone would mix -its radiance/depth contract with arbitrary spatial overlays. Preserve this failing -product check while extending the remote presentation inputs and graph stages. -The same boundary still needs the planned authored lens inputs after body -composition. The full failed spatial sequences remain in their evidence directory -and portal-client-walk-60-third-explicit-held-clear-image-frames-warm-spatial-shaders. -The latest passing material sequence replaced that fixture's prior successful -capture directory; its transition/first/final/sample pairs are retained. - -## Depth-tested spatial GUI in ordered portal layers - -Ordered-layer producers now prepare and submit their spatial InterfacePass. -The opaque radiance image keeps its existing scope. Depth-tested spatial batches -join the peeled transparent layers, so the receiver still composites the current -body against the same ordered depth domains. No wire version or image-count change -is needed for these batches. - -FrameOverlayHook exposes prepared batch capture through WorldInterfaceCapture. -InterfacePass reuses its submitted mesh, clipping, owner-scoped authored shaders -and requested-camera transforms, with an additional HDR pipeline that writes -fragment depth. Each batch first draws to graph-declared RGBA16F/D32F scratch -attachments. The interface-layer shader then selects fragments against opaque and -previous-layer depth, followed by a colour replay at the selected depth. Scratch -colour is already premultiplied, so this replay uses a matching blend state. -Discarded and zero-alpha fragments leave deeper layers available. All shader -variants include the new capture pipeline in atomic installation and retirement. - -Scratch targets are ordinary graph resources, reused between batches. The node -counts actual render passes and interface batches. This adds per-batch GPU passes; -no release performance claim is made. Ordered captures include accepted GUI words -in their resource signature. Always-on-top collectors are explicitly unsupported -by this depth-ordered path and cause capture failure instead of silent omission. -Their separate ordering contract, along with lens inputs after body composition, -remains required work. - -The initial product check passes 11,200 assertions (spatial-layer-product-gpu.log). -The render sweep passes 80,383 / 30 (spatial-layer-verified-gpu.log), including portal -runtime/host, interface owner and authored opaque occlusion cases. The expanded -ordered-layer fixture passes 94,420 assertions (spatial-layer-mixed-gpu.log): ordinary -glass, spatial GUI, discard, zero alpha, and mixed glass/GUI in both depth orders. -It retains half-alpha, exact layer distance, opaque occlusion, visible-overflow and -recovery checks. An intermediate test-oracle error expected a discarded front layer -to reveal a third pane behind the opaque wall; that 816-assertion failure remains in -spatial-layer-discard-gpu.log and was corrected by applying the same opaque bound -to expected layer indices. - -Headless render passes 46,802 / 469 and Client 10,237 / 173 -(spatial-layer-verified-host.log and spatial-layer-verified-client-host.log). -Graph tests pass 8,993 / 225 (spatial-layer-graph.log). All 36 staged shaders pass -SPIR-V/MSL binding validation (spatial-layer-shadercheck.log). Client, Studio and -both test binaries build; the final layer-fixture build is -spatial-layer-mixed-build.log. The existing DrawList::JointFrames initializer warning -remains. No sanitizer or interactive Studio run was added. - -Final spatial product verification passes 11,192 assertions -(spatial-layer-verified-product-gpu.log), retaining the original landmark threshold. -Inspected frames 145 and 146 show the blue floor on both sides of outbound -adoption. The successful spatial capture directory retains 12 BMP/JSON pairs: -first/final frames and both sides of each ownership or view transition, plus PNG -copies of those two inspected frames. Full failed sequences remain preserved in -their evidence directories. The final shader formatting rebuild stages SPIR-V and -MSL successfully (spatial-layer-shader-format-build.log); all 36 modules pass again -(spatial-layer-final-shadercheck.log). This last shader change is whitespace only. - -## Shared world-view batch routing - -WorldViewInterface now forwards ordered-layer capability, prepared batch count and -batch recording to its spatial hook. Previously it inherited the empty batch API: -the same InterfacePass that worked directly in a producer lost its spatial batches -when wrapped for foreign-world presentation. Screen UI remains routed separately. -Failed or not-yet-run spatial preparation exposes no batches and records nothing; -shared spatial/screen hooks still prepare only once. - -The expanded existing world-view ownership test reproduced ten failed assertions -(world-layer-routing-before.log). After the fix, headless render passes 46,820 / 469 -and Client passes 10,237 / 173 (world-layer-routing-render.log and -world-layer-routing-client.log). Client, Studio and both test programs build -(world-layer-routing-build.log); formatting and diff checks pass. No new GPU, -interactive Studio, sanitizer or release profiling run was made for this routing -change. Always-on-top capture and the post-body lens chain remain unfinished. - -## Spatial overlay wire member - -PortalImageLayerSet now has an optional SpatialOverlay member for premultiplied -world-space always-on-top GUI. It carries no depth: it belongs after current-body -composition, rather than inside the physical transparent depth order. It must -share the opaque image's request, extent, capture tick, content revision, lighting -revision and lighting snapshot. Screen UI is outside this payload. - -PIMG is now version 13. A canonical presence byte follows the transparent count; -the optional overlay is the last length-prefixed image. All member prefixes are -admitted before decompression. Expanded pixel limits include the overlay, and -ImageCount lets inbox admission charge its pixels and copied metadata before -transactional decode. Held-byte accounting, replacement, expiry and TakeLayers -move or release the complete group. Zero alpha requires zero colour, and alpha -outside [0,1] is refused. Invalid groups preserve the caller's output. - -This is transport construction, not completed rendering support. Producers still -refuse always-on-top ordered captures. QueuePortalImageLayerSet explicitly refuses -groups containing SpatialOverlay until GPU import and composition are wired; -accepting it there now would silently discard the member. Next work must capture -the top-only interface into a graph-owned HDR target, charge that extra capture, -import it atomically with the paired layers, and blend it after current-body and -transparent composition before the authored lens chain. Preserve it through -source replacement and endpoint retirement without inventing a depth value. - -Wire/inbox focused checks pass 10,654 / 13 (spatial-overlay-wire-focused.log). -After strengthening the pixel-budget oracle to enlarge all members together, -headless render passes 52,631 / 469 (spatial-overlay-wire-render.log). Client passes -10,237 / 173 (spatial-overlay-wire-client.log). Existing producer-layer and source -upload GPU cases pass 94,541 / 2 (spatial-overlay-wire-gpu.log), exercising version -13 with the overlay absent. Overlay coverage includes round trips, truncation, -byte mutations, individually valid members with mismatched capture metadata, -malformed alpha/depth, compressed expansion and inbox replacement pressure. -It does not yet prove overlay pixels on a GPU. - -Client, Studio and both test programs build (spatial-overlay-wire-final-build.log); -the final test-only rebuild is spatial-overlay-wire-budget-build.log. Formatting -and diff checks pass. Existing initializer and range-loop-copy warnings remain. -No interactive Studio, sanitizer or release profiling run was added. - -## Atomic spatial overlay GPU import - -QueuePortalImageLayerSet now accepts the optional overlay as the last returned -handle. Its local binding role is three, independently of the number of physical -transparent members. Standalone QueuePortalImage still refuses that role: overlay -ownership is admitted with the complete capture group. No depth texture is -allocated for it. Cache admission and reuse distinguish paired images from -colour-only overlays, preserving exact logical residency and pending-byte totals. -Allocation still finishes before any input bytes or output handles move. - -The existing copied-layer/body GPU fixture now uploads overlay groups in eye and -seam cases. It checks readiness after upload, four-member residency at 44 bytes -per pixel, whole-group retirement through the overlay handle, malformed capture -refusal and a second cycle with no new texture allocations. The case passes -48,768 assertions (spatial-overlay-import-gpu.log). This proves import and lifetime, -not overlay blending: its rendered body reference still uses the original group. - -Headless render passes 52,630 / 469 (spatial-overlay-import-render.log), and Client -passes 10,237 / 173 (spatial-overlay-import-client.log). The render test build and -Client/Studio builds pass (spatial-overlay-import-build.log and -spatial-overlay-import-products-build.log). Formatting and diff checks pass. -Existing initializer warnings remain; no sanitizer or release profiling was run. - -The producer still refuses always-on-top ordered captures. Source publication -still expects three handles and must be extended before it can admit an overlay -group. Next connect its handle through retained capture metadata and View, add -the graph-owned top-only capture and post-body blend, and charge the extra capture -against the request budget. The authored lens chain remains later work. - -## Spatial overlay source publication - -PortalImageSource now reserves four upload handles and passes only the actual -member count to atomic import. It publishes SpatialOverlayImage in -PortalImageCapture after the complete group becomes ready. Pending replacements -retain the old overlay together with its camera and paired images. Publication -without an overlay, flat-image replacement, expiry and endpoint retirement clear -the handle; request cancellation retires all pending members without changing the -currently displayed capture. - -The source lifecycle GPU fixture alternates overlay-bearing and ordinary groups -in both directions. It checks pre-publication invisibility, retained metadata, -seven simultaneous images during replacement, cancellation before/after GPU -submission, flattening and endpoint withdrawal. The focused run passes 254 -assertions (spatial-overlay-source-gpu.log). The final combined source/body run -passes 49,022 / 2 (spatial-overlay-source-final-gpu.log). - -Headless render passes 52,630 / 469 and Client passes 10,237 / 173 -(spatial-overlay-source-render.log and spatial-overlay-source-client.log). -Client, Studio and both test programs build (spatial-overlay-source-final-build.log). -New test-count signedness warnings from the first build were corrected; existing -initializer warnings remain. Formatting and diff checks pass. No sanitizer, -interactive Studio or release profiling run was added. - -This closes source publication only. The current-body graph still accepts only -the three paired images and refuses an overlay-bearing group. Next carry the -handle into View, import and blend it through graph-declared resources after -body/transparent composition, then add top-only producer capture with an explicit -pixel charge. The real always-on-top product crossing remains unverified. - -## Graph composition of imported spatial overlays - -View now carries EyeSpatialOverlayImage and includes it in presentation damage. -The eye-image node accepts a spatial-overlay selection with a colour-only output, -checks its capture group and owner against the base image, and refuses missing or -foreign overlay handles. DefaultPortalBodyDocument can append this import and a -colour-compose node after body and ordered transparent composition. Its export -keeps reading the existing opaque depth resource unchanged. - -colour-compose blends premultiplied source-over HDR colour with two samplers and -no depth input or attachment. It uses graph-owned output storage and reports its -draw and output bytes. ComposePortalBodyImage validates all four handles when an -overlay is present and selects a separate cached graph variant for that case. -This does not assign synthetic physical depth to always-on-top GUI. - -The expanded copied-layer/body fixture covers both eye and seam projections, -four body distances and rotated cameras. It compares every blended pixel against -the unoverlaid body/room result and requires byte-identical exported depth. It -also checks foreign/missing overlay refusal and retains import/retirement/cache -checks. Combined source/body GPU tests pass 68,236 / 2 -(spatial-overlay-compose-matrix-gpu.log). The initial narrower run passed 51,112 -assertions (spatial-overlay-compose-gpu.log). - -Graph tests pass 9,088 / 225 (spatial-overlay-compose-graph.log). Headless render -passes 52,636 / 469 and Client 10,237 / 173 (spatial-overlay-compose-render.log and -spatial-overlay-compose-client.log). All 37 staged shaders pass SPIR-V/MSL checks -(spatial-overlay-compose-shadercheck.log). Client, Studio and both test programs -build (spatial-overlay-compose-final-build.log); the final expanded test build is -spatial-overlay-compose-matrix-build.log. The first build failed on a new fixture -variable-name collision, corrected before these runs; its output remains in -spatial-overlay-compose-build.log. Formatting and diff checks pass. Existing -initializer warnings remain. No release profiling, sanitizer or interactive -Studio run was added. - -Producer capture remains unfinished: ordered producers still refuse always-on-top -collectors. Next record top-only spatial UI to a graph-owned HDR image, include it -in the atomic capture result and charge its extra pixels before submission. Then -verify real authored GUI across the product crossing. Authored lens inputs and -their post-body chain remain separate required work. - -## Producer capture of always-on-top spatial GUI - -Ordered producers now record top-only spatial GUI through a graph-owned HDR -colour target. The depth attachment exists for pipeline compatibility and never -becomes overlay payload. Depth-tested GUI remains in the two physical layers; -player screen UI stays outside this capture. A visible top collector requests -a fifth export alongside opaque, two physical layers and the overflow probe. -The producer admits its pixel cost before queueing, then collects all exports -from the same submitted frame before publishing the optional overlay member. -Automatic body demands reserve this possible fifth image when fitting extent. - -The renderer export pool and submission index list share a five-slot capacity. -Adoption planning derives that same bound. The first GPU attempt reproduced -missing overlay completion: submission tracking still had four entries. The -parallel review also found a four-entry resident adoption scratch array. Both -were corrected. The resident fixture now exercises five-member adoption and -waits for GPU completion before testing subsequent slot reuse. - -Producer and resource-image GPU tests pass 714,927 assertions / 14 cases -in spatial-overlay-producer-validated-gpu.log. This includes authored top-GUI -premultiplied HDR pixels, empty physical layers, removal/recovery, explicit -overlay budget refusal, copied export completion and five-image resident -adoption. The command excludes eye-current-camera. The preceding broad run in -spatial-overlay-producer-capacity-gpu.log reproduces its three existing failures: -986 translated, 786 rotated and 424 combined-motion mismatched pixels. It also -contains the resident fixture's pre-wait failure. No current-camera fix is claimed. - -Headless render passes 52,641 / 469 and Client 10,237 / 173. Graph passes -9,091 / 225; all 37 staged shaders pass SPIR-V/MSL validation. Evidence is in -spatial-overlay-producer-capacity-headless.log, -spatial-overlay-producer-headless-client.log, -spatial-overlay-producer-graph-final.log and -spatial-overlay-producer-shadercheck.log. Client, Studio and test programs build -in spatial-overlay-producer-capacity-build.log; the final resident fixture build -is spatial-overlay-producer-resident-test-build.log. Earlier graph-order, -inputless-source declaration and compile failures remain in their producer logs. - -The always-on-top product crossing still needs its own oracle. Existing product -captures use ordered layers before destination replica admission, then switch to -complete-world captures. The new oracle must prove the optional overlay was -present in that earlier ordered group. Authored lens inputs, their post-body -chain, current-camera coverage, release profiling, sanitizers and interactive -Studio verification remain open. - -## Product always-on-top GUI crossing - -The new portal-product-spatial-overlay fixture keeps the existing authored -red/blue floor and both landmark gates. A small green always-on-top SurfaceGui -belongs only to walk.destination. At outbound adoption, the fixture requires -the earlier portal capture to come from that remote producer with opaque-lighting -scope and a nonzero spatial_overlay_image. It projects three interior marker -positions through each accepted capture camera and checks green pixels on both -sides of adoption. Client capture metadata now includes the overlay handle. - -The product test passes 11,362 assertions in product-spatial-overlay-gpu.log. -The first outbound transition is frames 149/150, retained in -product-spatial-overlay-first-pass-evidence. -Frame 149 has overlay handle 107; frame 150 uses the complete-world local capture. -Both BMPs were converted to PNG and inspected: the green marker is visible above -the player and the blue destination floor persists. All 600 BMP/JSON pairs remain -available. The path is distinct from prior spatial-shader and baseline evidence. - -Additional producer discard and zero-alpha top-GUI cases pass 126,740 assertions -in spatial-overlay-producer-transparent-gpu.log. This verifies canonical empty -overlay pixels alongside removal/recovery and the existing ordered-layer cases. - -The subsequent graph-owned lens prerequisite is still under validation. The -first build reproduced leftover LensA/LensB lookups, then built after removal. -An unrelated concurrent Studio edit failed on candidate.Index; it was not -changed as part of this work. Client/render targets build in -lens-graph-product-overlay-final-build.log. Headless render passes 52,642 / 469 -in lens-graph-headless-render.log. The initial lens graph test run has two -failures: expected resource count and missing internal-scratch intent in graph -diagnostics. These are not closed by the passing product test. - -## Graph-owned lens inputs and intermediates - -shader-lenses now resolves named graph colour and R32F depth inputs, plus -distinct HDR final and scratch outputs. Private LensA/LensB allocations and -lookups were removed. The default graph declares the scratch resource, repeated -lens nodes can own separate intermediates, and output extents follow the graph -resource dimensions. Empty and odd-length chains publish the declared final -image. Invalid port offsets and aliased input/output textures are refused. - -PortSpec now marks internally consumed outputs explicitly. Lens scratch uses -that marker, so diagnostics keep its memory/lifetime visible without calling -it an unused output. A node whose final output is unused still reports dead. -The diagnostics test covers reordered named ports and reused scratch; the -profile test includes the added resource. Graph tests pass 9,105 / 226 in -lens-graph-contract-tests.log. The initial contract compile missed propagation -through the catalogue's local port descriptor; corrected output is in -lens-graph-contract-final-build.log. - -The expanded lens GPU fixture first reproduced a separate cache bug: replacing -a named pipeline released its graph textures, but unchanged scene damage then -selected no-op scene passes. The new graph had no output texture. Each installed -pipeline now receives a monotonic revision, and that selected revision participates -in the viewport content signature. Replacement, switching and reinstallation can -therefore invalidate retained scene work without invalidating unrelated pipelines. -The fixture remains unchanged after reproducing this failure in -lens-graph-verified-gpu.log. - -The corrected combined GPU run passes 195,727 assertions / 5 cases in -lens-graph-invalidation-gpu.log. It includes zero through three noncommutative -authored lenses, repeated graph nodes, a distinct remapped depth resource, and -full/half-sized lens outputs. Chained transforms compare against a fused shader -with one final 8-bit level allowed for intermediate half-precision rounding; -depth remapping compares exact pixels and keeps both depth textures live to -prevent aliasing from masking the wrong sampler. Producer layers, source/body -composition and opaque-versus-lensed capture also pass in that run. - -Client, Studio and test programs build in lens-graph-invalidation-build.log. -The unrelated concurrent Studio compile error from the first attempt no longer -appears in the final build. No sanitizer, release profiling or interactive Studio -run was added. This is the graph prerequisite only: bounded authored lens inputs, -accepted program identities and capture time still need transport and post-body -application. The current-camera image failures remain separate and open. - -Final headless render passes 52,641 / 469 and Client 10,237 / 173 in -lens-graph-final-render.log and lens-graph-final-client.log. The product rerun -against the final renderer passes 11,285 assertions in -product-spatial-overlay-final-gpu.log. Its outbound transition is frames 148/149 -in portal-client-walk-60-third-explicit-held-clear-image-frames-warm-spatial-overlay, -with remote overlay handle 90 before adoption and complete-world capture afterward. -Both PNGs were inspected and retain the green marker and blue floor. Formatting -and diff checks pass. All product captures and earlier failure logs are retained. - -## Captured authored lens chain, integration in progress - -PIMG v14 adds a bounded ordered lens chain to PortalImageLayerSet. Each entry -carries a copied rigid pose, shader name, accepted program hash, radius, inner -radius, falloff, strength, spin, priority and sphere shape. Local entity IDs stay -out of the wire. The chain carries capture time; an empty chain has canonical -zero time. Borrowed metadata validation and record/name byte admission precede -image decompression. Codec/inbox checks pass 31,523 / 27 in -captured-lenses-codec-inbox.log. - -Ordered producers collect accepted program identities under their content owner -and refuse missing programs or invalid parameters. Source publication moves the -chain with its atomic image group; pending replacements keep the previous chain, -and cancellation, flattening and expiry preserve or clear it with that image. -Body composition resolves the authenticated producer through the view's foreign -content bindings, checks exact accepted shader hashes and uses a lens-only owner -and time override. Geometry keeps its own content owner. Those overrides also -participate in retained viewport invalidation. - -The body graph can run captured lenses after body/transparent/overlay composition -using explicit composed depth and separate HDR final/scratch resources. Graph -tests pass 9,325 / 226 in captured-lenses-graph.log. Headless render passes -69,213 / 469 and Client 10,237 / 173 in captured-lenses-headless-render.log and -captured-lenses-headless-client.log. Client, Studio and tests build in -captured-lenses-final-build.log after fixing the missing hash-type include from -captured-lenses-build.log. - -The first combined GPU run in captured-lenses-gpu.log passes three cases and -fails the body-chain oracle at 2,312 pixels. The observed 0.0104857 error matches -three intermediate half-float stores rounded toward zero, while the initial -oracle used unrounded arithmetic. The revised fixture uses binary fractions -and explicit intermediate quantization without widening its tolerance. The rerun -passes 87,709 assertions / 3 cases in captured-lenses-quantized-gpu.log. -It still checks distinct A/B/A shader runs, captured time, composed -depth, unchanged alpha/depth and missing owner/hash refusal. - -Product review also found divergent native order: DefaultPbrDocument applied -lenses before transparent geometry/top GUI, while DefaultWorldHdrDocument applied -them afterward. DefaultPbrDocument now authors the common HDR chain, and -DefaultWorldHdrDocument reuses it. Surface capture, portal/mirror composition, -transparent geometry and spatial GUI precede lenses, then display tonemapping. -Catalogue formats and graph-order expectations match that chain. Graph tests -pass 9,305 / 226; headless render passes 69,207 / 469 and Client 10,237 / 173 -in captured-lens-unified-graph.log and captured-lens-unified-headless-*.log. - -The first source/host GPU sweep exposed stale four-byte readbacks of portaled, -which is now eight-byte HDR. Display oracles now capture tonemapped and keep -independent no-portal baseline renders where required. The corrected sweep -passes 219,600 assertions / 15 cases in captured-lens-unified-gpu.log. Client, -Studio and tests build in captured-lens-integration-build.log. - -The real moving-lens product fixture fails 19 checks in -product-captured-lens-first-gpu.log: captured images and accepted lens hashes -arrive, but the displayed portal image remains zero and neither adoption occurs. -All 600 frames are retained in product-captured-lens-first-failure-evidence. -This reproduces a circular dependency: the initial portal needs the destination -program before walking, while successor replica creation requires a crossing -offer. Preparing shaders only on that successor cannot resolve initial readiness. - -PIMG v15 now carries a deduplicated accepted SPIR-V dictionary, bounded to 16 -programs and 1 MiB of code, with hash and byte admission before decompression. -Renderer-local program leases validate SPIR-V and the fixed lens ABI before -device creation; immutable name/hash groups share references in 256 reusable -slots. Captured pipelines have storage separate from authored world owners. -A real owner named portal.lens.programs/0 reproduced a collision in the initial -shared-map design; both creation paths now share only the device-creation helper. -Source upload, publication, cancellation and retirement move or release -those references with the image group. Producer words come from the accepted -shader library module and must match the installed program hash. The first build -found a missing registry declaration, now added. Client, Studio and test targets -build in captured-lens-verified-build.log. - -The same-camera native/captured-body oracle uses actual room radiance and two -peeled glass layers at three body depths, with front and rotated cameras. Its -integer A/B/A shifts and quarter-turn also match an independent byte-exact -coordinate oracle. Imported/native HDR retains the existing .004 glass-store -bound and .003 depth bound, over every pixel. Malformed SPIR-V, wrong shader -stage, wrong sampler set/binding and mismatched token identities are refused; -authored-owner deletion and final captured-program release cannot delete each -other's pipelines. These checks pass in captured-lens-final-gpu.log. That broad -run passes 32 / 33 cases and 674,463 / 674,466 assertions. The only failures are -the previously known current-camera translation/rotation/combined checks, with -unchanged mismatch counts 986 / 786 / 424. Headless render passes 86,179 / 469, -Client 10,237 / 173 and graph 9,305 / 226 in captured-lens-final-headless-*.log -and captured-lens-final-graph.log. Shadercheck passes all 37 staged modules. - -The program-carrying product run now completes both handoffs. Its initial -pixel oracle forgot that the source world's lens also moves the portal image: -equal opposite shifts cancelled. Unequal destination/source shifts now require -a visible net shift and an empty vacated edge. Those pixel and captured-hash -checks pass across frames 157/158, inspected as PNGs, in -product-captured-lens-combined-shift-gpu.log. That run still fails one of 11,234 -assertions: after returning, the predicted body settles but the script-visible -Humanoid.MoveDirection remains nonzero. Camera distance is correct and key -release occurs; the missing rest-state sample is under investigation. Earlier -cancelled-shift frames are preserved in product-captured-lens-cancelled-shift-evidence. -This checkpoint does not close authored lens crossing or current-camera parity. - -The movement probe reproduced a separate stale replicated Humanoid.MoveDirection: -frame 599 has a stopped predicted direction but a nonzero ECS direction on the -returned humanoid. Frames are retained in product-captured-lens-stale-direction-evidence. -No movement behavior was changed. Optional portal-input and portal-input-stop -traces now identify the authoritative humanoid and applied direction. Traced -runs pass, including product-captured-lens-stop-repeat-gpu.log with 12,107 -assertions and both final directions zero, but no traced failure yet establishes -where the stale value originates. The intermittent failure remains open. - -The lens fixture's vacated-edge sample now uses world X=1.2; the former X=1.6 -sample could overlap the shifted marker as its projection grew. All three -positive shifted-marker samples remain. Passing frames and failed movement -frames are retained separately. These fixes do not weaken the rest-state gate. - -### Current-camera packet binding - -BindWorldView now borrows the retained world's full geometry and camera layers -while preserving the caller's camera, projection, target, slot and body selection. -It validates the live owner name and store identity before mutation, then clears -imported eye and captured-lens state. Client::PreparePortalWorldView uses this -same helper. Caller-owned damage is computed after binding in the client. - -The current-camera fixture explicitly checks that image-only output stays at -its capture camera. Its new full-packet branch renders the normal graph with -the retained hidden post, retaining all four original motions and the .002 -pixel bound. current-camera-binding-gpu.log passes 155 assertions; the existing -WorldView suite passes 172 assertions across four cases in -current-camera-binding-headless.log. The first build rejected a test CFrame -comparison without an equality operator; component comparisons fix that error. -This establishes packet rendering, not disocclusion recovery from pixels alone. - -Client scene eligibility now requires a live, admitted, fully joined authenticated -successor with the matching destination and no refusal/failure. Joined follows -complete authoritative snapshot application. Player prediction still requires -Ready and DrawingArrivedPlayer. Existing portal-image readiness refusal remains. -No existing content-session flag guarantees that every asset loaded, so this -change makes no such guarantee. Product routing now passes the scene, pixel and handoff checks in -current-camera-scene-gates-product-gpu.log. That run passes 11,547 of 11,548 -assertions; the one remaining failure is the unchanged post-return rest-state -gate. The earlier routing run had 52 assertions for the old player-arrival -requirement; these now check admitted/joined/live/matching scene ownership and -absence of rejection or failure. - - -The traced routing failure proves the authority applied zero to the same returned -humanoid at world tick 297/input 299. Client frame 304 had replicated through -300 but retained the nonzero component, still stale at replicated tick 598 in -frame 599. Native motion acknowledgements also froze at pose tick 324/input 326; -this is recorded separately rather than assumed to be the same failure. Full -frames and log are in current-camera-routing-first-evidence. Replication row -tracing is the next diagnostic step; no movement behavior fix is claimed. - -A separate headless reproduction found eight missing presentation invalidations -for content-owner bindings and effective lens inputs. The signature now includes -those bindings on active layers and active lens parameters/program/time. An -inactive lens clock does not dirty an otherwise unchanged scene. The targeted -presentation/WorldView run passes 641 assertions across 49 cases in -current-camera-signature-headless.log. - -Final checks for the packet-binding/signature slice pass: render headless -86,260 assertions / 471 cases, client headless 10,237 / 173, and the focused -current-camera/lens/layer GPU group 83,786 / 4. Logs are -current-camera-final-headless-render.log, current-camera-final-headless-client.log, -and current-camera-final-gpu.log. No release profiling, sanitizers or interactive -Studio run was performed for this slice. - -Opt-in replication-row tracing now records humanoid component signature changes, -packing, acknowledgement retirement and application hashes without a scene-layer -dependency or behavior changes. Build passes in replicated-stop-row-trace-build.log; -replication tests pass 22,409 assertions / 271 cases. The traced product run still -fails the single rest-state assertion in replicated-stop-row-trace-product-gpu.log. -Its application traces include changing server snapshot-store identities; these -must not be mistaken for proof that the client applied the stop. Correlating the -actual client recipient remains in progress. - -Client-scoped replication tracing reproduced the loss in -replicated-stop-client-trace-product-gpu.log (12,444 / 12,445 assertions pass). -Native peer ...0880 sends/applies/acknowledges humanoid tick 258, then has no -candidate for the authoritative zero at tick 270. The other two peers receive -that change. This places the loss before native-client packing, rather than in -component decoding or a later client overwrite. The strongest current hypothesis -is snapshot streaming: its branch skips ordinary change collection while the -global changed list is replaced at the next publication. A deterministic test -and explicit streaming trace are being added before a behavior fix. - -The deterministic snapshot test reproduced loss both during initial world -streaming and an oversized component slice: the acknowledged small value stayed -1 after a one-shot change to 0. The first fix retains changes in existing -Unconfirmed rows while streaming, clearing superseded SentAt acknowledgements. -Both reproduction sections pass, and the product run passes 11,600 assertions -in snapshot-changes-fixed-product-gpu.log. Broader replication testing found two -regressions from also retaining values already included in a newly captured -initial snapshot: an unnecessary post-join message and a delayed audit. These -are being fixed rather than weakening the existing checks. Both change-detection -modes and a real delayed acknowledgement now extend the regression fixture. - -### Snapshot-stream change retention fix - -Both deterministic sections reproduced the missing update before the fix. -Authority now preserves known, sendable, unsuppressed changes in its existing -Unconfirmed rows while a snapshot is already streaming, or before starting an -oversized slice. A superseded SentAt is cleared so an older acknowledgement -cannot retire the newer value. Fresh full snapshots already include their -capture-tick changes and do not redundantly queue them. Recovery sends the -latest component value when ordinary publication resumes. - -The expanded fixture covers observed and signature detection across initial -snapshot, oversized slice and a real delayed acknowledgement. Its setup fixes -kept the serialized string payload observed while varying detection for the -small state component. All 22,503 assertions / 272 replication cases pass in -snapshot-changes-final-replication.log, including the existing no-extra-send and -audit checks. Client headless passes 10,237 / 173 in snapshot-changes-final-client.log. -Client/server and Studio builds pass; snapshot-changes-final-build.log records -the final Studio and replication-test build. - -The refined traced product run passes 11,660 assertions. With replication tracing -disabled, the final product run passes 12,379 assertions in -snapshot-changes-final-product-gpu.log, including both handoffs, lens/scene pixels -and the post-return rest-state gate. This closes the reproduced lost-update bug. -It does not claim image-only disocclusion, nested scaled-aperture composition or -the full render-refactor acceptance matrix. Release profiling, sanitizers and -interactive Studio verification were not performed for this change. - -### Nested ordered capture, implementation started - -The top-GUI/authored-lens checklist item is complete within its own scope; nested -scaled-aperture composition remains the distinct acceptance case required by -RENDER-REFACTOR.md. The new production-path GPU section requests ordered opaque -layers through one child portal. It fails before dispatch because ValidRequest -rejects OrderedLayers with nonzero recursion. The request has a valid binding and -an eight-capture pixel budget. nested-ordered-capability-red-gpu.log records the -32 / 33 assertions before rejection. This is a capability reproduction, not a -native pixel/depth comparison. - -The next representation is a bounded flat capture tree: each node retains its -own ordered images, accepted camera, lighting, lens programs and producer -identity; each parent-before-child edge carries the authored aperture geometry -and parent-to-child transform. Child linear depth stays in child units. Leaves -compose their mapped current body first; parents sample completed child colour -at the parent aperture depth before their physical layers and lenses. The entire -tree must be admitted, uploaded, replaced and retired atomically under aggregate -node, geometry, pixel and program budgets. - -The later independent depth oracle uses outer scale 2 and inner scale .25, a -parent mouth at depth 8, a parent blocker at depth 6 and a child body at depth 4 -(equivalent parent distance 16 for that mapping). Raw child depth must never beat -the parent blocker. Native unfolded HDR comparison, per-node depth probes and a -second body pose without room re-upload remain required. Borrowed geometry -preflight and the tree codec are being built first; runtime support is not yet -claimed. - -The standalone capture-tree codec now builds and passes its tests. PIMG kind 6 -(version 15) carries at most 16 parent-before-child nodes and depth 4. It retains -per-node camera, endpoint claims, required lighting and layer sets, plus encoded -aperture geometry and canonical scaled transforms. Borrowed preflight validates -aggregate pixels, geometry, program bytes and metadata before image decoding. -Program hashes share the distinct-program limit across nodes; physically repeated -program words still consume the byte budget. Sibling aperture keys must be unique. -Endpoint authentication remains the presentation adapter's responsibility. - -MeasurePortalGeometry and DecodePortalGeometry share parsing/validation, with -transactional output and mutation/truncation parity checks. Tree tests cover -independent cameras, two physical layers, top GUI, lens dictionaries, malformed -topology, depth boundaries and whole-tree budgets. An early test command used the -previous binary and did not match the new tree suite; it is not tree evidence. -After final linking, portal-capture-tree-headless.log passes 55,687 assertions / -39 cases. Full headless render passes 92,515 / 475 in -portal-capture-tree-full-headless.log; existing layered GPU cases pass 83,550 / 2 -in portal-capture-tree-existing-gpu.log. Final codec build and formatting checks -pass. This codec checkpoint did not implement recursive producer collection, -GPU tree import, composition or the native scaled-depth oracle. - -### Capture-tree admission and ownership - -The inbox now accepts ordered recursion through depth 4. Borrowed preflight -matches the root request key, exact camera, dimensions and authenticated endpoint, -then requires the source adapter to approve every child against current Universe -routes before image decoding. Whole-tree pixel and metadata budgets keep the old -capture charged during replacement. A successful flat reply cannot satisfy a -recursive request; flat failure replies still complete it. - -The renderer imports each tree as one lease over all image groups and captured -lens programs. Partial preparation rolls back. Publication waits until every -group has been submitted on the device queue, making later sampling queue-safe; -this is not a claim that upload fences have completed. Dropping any member, -forgetting its world or shutting down retires the entire tree. Sparse physical -layers retain the fixed top-GUI handle slot. - -PortalImageSource publishes the complete tree atomically and checks child -incarnations during retention. Retiring an old child removes its old capture -without cancelling an unrelated replacement. Its payload-only mode retains -ordered captures in the bounded inbox for a parent producer, wraps leaf layers -as one-node trees and performs no GPU import. Payload expiry and consumer -endpoint retirement prevent later extraction. The body graph has an optional -aperture overlay before depth export, physical layers, top GUI and lenses. - -An initial build caught an optional-projection expression in the import code; -the corrected final build passes. The first payload test constructed replies -with pre-stamping request keys; fixtures now decode the actual issued request. -portal-tree-source-full-headless.log passes 92,822 assertions / 480 cases. -portal-tree-source-gpu.log passes 83,772 / 4 on offscreen Vulkan, covering tree -imports, source replacement/retirement and existing flat layered paths. -portal-tree-graph-tests.log passes 9,881 / 226, including all 32 body-graph option -combinations. Formatting and diff checks pass. No release profiling, sanitizer -run or interactive Studio verification was performed for this slice. - -The production capability case now reaches the producer, which explicitly -refuses recursive ordered capture: portal-tree-producer-capability-gpu.log has -35 passing assertions and one failure, `Status 4 != Ok`, with diagnostic -"unsupported recursion depth or camera clip plane". Producer tree collection, -bottom-up current-body composition and the independent scaled native HDR/depth -oracle remain unfinished. ComposePortalBodyImage refuses a tree capture until -that composition path exists, preventing a root-only image from implying nested -support. - -### Recursive producer, body composition and delegated identity - -The producer now collects ordered child payloads into bounded capture trees -without importing child images on its GPU. Each node keeps its own camera, -lighting, depth units and captured programs. Current-body composition walks the -tree bottom-up, maps the body through each seam and uses the encoded aperture -geometry to compose child output before parent physical layers, GUI and lenses. -Fresh output adoption preserves the prior complete image if an intermediate -allocation fails. Local reflected surfaces still return an explicit unsupported -diagnostic; this does not close recursive mirror support. - -The independent three-room native comparison reproduced incorrect depth export -ordering. Aperture colour was ready while depth export could run before the -aperture wrote hardware depth. An explicit graph dependency now orders that -export after aperture composition. The scaled native HDR/depth comparison passes, -including a second body pose without room uploads and capacity-failure rollback. -Original failure frames remain in -`.cache/build/dev/tests/nested-body-depth-pre-order-fix`. - -Host relay bindings now carry exact local and published endpoint tuples. The -source authenticates the transport separately from the canonical tree identity; -binding replacement and withdrawal retire affected captures. An alias refusal -test reproduced acceptance of a local child tuple as a published identity -(231 passing assertions, two failures in portal-tree-alias-red.log). The fixed -check passes all 233 assertions. Binding decoding also refuses conflicting local -tuples across exports and return routes before allocating owned strings. - -Final dev checks pass: portal-tree-final-headless.log has 93,055 assertions / -481 cases; portal-tree-final-world.log has 32,635 / 249; and -portal-tree-final-graph.log has 10,449 / 226. Offscreen Vulkan checks in -portal-tree-final-gpu.log pass 320 / 2 for native scaled composition and actual -HostLink/PresentationRelay root export, withdrawal and replacement. The latter -currently carries a one-node tree, so it does not prove nested relay routing. -portal-tree-final-source-gpu.log passes 127,247 / 4 for producer layers, source -publication and tree import. portal-tree-final-producer-gpu.log passes 81 / 1 -for actual recursive producer collection, budget refusal and child withdrawal. -Build, formatting and diff checks pass. - -Nested relay routing, the broader animated/material/oblique native matrix and -the combined product failure/crossing gates remain open. No release profiling, -sanitizer run or interactive Studio verification was performed for this slice. - -### Nested relay and oblique native follow-up - -The relay fixture now also carries a two-node tree. Its child request and reply -cross HostLink and PresentationRelay to a separate parent-owned producer, using -the same bounded nested-reply channel policy as ServerPresentation. It verifies -both published identities, replacement, and child-only withdrawal while the -root endpoint stays live. This relay case passes in -portal-tree-nested-oblique-gpu.log. - -The native oracle now retains the original scaled case and adds independently -translated/rotated room frames with an oblique camera. Its unchanged HDR and -depth limits expose three failures: four stationary aperture-edge pixels differ -in each root image, and native centre depth at the middle room's second body -pose differs by 0.000139236 against the 0.0001 bound. The combined log reports -675 passing assertions and three failures across two cases. This is an open -rendering gate, not completed oblique support. The failure images are under -`render-failures/nested-body-depth/transformed-room-0-pose-0` and `pose-1` -beside test_render. - -Double-precision inverse-VP setup reduced the depth error only to 0.000135422 -and left the four colour pixels unchanged; that experiment was reverted. -Geometry placement arithmetic alone does not explain the error. Packed instance -rotation, hardware depth and aperture rasterization remain under investigation. - -### Oblique coverage and rotation precision - -The four colour failures were reproduced numerically as frame/aperture coverage -disagreements caused by SNORM16 quaternion rounding. An eight-byte, -twenty-bit-component experiment cleared three pixels but left one gap. Full-float -rotations clear every HDR mismatch at the original 0.002 bound. The aligned and -translated/rotated/oblique cases retain all three subtree roots, both body poses, -separate depth units and the no-room-upload check. - -Instance rows now use four aligned vectors, 64 bytes instead of 48. Joint rows -use seven words instead of five. CPU upload, shader instance/skin decoding and -build-time stride guards agree; the discarded twenty-bit codec is removed. -Independent double-rotation tests retain a 30-micrometre displacement bound at -100 metres. A new GPU fixture compares two weighted joints and two palette -updates against independently CPU-deformed meshes across the full HDR image. - -The native-only ideal-ray depth assertion was a separate reference error. -The RTX 4090 reports eight subpixel precision bits, and independently snapping -the triangle vertices reproduces its pose-specific depth difference. The native -export check now starts from captured hardware depth and independently computes -camera-space distance with double-precision matrix math. Its 0.0001 tolerance -is unchanged. Parent/child aperture-depth analytic checks remain unchanged, and -the leaf composition also compares against native depth at 0.0001. This corrects -the raster reference; it does not claim ideal rays and rasterized triangles have -identical depth. - -portal-skin-oblique-final-gpu.log passes 632 assertions / 2 cases on offscreen -Vulkan. Broader projection, character, layers, imports and relay checks pass -137,159 / 16 in portal-rotation32-regression-gpu.log. Full headless render passes -101,264 / 481 in portal-rotation32-headless.log; world passes 32,635 / 249 in -portal-rotation32-final-world.log. Shader validation passes all 37 staged modules, -including SPIR-V/MSL structure and bindings. Dev and optimized bench builds pass -after fixing private-name unity collisions in capture-camera conversion and the -world presentation stream. Formatting and diff checks pass. - -The existing instance benchmark printed three optimized samples to the terminal: -10,000 unchanged rows measured 25 ns/row to pack, 17 ns/row to upsert prepacked -data and 16 ns/row for exact source reuse. This is current CPU cost, not a matched -old/new GPU performance comparison. The byte increase is explicit; broader -release 1/2/8-view traffic and timing gates remain open. No sanitizer run, -interactive Studio check or hardware execution of MSL was performed. - -Original oblique failure artifacts are preserved under -`.cache/build/dev/tests/nested-body-depth-pre-rotation-fix`. Animated nested -crossing, moving lighting, full material/lens composition, recursive mirrors and -the remaining product acceptance matrix still need their own evidence. - -### Nested animation, replacement capacity and lighting interaction - -The three-room native oracle now includes two weighted joints, two palette -poses and an inherited body cut distinct from each entrance plane. Independent -CPU-deformed reference meshes cover aligned and translated/rotated/oblique room -frames, all three subtree roots and unchanged HDR/depth tolerances. These checks -pass while the retained room images receive no new uploads. Physical product -crossing and its lifecycle combinations remain separate acceptance gates. - -Two new failing cases exposed production defects. A three-node capture with -two physical layers uses nine images, so the previous sixteen-image pool could -not keep an old tree while preparing its replacement. The derived limit is now -145 images: two maximum sixteen-node, four-image trees, sixteen composition -outputs and one retained root. Tree leases remain capped at sixteen; CPU/GPU -image budgets remain 32 MiB each. Tests cover ordinary nine-image replacement, -maximum sixty-four-image replacement, exact slot exhaustion and retirement. - -Finite aperture axes of magnitude 1e30 overflowed the float cross product and -let an invalid entrance clip reach composition. Shared double-precision normal -construction and finite derived-value checks now refuse it before allocations. -Correct entrance clips still compose with both ordinary and 1e30 axes. A nearby -finite-input sampling overflow returned failure only after creating fifteen -textures (82 allocations versus 67 in portal-tree-sampling-overflow-red-gpu.log). -Sampling elements and determinant now pass the existing adoption validity rules -before any child renders. The final focused gate, including relay, passes -2,360 assertions / 5 cases in portal-tree-sampling-overflow-fixed-gpu.log. -Headless render passes 101,394 / 481 in -portal-tree-capacity-overflow-headless.log; broader Vulkan fixtures, character, -relay, producer and source checks pass 137,085 / 15 in -portal-tree-capacity-regression-gpu.log. These are dev checks, not release -performance measurements. - -The new nested lighting oracle remains failing with default SSAO enabled. -portal-tree-lighting-ssao-gpu.log confirms seven full-HDR lighting failures -(217 passing assertions / 224): 8 to 17 pixels differ, with maximum error -0.0032959 against 0.002. -Body colour probes pass, but native room pixels beside the body silhouette are -darker. The retained room-only image lacks the current body's ambient occlusion. -The fixture retains distinct room lighting, a changed deepest-room local light -and recomposition of the old capture after replacement. Its tolerance and SSAO -configuration have not been relaxed. - -Correcting this requires merging room/body depth and normals before per-room -SSAO, then applying that result only to ambient radiance. Multiplying finished -RGB would also darken direct light, emission and fog. Retaining the full G-buffer -would additionally require the matching shadow and lighting resources when -relighting; an alternative is shared-shader factorization into unaffected -radiance plus ambient response times SSAO. Neither transport is implemented yet. -Child aperture composition must remain after the parent's SSAO so depths from -different rooms never enter one occlusion domain. The next implementation must -also test room-to-body occlusion, fog/material AO and no room reuploads during -body movement, while preserving old/new capture ownership. - - -### Retained ambient transport and bright HDR precision gate - -PIMG16 now carries paired native RGB10A2 normals and RGBA32F ambient response -with opaque captures. Response RGB includes material AO and fog attenuation; -alpha retains the original filtered SSAO sample. Four-plane capture, resident -adoption, copied import, hashes, compressed preflight and inbox/tree accounting -include both auxiliary planes. Opaque payload grows from 12 to 32 bytes per -pixel. Existing wire and CPU/GPU byte budgets remain unchanged. Auxiliary -planes must be paired and cannot appear on transparent or overlay layers. - -Each retained room merges its own depth/normals with the current body before -SSAO. The body uses that occlusion in deferred lighting; room correction changes -only ambient radiance. Child apertures enter after this stage and keep separate -depth domains. Native padded normal allocations are cropped at capture to the -logical view extent without resampling their packed values. - -The original and contact lighting cases pass 608 assertions in -portal-ambient-contact-gpu.log, including room-to-body and body-to-room AO, -two body poses, lighting replacement, retained-old isolation and zero room -reuploads. Expanded native controls also pass fog, emission and material AO. -The expanded run is nevertheless red: portal-ambient-material-gpu.log reports -1,428 passing assertions / 1,442 with fourteen failures, all in ambient=8. -The original 0.002 HDR tolerance and enabled SSAO remain unchanged. - -Bright retained colour exposes lost precision before correction. In the leaf -revision-zero, pose-zero artifact, 84 pixels fail; all 215 failing RGB components -are lower by exactly 0.00390625, one binary16 ULP in [4,8). The correction starts -from rounded RGBA16F room colour and rounds again on output. Full-float response -cannot recover the lost baseline bits. Preserving the unrounded lighting -baseline or equivalent sufficient lighting terms remains implementation work; -this is not a completed general HDR solution. Artifacts are under -render-failures/nested-room-lighting/ambient-8-* in the dev test directory. - -Broader capture/composition verification in portal-ambient-wide-gpu.log passes -833,464 of 833,670 assertions, 22 of 23 cases. The remaining 206 failures are in -rotated, offset-coplanar transparent panes, with roughly one-unit red/green -errors. Direct drawing orders transparent objects by centre distance, while -peeling groups exact per-pixel depths. Attribution and correction remain open; -no baseline establishes that this failure predates the current work. -Headless render passes 103,026 / 483 in portal-ambient-final-headless.log; -graph passes 10,564 / 228 in portal-ambient-final-graph.log; shader checking -passes all 40 modules in portal-ambient-final-shadercheck.log. These checks do -not close product crossing, shadows, recursive mirrors or release performance. - - -### Full-float baseline closes the reproduced bright ambient gap - -PIMG17 adds a group-owned RGBA32F lighting baseline beside normal and response. -An optional deferred-lighting MRT variant writes the same unrounded result to -this plane and the ordinary RGBA16F colour in one invocation. Room correction -uses the full-float baseline. Ordinary deferred rendering retains one output -and does not allocate this plane. All three auxiliary planes are inseparable; -codec, compressed preflight, staging, resident reuse and retirement include the -additional hash and bytes. Opaque payload is now 48 bytes per pixel, with the -existing byte limits and image-handle limits unchanged. - -portal-baseline-lighting-gpu.log passes 1,326 assertions across original, -contact, fog/material and ambient=8 scenarios. The unchanged 0.002 HDR gate -covers all subtree roots, both body poses, two lighting revisions and retained -old captures without room uploads. This closes the reproduced bright ambient -failure, not every possible HDR/material/lighting interaction. -portal-baseline-headless.log passes 103,311 assertions / 483 cases; -portal-baseline-graph.log passes 10,586 / 229; shader checking passes 41 modules -in portal-baseline-shadercheck.log. The dev build passes in -portal-baseline-build.log. - -The transparent diagnostic in portal-coplanar-diagnostic-gpu.log confirms -reversed blend order: both red and green layers survive capture, while direct -object-centre ordering puts red last and per-pixel peeling selects green nearer. -Their linear depths differ by only a few float steps around three units and -sometimes quantize to the same exported depth. The 206 existing parity failures -remain open. A wider baseline run also exposed an incorrect new storage test -assumption that GPU attachment half conversion exactly matches CPU nearest -rounding; correcting that representation oracle and checking optional baseline -output ordering are the next verification steps. - - -Final baseline integration: portal-baseline-final-gpu.log passes 931,180 of -931,386 assertions, 24 of 25 cases. Only the 206 coplanar transparent ordering -assertions remain failing. Five-plane copied/resident storage, import reuse, -producer/relay/tree composition, all four lighting scenarios and optional -baseline extent checks pass. The storage oracle now bounds attachment conversion -between adjacent half values instead of requiring CPU nearest-rounding identity; -the full-image 0.002 HDR tolerance is unchanged. - -The optional-output test reproduced a real sizing defect: baseline-first with -33x19 baseline and 65x37 colour incorrectly executed deferred lighting -(portal-baseline-extent-red-gpu.log, 23 / 24 assertions). ViewRecording now -resolves lighting dimensions from the named colour output. Both output orders -accept matching extents and reject mismatches in the final GPU run. The final -dev build passes in portal-baseline-extent-fixed-build.log, and headless render -passes 103,312 assertions / 483 cases in portal-baseline-final-headless.log. -Graph and shader results above remain current. No release performance run, -sanitizer run or interactive Studio check was performed for this change. - - -### Retained glass body-depth ties and ordering conflict - -A new single-pane native oracle captures glass without an opaque body, then -imports that glass over a newly rendered body. It covers identity and -rotated/translated cameras, an oblique pane and body positions before, exactly -on and behind the pane. This is independent of transparent-to-transparent -ordering. The old exact-tie fixture included the body during capture, allowing -opaque-z to discard the glass before the import boundary was exercised. - -portal-transparent-tie-red-gpu.log reproduces 309 incorrectly visible pixels -at the transformed exact tie, maximum HDR error 0.50415 (147 / 148 assertions). -Transparent capture exported an interpolated world-position dot product; -opaque body depth came from actual D32 reconstruction. The two calculations -were not equal for the same surface. The transparent-layer node now exports -selected D32 through the existing depth-linearise shader, matching the body's -calculation. Removed geometric R32 writes from ordinary and interface peel -shaders and their MRT attachments. A final fullscreen pass writes the existing -R32 output; it adds no image plane, wire bytes or CPU readback. Its pass count -and output bytes are reported. Its release performance has not been measured. -portal-transparent-depth-fixed-gpu.log passes all six cases / 138 assertions -at the unchanged 0.002 full-image tolerance. - -The ordering conflict remains open. Scenario five in ResourceImage uses two -intersecting panes centred at (0,0,-3), rotated by opposite 0.35-radian yaw. -The nearest colour changes between samples on the left and right, with near -and far depths separated by more than 0.1. Direct rendering's whole-object order -cannot match per-pixel peeling on both sides. The combined initial diagnostic -in portal-transparent-intersection-tie-red-gpu.log records 608 ordering -assertion failures, including the previous 206 coplanar failures, plus six -fixture projection-setup failures subsequently corrected. No epsilon or -parity tolerance change was introduced. A user question about which ordering -should define final behavior is pending; the body-depth correction is valid -under either choice. - - -Final shared-depth verification: portal-transparent-depth-wide-gpu.log passes -939,704 of 940,312 assertions, 25 of 26 cases. Only the 608 coplanar/intersecting -transparent ordering assertions fail. Body-depth ties, baseline lighting, -resource storage/import, producer/interface layers and tree/relay checks pass. -Headless render passes 103,312 / 483 in portal-transparent-depth-headless.log; -shader checking passes all 41 modules in portal-transparent-depth-shadercheck.log. -The build passes in portal-transparent-depth-build.log. Read-only integration -review found no additional defect. No sanitizer or interactive Studio run was -performed. The full render and product acceptance scope remains open. - - -### Scaled depth ties, nested single glass and ambient codec cost - -The retained single-pane depth oracle now covers scales 0.37, 1 and 3.1, -including scaled camera near/far planes and translated/rotated room frames. -All eighteen before/tie/behind cases pass 414 assertions in -portal-scaled-tie-gpu.log at the unchanged 0.002 HDR tolerance. - -The three-room lighting oracle adds one real physical transparent layer in leaf -C, separately before and behind its moving opaque body. Source room and glass -captures share a frame; the native reference renders complete geometry through -ordinary transparency without layer extraction. All subtree roots, both body -poses, both lighting revisions, retained-old isolation and zero room reuploads -remain checked. Native controls prove that glass affects room pixels and affects -or preserves the body centre according to its depth. - -Initial failures were fixture mistakes: a view pass declared after shared -present, a leaf readback of the opaque intermediate instead of final glass -composition, and an AO control measured after glass attenuated its signal. -The fixture now declares view work before frame exports, reads the actual final -leaf output and compares AO before transparency at the original thresholds. -No production change was needed for this extension. The combined final GPU run -passes 2,616 assertions / 2 cases in portal-nested-glass-final-gpu.log, covering -all six lighting scenarios and eighteen scaled depth cases. The dev build -passes in portal-nested-glass-readback-build.log. The separate 608 multi-pane -ordering failures remain open; this does not establish general glass/HDR parity. - -`just portal-ambient-bench 3` now measures the PIMG17 five-plane CPU codec for -one, two and eight distinct 256x256 views. The bench preset uses the optimized -build; the runner reports the minimum of three measured samples after warmup, -per view batch. Raw and compressed decode include validation; automatic -roundtrip includes encode, decode and validation of all five planes. - -| CPU operation | 1 view | 2 views | 8 views | -| --- | ---: | ---: | ---: | -| Raw decode and verify | 1.766 ms | 3.513 ms | 14.441 ms | -| Compressed decode and verify | 1.797 ms | 3.691 ms | 14.246 ms | -| Automatic encode, decode and verify | 3.696 ms | 7.419 ms | 30.303 ms | - -Each view has 3,145,728 uncompressed plane bytes. This deliberately patterned -fixture is highly compressible: its first view encodes to 12,703 bytes versus -3,146,074 bytes in equivalent raw framing. This is not a general bandwidth -ratio. The raw packet is validated against the same production-decoded image; -no production compression switch was added. Output was printed to the terminal, -not saved as benchmark result files. These measurements exclude GPU capture, -upload, rendering and network latency. GPU 1/2/8-view timing and residency gates, -plus profiling of the measured CPU codec cost, remain open. Existing aggregate -initializer warnings appeared during the successful optimized build; no warning -cleanup was mixed into this work. - -### Profiled ambient sample validation - -`just portal-ambient-profile 3` now prints the existing FrameGraph hierarchy -during setup, then disables collection for timed batches. Fixed codec scopes -separate hashing, sample validation, compression, framing and materialisation. -Linux perf events were unavailable (`perf_event_paranoid=4`); no system setting -was changed. The engine profile recorded zero dropped spans. - -Before optimization, raw decode spent 1.731 of 1.792 ms in validation. Baseline, -response and depth sample scans consumed 0.636, 0.587 and 0.149 ms respectively. -Portable little-endian integer classification replaces the per-float ByteReader -scans in codec validation and direct import. Depth still rejects negative zero; -baseline accepts every finite value; response admits negative zero and bounds -alpha to one. Hashes, plane pairing and admission budgets remain enforced. -The shared private helper uses byte loads without alignment or aliasing -assumptions. Classification tests compare the original floating-point rules -across both signs, all exponents, boundary mantissas, seeded random words, -unaligned planes and each component position. - -Matched optimized bench measurements use the same profiling scopes, patterned -256x256 five-plane fixture and minimum of three samples after warmup. Times -below are milliseconds per batch; profile collection is off during measurement. - -| CPU operation | 1 view before / after | 2 views before / after | 8 views before / after | -| --- | ---: | ---: | ---: | -| Raw decode and verify | 1.885 / 0.486 | 3.736 / 0.971 | 15.290 / 4.099 | -| Compressed decode and verify | 1.921 / 0.535 | 3.846 / 1.070 | 15.533 / 4.294 | -| Automatic encode, decode and verify | 3.991 / 1.213 | 7.984 / 2.431 | 32.428 / 10.286 | - -The post-change raw profile measures baseline/response/depth scans at -0.078 / 0.076 / 0.016 ms. Hashing now accounts for more of validation cost. -These are CPU measurements, not GPU or network performance claims; direct -import speed was not separately measured. Benchmark output stayed in the -terminal. Dev and optimized builds pass. Headless render passes 131,931 -assertions / 485 cases in portal-codec-samples-headless.log. Focused offscreen -Vulkan import and six-scenario nested lighting pass 2,856 assertions / 3 cases -in portal-codec-samples-gpu.log. Independent read-only review found no acceptance -gap. The separate 608 multi-pane ordering failures and broader render/product -acceptance requirements remain open. - -### Retained directional-shadow oracle remains red - -The seventh nested-lighting scenario enables real shadow casting with an angled -sun. The six previous scenarios explicitly disabled casting on every row and -therefore did not prove shadow interaction. Two native controls toggle only -the room caster or current-body caster, preserving geometry and light-fit -bounds. Both controls require receiver pixels to darken by more than 0.002, -for both body poses and both lighting revisions. - -The first fixture attempt used single-sided planes and failed its first native -control in portal-shadow-oracle-gpu.log. The shadow pipeline intentionally culls -front faces. Closed slab casters now provide back faces while keeping the -original front depths and receiver masks. This is a fixture correction, not a -production shadow change. - -The corrected run in portal-shadow-closed-gpu.log passes 2,712 of 2,726 -assertions. All native controls and the six earlier scenarios pass. Fourteen -full-image comparisons fail across three subtree roots, two body poses, two -lighting revisions and retained-old checks. Maximum HDR error is 0.139465 -against the unchanged 0.002 limit. The leaf pose-zero image has 44 mismatched -pixels in region (25,27,13,11). Expected, actual, difference and raw HDR artifacts -are under render-failures/nested-room-lighting/shadows-*. Dev build passes in -portal-shadow-closed-build.log. No performance conclusion comes from this run. - -Current composition retains scalar lighting and ambient derivatives but no -room shadow map. Its native shadow pass fits and draws current body/aperture -rows; retained room casters are absent. The room correction shader adjusts -ambient radiance only, so newly inserted body shadows cannot alter retained -room direct lighting. A complete fix must preserve light-space room occlusion, -the matching shadow projection and the room's direct-light response under -existing ownership and byte bounds. Reconstructing only visible room depth -would omit off-camera casters. This requirement remains open alongside the -independent multi-pane transparency ordering decision. - -Implementation constraint: native light fitting uses the union of all source -row bounds and current body bounds. A body outside the original bounds changes -the light matrix, so an old shadow image cannot simply be reprojected with exact -parity. Keep room caster geometry at the source. A prospective image-only path -requests the source shadow image for the shared matrix and exact retained -snapshot, then combines it with current body shadow depth locally. A source -that cannot serve that snapshot must refuse and refresh the capture rather -than mix revisions. Room directional response can carry unshadowed RGB and -original shadow visibility, allowing the existing unrounded baseline to apply -the new visibility delta. This design is not implemented or verified; shadow -image byte admission, ownership, readiness and retirement remain required. - -### Directional response output verified; shadow delivery remains open - -Deferred lighting now has an optional `directional-response` RGBA32F output -paired with `lighting-baseline`. Its RGB is the unshadowed directional term -after fog attenuation; alpha is the original four-tap shadow visibility. -The same shader invocation writes ordinary RGBA16F colour and its unrounded -baseline, preserving their common calculation. Background and authored final -colour have zero response and visibility one. The ordinary pipeline does not -request this output. A lazy three-attachment pipeline and graph-owned target -serve connected outputs, with tracked allocation and a directional output-byte -counter. Response adds 16 bytes per pixel, or 1 MiB at 256x256. - -Backend validation rejects response without baseline, shared output resources -and mismatched extents. Colour determines dimensions regardless of output -ordering. Graph serialization roundtrips the optional port, and devices only -need its RGBA32F capability when an optional output is connected. - -The new GPU oracle compares closed-caster shadow-on and shadow-off native -lighting with unchanged scene bounds. Response correction in both directions -matches the full-float baseline within the unchanged 0.002 HDR bound, including -direct intensity eight, material AO, emission and fog. Independent ordinary -deferred colour agrees with the optional-output path. A bounded camera phase -sweep positively exercises fractional PCF visibility and its correction; -empty output, output order, mismatched sizes, missing baseline and shared -attachments are also checked. - -An initial build caught accidental edits in unrelated callbacks; those were -removed before GPU execution. An initial GPU comparison read the native lit -target after volumetrics reused it, causing four fixture failures. Both oracle -pipelines now stop immediately after deferred writes. No tolerance changed. -The final dev build passes in portal-directional-fractional-build.log. Focused -Vulkan passes 271,282 assertions / 4 cases in portal-directional-final-gpu.log, -including all eighteen scaled transparent/body depth cases. Headless render -passes 131,931 / 485 in portal-directional-headless.log; graph passes 10,597 / -229 in portal-directional-graph.log. Shader checking passes 42 modules with -SPIR-V and MSL structural validation in portal-directional-shadercheck.log. -No Metal hardware, sanitizer, interactive Studio or release timing was run. - -This output is a prerequisite, not the retained-shadow fix. It is not yet -transported in PIMG17 or consumed by retained composition. The broader import -and seven-scenario lighting run passes 3,366 / 3,380 assertions, retaining the -same fourteen shadow failures in portal-directional-retained-gpu.log. Source -shadow snapshots, shared light fitting, bounded delivery, current-body depth -composition and atomic image ownership remain required. Native 2048x2048 D32 -maps are 16 MiB each, so copied delivery cannot rely on compression to meet the -4 MiB wire bound; a complete design must account for retained and scratch maps -under GPU admission limits and share compatible maps across views. - -### PIMG18 directional response ownership and delivery - -The optional directional response now travels through production capture, -PIMG18 encoding, borrowed preflight, inbox/tree accounting and GPU import. -Presence uses flag 256 and compression flag 512 in the existing 16-bit mask. -The plane requires the complete ambient set, depth, opaque scope and captured -lighting. Its exact 16-byte-per-pixel size, hash, finite nonnegative RGB and -visibility in [0,1] are checked; negative zero remains valid. Transparent and -spatial layers cannot carry it. Ambient-only captures remain valid without the -new plane. PIMG17 packets are not accepted by the PIMG18 decoder. - -Six-plane captures cost 64 bytes per pixel, with 52 auxiliary bytes charged by -borrowed preflight before decompression. The wire limit remains 4 MiB; CPU and -GPU import limits remain 32 MiB. Per-image staging covers the maximum six-plane -extent at 16 MiB. A raw 256x256 six-plane payload fills 4 MiB before framing and -is refused; compressed payloads are still charged at their expanded size. -Tests cover raw/compressed roundtrips and truncations, invalid flags, hash-valid -bad samples, compressed invalid samples, inbox exact limits and tree preflight. - -Copied capture, resident capture/adoption, cache reuse, hash-only replacement, -plane removal, upload retries and retirement include the directional texture, -hash and pending capacity. Producer capture moves and hashes all six planes -from one frame. The nested lighting oracle now carries six-plane room captures -through both lighting revisions and retained-old checks without room reuploads. - -Review found and corrected the capture port whitelist, direct transparent-layer -admission and tree capacity accounting. A new exact-byte eye-image test then -reproduced a remaining five-output guard failure in -portal-directional-eye-red-gpu.log. Raising that guard to six makes imported -directional samples reachable through the graph. The test compares a distinct -17x9 response pattern, and all other planes, after upload and again after -resident recapture/adoption. Six uploads occur once; final drops release all -import and cache bytes. The fixed run passes in portal-directional-eye-fixed-gpu.log. - -Dev build passes in portal-directional-transport-fixed-build.log after adding -a missing test generator include; the final guard build passes in -portal-directional-eye-fixed-build.log. Headless render passes 134,163 -assertions / 487 cases in portal-directional-transport-headless.log. Graph passes -10,598 / 229 in portal-directional-transport-graph.log. GPU storage/lifecycle -passes 875,676 / 13 in portal-directional-storage-gpu.log, excluding the already -red multi-pane ordering fixture. Producer, source, import and seven-scenario -lighting pass 131,422 / 131,436 assertions, five of six cases; only the same -fourteen shadow comparisons fail in portal-directional-transport-gpu.log. -The first combined GPU filter misspelled resourceimage; the separate storage -run above supplies that missing coverage. - -`just portal-ambient-bench 3` passes on the optimized build with the existing -five-plane 256x256 fixture under PIMG18. Roundtrip batch minima are 1.252 / 2.532 / -10.684 ms for 1 / 2 / 8 views. Payload and framing sizes are unchanged. Output -stayed in the terminal. These figures do not measure the new sixth-plane cost -or GPU performance. Existing aggregate initializer warnings remain unrelated -to this change. No shader source changed in this delivery step. - -The directional response is now delivered but retained composition does not -yet apply its shadow delta. Source shadow snapshots, matching light matrices, -bounded shadow-image delivery and current-body shadow composition remain open, -as do the broader render and product acceptance gates. - -### Retained shadow delivery constraints, inspected 2026-09-09 - -Source capture currently retains image tokens and pixels, not immutable caster -assets. `WorldFrame` is reused during producer pumping. Copying draw rows and -joints would not preserve later mesh, texture or shader revisions. An old room -may reuse a matching captured source shadow image, but cannot request current -casters under an old image revision without checking the complete source state. -A changed fit or unavailable old state requires a complete capture refresh. - -Native fitting uses all source and body row bounds, including noncasters and -off-camera rows. Capture must carry the source bounds and exact light matrix; -reuse requires the union fit with the current body to match that matrix. -`EyePlayer` hides primary camera rows while preserving their shadows, so it -cannot be repurposed as authenticated shadow-caster exclusion. - -The native target uses the selected depth format, with D32, D24 and D16 device -fallbacks. A D32 delivery path must explicitly reject a different native format. -Vendored SDL supports exact depth-to-depth texture copies with matching formats -and depth transfer-buffer upload/download. The existing global shadow target -can be scratch: copy source depth, then load it while drawing body casters with -cycling disabled. No extra global scratch target is required. This is inspected -API support, not a completed GPU delivery path or Metal hardware proof. - -The existing image capture API requires a colour plane, matching extents and at -most 512 pixels per side. Shadow capture therefore needs a separate depth path. -Sixteen 512-square D32 tiles cost 1 MiB each and fit the 4 MiB message bound even -without compression. Admission must reserve the full expanded 16 MiB before -accepting tiles and bind every tile to one authenticated snapshot and fit. -Mixed snapshots, conflicting duplicate tiles and incomplete transfers must -never publish a ready map. This tiled protocol is still to be implemented. - -One retained source map plus a six-plane 256-square eye image costs 20 MiB of -the existing 32 MiB import limit. The renderer's existing global scratch costs -another 16 MiB outside that import limit. Two distinct retained source maps fill -the import limit before any eye planes. Sharing equal maps does not solve the -worst case for recursive worlds or concurrent revisions. Delivery scheduling -and explicit readiness under pressure remain required; no limit was widened. - -### Native directional correction primitive - -`ambient-correct` now accepts an optional all-or-none group: directional -response, retained room depth, retained room normal and an explicit D32 shadow -map. The original three-input ambient shader remains unchanged. The new lazy -variant reconstructs room-world positions with the capture camera and applies -both ambient and directional deltas before one RGBA16F store. Native deferred -lighting and correction share the same PCF function, bias, taps and sampler. -The explicit map enables sampling independently of local caster presence and -supplies its own texel size. It must match the current light matrix and world -domain; this node does not authenticate source snapshot metadata. - -Backend installation rejects all fourteen partial combinations. Execution -checks eye-plane formats/extents, square D32 shadow format and output aliasing. -The map can have a different extent from the eye. Headless render passes -134,227 assertions / 488 cases in portal-shadow-correction-headless.log, -including all sixteen optional-input combinations and document roundtrips. -Graph passes 10,598 / 229 in portal-shadow-correction-graph.log. Shader checking -passes 43 SPIR-V/MSL modules in portal-shadow-correction-shadercheck.log. - -The GPU oracle imports six planes captured from native shading and executes -the actual correction node against a changed native map. Both signs of the -shadow delta, intensity eight, fog, emission, material AO and fractional PCF -agree within the unchanged 0.002 HDR bound. The initial run had sixteen -failures because the new ambient-response producer reused undeclared readback -storage. Explicit final capture reads fix that lifetime. The first lifetime -fix also put a frame capture between view nodes and was correctly refused; -the correction graph now branches before that final capture. The receiver -keeps native shadow clearing active when the closed caster is disabled, so -the explicit map actually represents the unshadowed state. Final dev build -passes in portal-shadow-correction-map-build.log. Focused Vulkan passes -355,681 / 4 in portal-shadow-correction-map-gpu.log. - -The production retained-tree graph is not connected to this optional group -until it owns an authoritative source-plus-body map. Its seven-scenario test -still has the same fourteen shadow failures. Combined with scaled transparent -body checks, portal-shadow-correction-retained-gpu.log passes 3,168 / 3,182 -assertions, one of two cases. This primitive does not close retained shadows. -No sanitizer, Metal hardware, interactive Studio or GPU release timing ran. - -`just portal-directional-bench 3` now measures six-plane PIMG18 CPU delivery. -The timed fixture is 255-square so raw framing fits the unchanged wire bound. -Setup also verifies compressed 256-square equality and raw refusal at -4,194,686 bytes. At 255-square, 1 / 2 / 8-view payloads are 4,161,600 / -8,323,200 / 33,292,800 bytes; compressed wire sizes are 16,475 / 32,681 / -135,382 bytes. Optimized three-sample batch minima in milliseconds: - -| Operation | 1 view | 2 views | 8 views | -| --- | ---: | ---: | ---: | -| Raw decode and verify | 0.674 | 1.347 | 5.981 | -| Compressed decode and verify | 0.733 | 1.467 | 5.886 | -| Encode, decode and verify | 1.663 | 3.315 | 13.945 | - -Benchmark output stayed in the terminal. The existing five-plane default job -remains available. These measurements exclude shadow-map delivery, GPU work -and network latency. Existing aggregate initializer warnings remain unrelated. - -### Exact native shadow capture and shared fitting - -`View::DirectionalShadowBounds` now accepts an explicit enclosing AABB in the -view's world. Native views keep their ordinary all-row fit. Invalid, inverted, -overflowing or non-enclosing overrides refuse rendering; source bounds remain -separate from the chosen domain. Override changes invalidate retained view -content. A GPU oracle renders full native casters and then source/body subsets -under the shared fit: the minimum of the two subset depth maps equals the full -native map exactly at scales 0.37, 1 and 3.1, including an off-camera caster. - -The new per-view `shadow-capture` node reads the native D32 map into -`ResourceImage::Depth`, with no colour or auxiliary planes. -`ResourceImageKind::DirectionalShadow` distinguishes this result. Its `Shadow` -metadata owns source bounds, fitted domain bounds and the exact column-major -light matrix, alongside the existing producing-frame identifier. Non-D32 -native formats and resident delivery are explicitly refused. This is copied -capture ownership, not a resident shadow-import API or a wire protocol. - -Capture runs before another view can overwrite the global shadow target. -Pending shadow captures force fresh world work, including all-one maps for -empty sources. Explicit domains and pending captures isolate their world -preparation; `FramePreparation::InvalidateWorld` restores ordinary preparation -for following views without repeating completed frame effects. Tests compare -two worlds' batched captures with separate native renders and verify that an -explicit fit does not leak into the next ordinary view of the same world. - -All retained capture transfer allocations, including colour capture, now share -an explicit 32 MiB cap. Idle transfer buffers are reclaimed before allocation -refusal; recorded or submitted buffers remain protected until their fences -complete, including cancellation. Two native 16 MiB readbacks can be staged -together; a third returns failure without allocating. This is a capture -transfer-buffer bound, distinct from the existing portal import limits and -from owned CPU images returned to callers. The five capture slots stay bounded. - -The first build caught missing private test constants/namespace qualification. -The first GPU run then reproduced an empty-source crash. GDB identified -`BindInstanceBuffers` passing nonexistent storage into Vulkan. A clear-only -shadow pass now binds no draw resources. The fixture originally mistook -`FrameResult::Ran` for evidence of GPU clearing; the new `render.shadow.clears` -counter verifies no clear occurs without a request and exactly one occurs for -an empty-source capture. No tolerance changed. - -Final dev build passes in portal-shadow-capture-batch-build.log. Headless render -passes 134,244 assertions / 489 cases in portal-shadow-capture-headless.log. -Graph passes 10,600 / 229 in portal-shadow-capture-graph.log. Focused Vulkan, -including existing image lifecycle and directional correction, passes -1,231,849 / 22 in portal-shadow-capture-final-gpu.log. Coverage includes exact -16 MiB depth bytes, same-frame colour/shadow identity, matrix/bounds metadata, -queued and submitted cancellation, empty maps, capacity refusal and retry, -cross-world captures, shared fit, malformed domains and ordinary-view recovery. -The existing multi-pane ordering failure remains excluded from this image -lifecycle run. No shader source changed in this step. No sanitizer, Metal -hardware, interactive Studio or release GPU timing ran. - -The production retained tree still has fourteen shadow failures: 2,754 / 2,768 -assertions pass in portal-shadow-capture-retained-gpu.log. Next work is binding -source exclusion and snapshot identities, bounded tiled delivery, imported -shadow ownership, copying source depth into scratch and loading current body -casters before the correction node. Multiple retained maps and revisions must -respect admission and readiness; capture primitives alone do not close this -gate or the full render plan. - -### Tiled shadow delivery and imported source/body composition - -`PortalShadowImage` carries a native 2048-square D32 image as sixteen raw -512-square tiles. Each packet repeats the expected producer incarnation, eye -key and pixel hash, capture tick, content/lighting revisions, excluded player, -source/domain bounds, light matrix and full depth hash. Assembly reserves its -16 MiB budget before accepting tiles, checks each tile hash and finite depth -samples, accepts exact duplicates, and publishes only after all tiles and the -full image hash agree. Cancellation releases the allocation. The caller must -supply an authenticated expected snapshot; packets do not establish trust. -There is no presentation-channel or source-job integration yet. - -The renderer now owns immutable imported shadow handles. Their actual D32 -textures and pending CPU capacity share existing portal import limits. Two -maps fill the 32 MiB limit, leaving no room for retained eye textures; admission -refuses further imports without consuming their inputs. Uploads use the shared -16 MiB staging buffer, retain CPU data after failed submission, and release it -on successful submission. Drop and world retirement release ownership. Code -review checked resident-image adoption against the same texture admission -limit; pending source captures remain separate capture allocations. - -A matching view requires the bound world, explicit enclosing domain and exact -native light matrix. Its shadow pass uploads once, copies the source depth into -the native shadow target, then loads it while drawing current body casters. -The body compositor selects the complete directional correction graph and -checks the retained eye identity, producer, exclusion and revisions. Imported -eye capture ticks now survive direct import, replacement, reuse and layer sets. -Missing or different ticks refuse composition. Resident colour adoption has no -authenticated producer tick and therefore cannot establish this pairing. - -The GPU integration test captures a source room, sends its exact depth through -the tile codec, imports it, and renders only current body geometry. Combined -D32 bytes equal a full native render exactly. Exported body-compositor colour -matches within the unchanged 0.002 tolerance. Disabling either caster changes -visible lighting, so parity does exercise shadows. Coverage also verifies one -upload across repeated views, shared shadow/eye capacity refusal, release, and -a valid but stale-tick map refusing the otherwise matching retained image. - -Dev build passes in portal-shadow-delivery-final-build.log. Focused Vulkan -passes 1,282,685 assertions / 23 cases in portal-shadow-delivery-final-gpu.log, -including previous capture, fitting, image lifecycle and correction tests. -Headless render passes 134,844 / 493 in -portal-shadow-delivery-final-headless.log. Graph passes 10,788 / 230 in -portal-shadow-delivery-graph.log, including complete directional bindings for -eye/seam documents with ambient prerequisites enabled automatically. The first -build caught a test constant colliding with Catch's CAPTURE macro, now fixed. -No shader changed, tolerance widened, or interactive Studio check ran. No -release GPU timing, sanitizer or Metal hardware verification was performed. - -This does not complete retained tree shadows. Authenticated source exclusion, -source snapshot production and routing, per-node shadow association, refresh -on changed fitting, and bounded scheduling across multiple retained revisions -remain required. The tile encoder currently validates the full 16 MiB image -for every tile; this has no measured throughput claim and needs profiling -before use in the production path. - -The production retained-tree rerun remains at 2,754 / 2,768 assertions with -fourteen shadow comparison failures in portal-shadow-delivery-retained-gpu.log. -The retained-old-lighting pose reports maximum error 0.139465 against 0.002. -The new standalone import/compositor route is not yet connected to this tree. - -### Serial tree shadows and explicit source-body exclusion - -The renderer now exposes Begin/Poll/Accept/Cancel for retained tree composition. -One job owns copied body rows, palettes and content-owner bindings. Common tree -preparation serves this path and the existing synchronous compositor. Each -pending request identifies one node's accepted eye image, producer incarnation, -capture tick, revisions, exclusion and mapped body/aperture bounds. Nodes run -from children toward the root. Accepted maps must match that identity, the -source/body domain union and the native light matrix. Only Poll transfers the -completed root image to its caller; a late Accept cannot consume the result. - -Only one job is admitted. It checks the existing import byte limits before -requesting/accepting another 16 MiB map and preserves the pending request on -budget refusal. Child images remain owned until their parent consumes them. -A real ordered-queue fence gates map retirement and advancement, avoiding an -unbounded backlog of deferred map allocations. Cancellation, tree retirement -and asset-epoch changes invalidate work. Submitted cancellation retains GPU -resources until the fence completes; normal Render calls also reap cancelled -jobs. These are import ownership limits, separate from graph scratch, capture -transfer buffers and driver allocations. No latency or throughput improvement -is claimed for this serial path. - -The nested lighting oracle now drives this API with source fixtures that own -immutable scene inputs and lighting for two revisions. All fourteen previously -failing shadow comparisons pass without changing the 0.002 tolerance. They -cover three subtree roots, two body poses, two lighting revisions, and retained -old lighting after the sun direction changes. Both casting directions still -have visible receiver controls. Tests destroy caller geometry/target storage -after Begin, refuse stale ticks and a competing map's byte pressure, retry after -release, cancel pending work, retire its tree, and send a late final response. -This verifies the renderer job; it does not connect host source jobs or network -tile routing automatically. - -PIMG and capture-tree wire version 19 add a distinct `RetainedBodyPlayer` account -identity. Ordinary `EyePlayer` still hides only primary colour while preserving -shadows. The new ordered capture profile removes the authorized body from both -source colour and shadow rows, after computing the original full native fitting -domain. Selection covers native/held rigs and decoded forwarded rows, remaps -primary-hidden row indices, and does not infer foreign ownership from coincident -local handles. Tree nodes and admission bind the same retained-body identity. - -`PortalImageProducer::SetRetainedBodyAuthorization` supplies the host policy for -an exact requesting endpoint incarnation and canonical account. Nonempty -exclusion defaults to refusal; authorization is checked before work, after waits -and before publishing completed captures. Application policy and automatic -request opt-in are not yet connected. The GPU producer test proves ordinary eye -selection preserves D32, authorized exclusion changes source colour and D32, -shared-domain depth equals an independent remaining-room render, room-only -fitting differs, and revocation after submission cannot publish a success. - -`SourceEmpty` now distinguishes no source rows from the native empty-scene -fitting fallback. Empty source bounds are canonical zero and empty depth is -exactly clear. Capture metadata also includes an imported seed's source bounds -when recapturing a combined map. Import and job fitting no longer union a -fictional origin box into an empty non-origin source. Tick zero is accepted as -a legitimate initial ECS tick; missing imported tick identity remains distinct -and refused. Wire tests cover both new cases and their malformed alternatives. - -Verification: portal-shadow-tree-verified-build.log passes. Headless render -passes 135,394 assertions / 500 cases in -portal-shadow-tree-verified-headless.log. Vulkan passes 194,347 / 16 in -portal-shadow-tree-verified-gpu.log, including tree composition/import, source -runtime, exclusion and recovery. The separate existing image/shadow lifecycle -run passes 1,231,849 / 22 in portal-shadow-tree-lifecycle-gpu.log. Existing -multi-pane ordering failures remain excluded from that lifecycle filter. No -shader changed, graph algorithm changed, sanitizer ran, Metal hardware ran, or -interactive Studio session ran in this step. - -The first runs exposed an empty-source metadata rejection, an ordinary request -identity change from hashing an absent exclusion, and rejection of unused caller -lights in the old-image job path. All are fixed. Broader runtime testing exposed -four appearing-child recovery assertions: a one-message presentation queue -returned Full for the second child and was treated as Unsupported. That branch -now retries transient transport pressure after cancelling the unsent inbox and -resident reservations. The existing copied/resident recovery cases pass. Temporary -production diagnostics were removed. Fixture mistakes in the shadow port name, -eye clip plane, light direction and test-only constants/constructor were corrected; -map comparisons avoid dumping entire 16 MiB vectors on failure. - -Next source integration must capture shadow and eye data in one producing frame, -construct an authenticated manifest, route bounded tiles to the pending node, -and retain or refuse the exact old source snapshot when fitting changes. There -is no retained caster asset revision pinning yet. The current ordered pipeline -uses all five capture slots when spatial overlay is present. A sixth bounded -slot can support the complete bundle without increasing the 32 MiB capture -transfer cap: padded worst cases under current pixel admission are 24,840,192 -bytes without overlay and 23,740,928 with overlay. This capacity change and the -source collector are not implemented yet. Multi-view scheduling, source policy -installation and the full R01-R17/P0-P12 plan remain open. - -`just portal-directional-bench 3` builds and passes under PIMG19. Raw 256-square -six-plane admission still refuses 4,194,686 bytes; compressed exact roundtrip -accepts 17,545 bytes. At 255 square, three-sample minimum CPU roundtrips for -1 / 2 / 8 views are 1.695 / 3.395 / 14.438 ms. Plane and wire byte totals are -unchanged from the preceding codec measurement. Output stayed in the terminal. -This measures the existing eye-image codec, not tiled shadow transport, GPU -composition, network latency or end-to-end frame cost. The optimized build -exposed missing aggregate defaults on the new retained-body selection fields; -explicit empty defaults remove those warnings. Earlier unrelated aggregate -initializer warnings remain. - -Final explicit-default build passes in portal-shadow-tree-defaults-build.log; -formatting and diff checks pass. The temporary diagnostic failure log is kept -as portal-shadow-recovery-diagnostic-gpu.log.gz because the original failed -vector assertion printed both complete depth maps. - - -## Same-frame source shadow retention and manifest admission - -The ordered retained-body source profile now queues its native D32 map alongside -opaque, transparent/overflow and optional spatial-overlay captures. Renderer -capture capacity is six; the shared transfer allocation bound remains 32 MiB. -Collection requires matching nonzero renderer CaptureFrame values and validates -the native dimensions, kind and metadata before publishing the eye. World tick -0 remains valid and is preserved independently of the renderer frame number. -The synthesized leaf tree now preserves RetainedBodyPlayer too. - -Each producer reserves at most two native maps, 32 MiB total, before submitting -the GPU capture. The reservation accounts for maps still being captured and maps -awaiting retrieval; actual retained CPU bytes are reported separately. Successful -eye delivery makes the original owned map retrievable once through -TakeShadow(exact requester incarnation, exact eye, now). Pending maps cannot be -taken. Endpoint/policy changes, cancellation and Clear release ownership; a ready -map expires one second after eye delivery. Retrieval never samples a later world -revision. These are per-producer retention bounds, separate from the unchanged -renderer transfer/import/staging bounds, not a new global host memory budget. - -The manifest codec reuses the canonical SHDW snapshot prefix used by tiles. -Decoding requires exactly one complete manifest and rejects trailing tile data, -truncation, oversized strings and invalid metadata without changing the output. -MatchesPortalTreeShadowRequest binds producer, eye, tick, revisions, eye hash, -exclusion, exact source/body domain and native light matrix. The pending request -now owns its accepted LightDirection; both pre-assembly checks and renderer -acceptance use the same matcher. Host envelope authentication remains required. - -Verification: - -- Library and test builds pass: portal-shadow-pair-library-build.log, - portal-shadow-pair-test-build.log and portal-shadow-pair-final-build.log. - Existing unrelated aggregate-initializer warnings remain. -- Headless render passes 136,066 assertions / 503 cases in - portal-shadow-pair-headless.log. The subsequent change only adds GPU fixture - overlay coverage and was compiled in the final build. -- Final offscreen Vulkan source/tree/import/runtime checks pass 194,488 / 17 in - portal-shadow-pair-final-gpu.log. The actual source fixture includes a visible - spatial overlay and therefore six distinct capture resources. It checks exact - native D32 bytes, paired metadata, wrong requester/key refusal, take-once, - revocation, two-map saturation, third-map refusal, expiry and pending Clear. - A generic six-result group also verifies same-frame collection and seventh - slot refusal. No image tolerance was changed. -- Formatting and whitespace checks pass. This is dev Vulkan correctness - evidence. No new release timing, sanitizer, Metal or interactive Studio run - was performed. The earlier codec benchmark does not measure these maps. - -Next integration must retain the authenticated requester chain. A child map is -owned by its immediate parent's internal Pending.Replies endpoint; the final -root consumer cannot retrieve it using its own requester. Finish currently drops -the parent/child job associations after tree delivery. Retain a bounded delivered -tree route record binding parent requester + parent eye to each accepted child -producer, child eye and original internal requester. Pulls must traverse these -records with current endpoint and policy checks, never impersonate a requester -named in an untrusted payload. Relay bounded packets without assembling maps at -every intermediate producer. - -PortalImageHost::Pump and PumpDriverLink are the existing scheduling/authenticated -transport boundaries. Host integration still needs explicit trusted retained-body -policy configuration, composition begin/poll/cancel ownership, shadow-message -demultiplexing, and a receiving assembly charged against existing renderer CPU -import admission. Keep one map/tile/assembly in flight per serial job. Validate -the manifest before tile allocation. A changed exact domain must refuse or -refresh the eye; old caster mesh/texture/shader revisions are not pinned, so -regenerating an old map from current source assets remains invalid. Automatic -host routing and full R01-R17/P0-P12 completion remain unfinished. - - -Final lifecycle follow-up passes 1,231,853 assertions / 22 Vulkan cases in -portal-shadow-pair-lifecycle-verified-gpu.log. The first run had four failures in -one ResourceImage capacity test: an earlier generated-group setup still left -two free slots while expecting refusal at the former five-slot limit. Its stale -oversized-group check also used six entries. The fixture now leaves one slot -free for atomic-group refusal and uses seven entries for oversized admission. -No production change was needed. The first result is retained in -portal-shadow-pair-lifecycle-gpu.log; the test-only rebuild passed in -portal-shadow-pair-capacity-build.log. The run includes the existing shared -transfer-budget, cancellation, idle reclaim, native-domain and directional -response checks. Known transparent-layer coplanar/intersection failures remain -outside this focused filter, unchanged and unresolved. - - -## Retained requester routes, host policy and charged shadow assembly - -Each retained source capture now reserves a delivered route record before GPU -admission. Four records per producer each hold at most sixteen accepted target -eyes, with bounded endpoint/key strings. They bind the exact parent requester -and eye to the original direct-child requester, actual transport endpoint and -accepted child-root eye. ResolveShadowRoute returns these owned values only -from a delivered record, after authorization and current endpoint/published -identity checks. The local target resolves to the original requester and -producer endpoint. Taking a map does not destroy its child route record. -Records expire one second after eye delivery; Clear, policy changes and endpoint -retirement release them. Retirement of any recorded descendant invalidates the -whole record. ShadowUsage reports route ownership and conservative metadata -bytes separately from the two-map CPU reservation. - -PortalImageHost::SetRetainedBodyAuthorization installs an owned trusted policy -for a local world, applying it to both current and future producers. The default -remains denial. Replacing or removing policy clears affected capture work. -Policies and producer entries pin ecs::Store::Identity, so a reused WorldId or -same world name cannot inherit old authorization. Retired entries are pruned; -policy count is bounded by the existing maximum producer count. RemoveWorld and -Clear discard policies. No game-specific authorization is inferred or installed -by this API. - -Renderer-owned tile assembly is now attached to the pending serial tree job. -BeginPortalCaptureTreeShadowAssembly validates the manifest with the existing -exact matcher before allocating. Its 16 MiB owner is charged against the same -PendingCpuBytes used by eye and shadow imports. AcceptPortalCaptureTreeShadowTile -requires the exact current job/node. The final tile tries to import and compose; -BudgetExceeded retains the completed map and charge, and -CommitPortalCaptureTreeShadowAssembly retries without replaying the tile. -Successful import transfers the charge once, with no yield between owners. -Cancellation, tree/world retirement and shutdown release assembly ownership; -submitted GPU resources retain their existing fence lifetime. The direct -full-image acceptance API remains available when no assembly is active. - -Verification: - -- Builds pass in portal-shadow-routes-build.log and - portal-shadow-routes-final-build.log. Existing aggregate warnings remain. -- Headless render passes 136,501 assertions / 506 cases in - portal-shadow-routes-verified-headless.log. New host tests send actual owned - requests and check current/future policy forwarding, replacement/removal, - served/unserved world-slot reuse, configuration bounds and capacity recovery. - The first headless run had six failures in two new cases because the fixture - selected Eye projection while leaving the default nonzero seam clip plane. - Setting the required zero clip plane fixed the setup; the encoder remains - unchanged. portal-shadow-routes-headless.log retains the first failure. -- Offscreen dev Vulkan passes 179,651 / 21 in - portal-shadow-routes-initial-gpu.log. The later rebuild changed only the - headless host fixture. The nested source test proves root-requester refusal at - the child, original nested requester recovery, root-map take without route - loss, exact eye/endpoint checks and child withdrawal. Leaf tests cover - pre-delivery refusal, expiry, four route records independent of map ownership, - fifth-route refusal before rendering and Clear reclamation. -- The native retained-tree lighting oracle now exercises real tile assembly, - duplicate manifest admission, stale job/node and damaged tile refusal, - cancellation, shared CPU pressure, completed-map texture pressure, commit - retry and final native colour parity. Existing runtime, host GPU, tree import - and composition cases are included. No image tolerance changed. -- Formatting and whitespace checks pass. No release performance measurement, - sanitizer, Metal or interactive Studio check was performed for these changes. - -Next: connect these APIs through bounded authenticated shadow control messages, -manifest/tile demultiplexing and PortalImageHost composition begin/poll/cancel -scheduling. Forward pulls through the retained route chain; never take a nested -map under the root's requester identity. Keep one outgoing map/tile and one -charged receiving assembly per serial job. Exercise actual multi-hop relaying, -transport Full/retry, cancellation and endpoint replacement. Current tests prove -the two-node requester boundary, not complete distributed transport. Existing -maps retain their original exact domain; changed-domain old-eye refitting still -requires pinned source asset revisions or explicit full eye refresh/refusal. -The end-to-end host flow and full render plan remain unfinished. - -### Authenticated shadow transport and host composition follow-up - -SHCT control messages now carry bounded manifest, tile and cancellation pulls. -Successful replies must match the exact target producer, accepted eye and tile; -the authenticated presentation envelope supplies requester identity. No requester -override crosses the wire. Canonical SHDW validation checks tile metadata, hashes -and samples without allocating a full receiving map. The existing 4 MiB message -bound and 16 MiB original shadow map remain unchanged. - -Producers serve their original retained maps and relay descendant pulls through -the recorded immediate requester chain. Five bounded transfer contexts allow a -producer to reappear in a capture path. They share a 4 MiB outbound wire budget. -Lost replies, Full and BudgetExceeded retry under a fixed ten-second deadline; -duplicate child pulls preserve correlation and do not renew that deadline. -The source separates shadow replies from ordinary image completions in one -bounded mailbox. The renderer retains ownership and charging of tile assembly. - -PortalImageHost now exposes BeginBodyComposition, PollBodyComposition and -CancelBodyComposition. It copies the current body into the renderer job, pulls -each exact manifest and tile, retries assembly admission and commit, and returns -one host-owned result. Completed compositions retain their capture and route for -another body pose. Retirement, cancellation and replacement release ownership. -The source capture lease is fixed at its first pin, at most ten seconds, while -the original image expiry stays intact. A fresh eye request can remain pending -beside retained pixels; accepted replacement retires the old lease. Repeated -composition does not renew it. Cancellation targets the captured published root -identity while transport authentication uses the actual carrying endpoint. - -Host cancellation uses a bounded queue and retries the existing Part17 reply for -one second. Producer cancellation releases local ownership and dispatches child -cancellation. It does not confirm descendant reclamation; fixed expiry remains -the fallback when a child cannot admit that control message. - -Verification: - -- The integration fixture first reproduced two production failures: slow - transfer lost the source eye at its ordinary one-second expiry, and completion - cancelled the map needed for a second pose. Both are fixed by the leases above. - portal-shadow-transport-lifetime-gpu.log retains those failures. -- Final dev build passes in portal-shadow-transport-final-build.log. The first - lease build found a shifted positional Preview initializer; named fields fixed - that compile error. Existing missing-field warnings remain. -- Headless render passes 137,818 assertions / 509 cases in - portal-shadow-transport-lease-headless.log. -- Offscreen dev Vulkan transport passes 1,161 assertions / one generated case - in portal-shadow-transport-verified-gpu.log. Its nine scenarios cover a lost - manifest pull, three distinct rooms, slow transfer, repeated composition past - ordinary expiry, A-to-B-to-A producer routing, cancellation during charged - assembly, a full reply mailbox, a fresh request before pinning and a fresh - request after pinning. Repeated composition expires at the original deadline. - Completed paths check visible output, exact shadow upload bytes and actual - presentation byte traffic. Cancellation and retirement check CPU reclamation. -- Earlier fixture failures were corrected without changing image tolerances: - opaque-lighting output needs the matching eye viewer scope, leaf host requests - need recursion enabled to obtain a capture tree, and the host combines camera - revisions before sending them. Logs preserve those initial failures. -- Existing runtime, host and native tree lighting GPU checks pass 177,568 / 18 - in portal-shadow-transport-lifecycle-gpu.log. Two requested tag names matched - no cases; a separate corrected run covers tree import and composition, passing - 2,082 / 3 in portal-shadow-transport-tree-gpu.log. -- Formatting checks pass. No release GPU performance, sanitizer, Metal or - interactive Studio verification has been performed for this transport slice. - -Next: connect trusted game authorization and current-pose composition into the -product loop. Automatic depth-zero layer-to-tree admission, changed-domain eye -refresh policy and complete disconnect/restart cancellation coverage remain -open. Old source asset revisions are still not pinned; changed-domain requests -must refuse or obtain a full new eye, never redraw an old map from current assets. -The full R01-R17/P0-P12 render plan remains unfinished. - -### Depth-zero retained body admission and product audit - -Authenticated retained-body layer replies now become one-node imported trees at -the receiving source. The node uses the pending capture camera/projection, -published producer identity and exact retained player from the admitted request. -It uses the existing tree upload, atomic publication, pin and retirement paths. -Ordinary ordered layers keep their existing flat import and PIMG is unchanged. -Host shadow composition therefore no longer needs a nonzero recursion depth for -a leaf. The transport fixture now requests depth zero in all seven leaf scenarios. - -Verification: - -- Dev build passes in portal-shadow-leaf-fixed-build.log. The first build found - an unqualified duration literal in the new test; std::chrono::seconds fixed it. -- Headless render passes 137,818 / 509 in portal-shadow-leaf-headless.log. -- Offscreen dev Vulkan passes 1,618 / 4 in portal-shadow-leaf-gpu.log, covering - the nine transport scenarios, ordinary and retained leaf admission, existing - flat layer publication and recursive tree publication. New checks verify - camera, producer, request and retained identity, pre-upload invisibility, - capture pin admission and complete cleanup. -- Formatting and whitespace checks pass. No release performance, sanitizer, - Metal or interactive Studio run was performed for this change. - -The product audit found prerequisites beyond the call-site swap. Scene.cpp still -uses EyePlayer and synchronous composition. Demand collection forces depth zero -and does not request RetainedBodyPlayer; whole-eye submission is separate. -Server connection/player/receipt ownership is not carried by PresentationBindings, -so a supervised producer cannot currently derive an authoritative exclusion grant. -World-local numeric UserId equality cannot authorize unrelated authorities. - -The current async job copies its pose at Begin, then fetches maps across multiple -round trips. Its completed image is not proof of current-frame avatar motion. -Fresh accepted eyes can also cancel every in-flight job, and each completed node -releases its imported shadow texture, so another pose fetches again. Fair host -scheduling, current-pose presentation, ownership grants/delegation, and first-person -shadow/child-view rig preservation must be addressed before enabling the new -product path. RENDER-REFACTOR-TASKS.md records concrete integration and acceptance -requirements. No product call was switched to a path that lacks those guarantees. - -### First-person retained rig and receipt ownership follow-up - -Retained-tree composition now accepts root primary visibility selection without -dropping the rig rows. The asynchronous job owns EyeRig, EyePlayer and validated -sorted hidden-row indices, including their metadata charge. Root composition uses -that selection; child composition clears it. Both synchronous and asynchronous -paths retain all body geometry for directional fitting, shadow casting and child -views. Invalid, duplicate and unsorted hidden indices refuse before submission. - -PresentationPeer::OwnsReceipt provides the exact live alias ownership lookup -needed to join a presentation requester to its authenticated server connection. -It refuses another peer's receipt, original client addresses, withdrawn or closed -receipts, and externally replaced endpoint incarnations. It does not itself grant -body exclusion or propagate policy to a producer. - -Verification: - -- Dev world and render builds pass in portal-receipt-owner-build.log and - portal-first-person-shadow-build.log. -- All world tests pass 32,650 assertions / 249 cases in - portal-receipt-owner-world.log, including receipt isolation and retirement. -- Headless render passes 137,818 / 509 in - portal-first-person-shadow-headless.log. -- Offscreen dev Vulkan passes 8,008 / 3 in portal-first-person-shadow-gpu.log. - The native retained lighting oracle adds first-person rig and explicit-index - scenarios, checks a visible-versus-hidden native difference, preserves child - lighting/shadow comparisons, and destroys caller selection storage after Begin. - Existing tree composition and all nine transport scenarios also pass. -- Formatting and whitespace checks pass. No image tolerance changed. No release - performance, sanitizer, Metal or interactive Studio run was performed. - -The authorization investigation found usable transfer provenance: -PortalTransferId identifies source world, incarnation and sequence; the source -can resolve an outgoing receipt from its exact player, and the destination can -resolve the committed live player from that receipt. Destination reservation also -binds the connecting authenticated identity. This mapping must scope grants; -world-local numeric player equality is not a substitute. Copied geometry currently -carries scalar Player identity only and loses foreign player identity on re-encode, -so grant transport alone cannot preserve ownership through nested copies. - -Next: implement trusted grant transport and scoped copied-row ownership, then -separate immutable shadow preparation from current-pose composition. Imported -shadow textures are still released per node and fetched again for each job. -Product scheduling, continuous eye replacement, latest-frame motion and the full -render plan remain unfinished. - -### Packed source shadow import foundation - -PortalShadowPacked defines an exact local depth representation with 64 consecutive -samples per block. Two descriptor words hold a minimum bit pattern and an absolute -payload offset/bit width. Integer deltas pack least-significant bits first; -constant blocks have no payload. Encoding measures output before allocation. -Decoding validates the complete canonical layout, offsets, minimal width, sample -range and exact end before allocating. CPU encoding/decoding preserves all accepted -normalized D32 bit patterns, including positive subnormals, and refuses budgets -transactionally. The network SHDW representation is unchanged. - -Renderer::QueuePackedPortalShadowImage retains eligible maps in a GPU storage -buffer. The existing shadow graph node decodes into native D32 scratch, then loads -current body casters. The map remains reusable across poses without another upload. -Packed buffers share the existing import GPU byte ceiling; pending vector capacity -and raw-plus-packed construction peak share the CPU ceiling. Upload staging keeps -its existing bound. TextureBytes reports logical import payload including these -buffers. Upload and decoder draw counters account for actual work. Raw imports -continue through their original copy path. The bounded shadow handle table now -allows a displayed tree and replacement candidate, subject to shared byte admission. - -The GPU subnormal test found a real representational limit: fragment depth output -flushes positive subnormal values to zero on the tested Vulkan device. Packed import -therefore detects those values and uses the existing raw D32 texture transfer, -preserving exact bits within the same budgets. It does not quantize or reject an -otherwise admissible depth map. portal-packed-subnormal-gpu.log retains the failed -direct-decoder test; the production fallback now checks that same input family. - -Verification: - -- Dev builds pass, including portal-packed-final-build.log. -- Headless render passes 138,027 assertions / 516 cases in - portal-packed-verified-headless.log. Seven new codec cases cover constants, - widths, block boundaries, independent bit packing, randomized values, hostile - layouts, invalid samples and exact budget/refusal ownership. -- Offscreen dev Vulkan passes 108,424 / 5 in portal-packed-verified-gpu.log: - standalone packed reconstruction, raw/packed native shadow and colour parity, - multiple moving poses without another map upload, exact subnormal fallback, - retained first-person/nested lighting and all nine transport scenarios. -- After adding the decoder draw counter, the focused import rerun passes - 101,801 / 2 in portal-packed-final-gpu.log. Formatting and whitespace pass. -- No release timing, full-tree pose performance, sanitizer, Metal or interactive - Studio run was performed. Storage correctness and transfer reuse are verified; - frame-rate suitability is not yet measured. - -This is the import/decoder foundation. Serial tree jobs still use the existing -per-node transfer path. Next connect whole-tree preparation and admission, an -independent prepared-tree lease, all-node current-pose domain validation and atomic -replacement before changing host/product scheduling. Trusted grants and scoped -copied-row ownership remain open, as does the full render plan. - -### Prepared capture-tree verification - -Prepared capture trees now retain child-first packed source shadows and their tree -lease before a current pose arrives. Prepared composition validates every node's -current body domain before submission, records the body pose as one queue-ordered -operation, and reuses the retained source maps across poses without further shadow -transfers. Owner release keeps the leased tree usable until preparation retirement. -Root primary selection still hides only the visible root copy, leaving full rig -geometry available to directional fitting, shadows and child views. - -Prepared maps use dedicated staging buffers only while preparation owns them. -Ordinary source shadows continue to use the shared portal staging buffer. The -shared buffer capacity is tracked separately from aggregate staging use, so a -normal eye-layer upload and a full raw D32 shadow can coexist without either -incorrectly borrowing the other's allocation. - -Verification on the final dev binary: - -- `ninja -C .cache/build/dev test_render -j2` linked successfully. The build log - is `.cache/build/dev/tests/portal-prepared-build.log`. -- Offscreen Vulkan `[shadow-import],[portal-tree-lighting],[portal-tree-import]` - passed 109,782 assertions in 6 cases. This covers raw and packed source imports, - native retained-room parity, prepared multi-pose zero-upload reuse, domain - refusal, replacement ownership and first-person root hiding. -- Headless `[render]~[gpu]` passed 115,936 assertions in 414 cases. -- Offscreen Vulkan `[portal-shadow-transport]` passed 2,440 assertions in 4 cases. - -Product host scheduling, trusted grant propagation and scoped copied-row ownership -are still required before changing the client path. Release full-tree pose timing, -sanitizers, Metal and an interactive Studio run remain outstanding. - -### Exact-domain source-prefit verification - -Host preparation now sends each renderer-validated node body bound through the -owned SHCT route. Producers deep-own the accepted source view, render an immutable -shadow prefit for the exact source-plus-body domain, and return retryable pressure -until its readback is ready. A resource-epoch change cancels the fit; stale depth is -never retagged under a new light matrix. Nested relays retain their authenticated -parent/target identities while their per-node bounds remain exact. Host upload -readiness includes pending producer fits, so callers submit the readback render. - -The bounded lease fixture holds two preview leases and two real preparation leases, -then rejects a fifth owner. It also checks hard retirement. The transport fixture -covers nested transfer, malformed and changed bounds rejection, fixed expiry, -endpoint withdrawal, delayed fit transfer, latest-pose composition, repeated-pose -zero network and shadow upload, and no mixed generations. - -Final dev verification used the final source snapshot: - -- `ninja -C .cache/build/dev test_render -j2` linked successfully. -- Offscreen Vulkan `[portal-tree-lighting],[portal-tree-import],[shadow-import],[portal-shadow-transport]` - passed 113,263 assertions in 10 cases. -- Headless `~[gpu]` passed 138,031 assertions in 516 cases. - -Logs are appended to `.cache/build/dev/tests/portal-prepared-build.log`. Trusted -grant propagation, scoped copied-row ownership, client product scheduling and -fairness remain open. Release pose timing, sanitizers, Metal and an interactive -Studio run remain unmeasured. - -### Caller-driven preparation fairness - -Preparation tickets retain only an accepted portal identity, tree and eye key. The -caller supplies its reference body only when the FIFO head is ready. A stale ticket -refuses rather than substituting a newer capture; callers cancel it and enqueue a -new tail ticket. Cancellation is the explicit invisible-demand withdrawal. - -Prepared source maps can be released independently after composition, retaining an -already displayed body image while freeing one of the two preparation slots. The -transport fixture checks FIFO head selection, non-head waiting, explicit ticket -cancellation, exact queued-start identity, three-ticket progress after release, -and repeated latest-pose zero transfer reuse. - -Final dev checks: offscreen Vulkan `[portal-shadow-transport]` passed 3,499 -assertions in 4 cases; headless `~[gpu]` passed 138,030 assertions in 516 cases. -The build log is `.cache/build/dev/tests/portal-prepared-build.log`. Product grant -propagation, client scheduling and release performance validation remain open. diff --git a/docs/future-work/RENDER-POST-HOOK-REFACTOR.md b/docs/future-work/RENDER-POST-HOOK-REFACTOR.md index 77135aa80..eb42d96ae 100644 --- a/docs/future-work/RENDER-POST-HOOK-REFACTOR.md +++ b/docs/future-work/RENDER-POST-HOOK-REFACTOR.md @@ -1,734 +1,82 @@ -# Render refactor after hooks +# Render cleanup after hooks ## Status -This document plans an internal cleanup of `mono.engine/render` after the hook -system in [RENDER-HOOKS.md](RENDER-HOOKS.md) is implemented and accepted. It is -not a claim that either the hook system or this refactor ships today. +This is the remaining internal cleanup after the render-hook contract in +[`RENDER-HOOKS.md`](RENDER-HOOKS.md) is accepted. The active release sequence +and hook requirements live in [`ROADMAP.md`](../../ROADMAP.md). This plan does +not change hook behaviour, the compiled render graph, or the current portal and +mirror optics. -`RENDER-HOOKS.md` is authoritative for hook behavior. This document only -defines how the frame path should be split around that behavior. +## Boundaries to preserve -The refactor must proceed in small steps. Every phase leaves the renderer -building, testable, and usable. Replaced paths are deleted as soon as their -replacement passes its gate. There must not be two permanent frame runners, -surface planners, hook owners, or pass lists. +- `Renderer::Render` remains the only batch coordinator and the compiled graph + remains the only render scheduler. +- Hooks keep their owned values, bounded asynchronous readbacks, exact node and + view identities, and renderer-owner-thread polling contract. +- A submitted frame alone commits history, uploads, and hook copies. Failed + submission leaves retryable state pending and publishes no completed bundle. +- Public headers do not gain device types. New render records stay private to + the module. -## Why this follows the hook work +## View recording ownership split -The hook work establishes one stable observation seam before the frame path is -split. That order matters. Moving the render code first would move capture -ownership and graph seams at the same time, making image or lifecycle failures -hard to assign to either change. +Split `ViewRecording` by lifetime, then delete each old field when it moves: -Complete the hook acceptance tests first. Freeze the current node names, -resource identity, snapshot alignment, and readback lifecycle as fixtures. The -frame cleanup may then move those responsibilities without changing their -contract. - -## Current pressure - -The renderer has already completed the first useful split. `Renderer::Render` -builds named `ViewRequest` data, `ViewRecording` prepares a view, `GraphRunner` -executes the compiled graph, and `src/nodes/*.cpp` owns node families. This -plan continues that shape instead of creating a new one. - -The remaining large units mix several kinds of ownership: - -| File | Current size | Mixed responsibilities | -|---|---:|---| -| `src/Renderer.cpp` | about 2,747 lines | Public facade, device operations, batch control, and view entry | -| `src/RendererState.hpp` | about 2,746 lines | Device, pipelines, residency, targets, history, imports, readback, and submission | -| `src/ViewRecording.cpp` | about 3,078 lines | Preparation, allocation, graph execution, presentation, capture, and submit | -| `src/ViewRecording.hpp` | about 668 lines | Inputs, derived view state, command state, and broad device access | -| `src/ScenePasses.cpp` | about 1,291 lines | Scene drawing, image drawing, resources, uploads, history, and profiling helpers | -| `src/nodes/GeometryNodes.cpp` | about 1,324 lines | Several geometry and transparency node backends | -| `src/nodes/MirrorNodes.cpp` | about 1,043 lines | Mirror planning, recursive recording, composition, and history | -| `src/nodes/ShadingNodes.cpp` | about 1,030 lines | Lighting, environment, post, and related bindings | - -Line count is navigation evidence, not a completion target. A short file with -hidden ownership is worse than a long file with one clear job. - -Three surface capture paths remain: - -1. `SurfaceCapturePlan.cpp` recursively builds a mixed mirror and portal plan. -2. `SurfaceNodes.cpp` records that plan through its explicit postorder. -3. `MirrorNodes.cpp::fillMirror` and `PortalNodes.cpp::fillLevel` still recurse - while recording GPU work. - -The mixed plan is the path to keep. The other two paths should converge on it -after behavior parity is proven. - -## Goals - -- Keep the compiled render graph as the only frame scheduler. -- Give every mutable field one owner. -- Make dependencies visible through one borrowed context. -- Separate input, prepared view data, and command recording state. -- Make preparation, graph execution, presentation, and submission distinct calls. -- Replace recursive surface traversal with a bounded explicit frontier. -- Keep node backends in focused files with no parallel pass list. -- Preserve hook names, timing, caching, resource lifetime, and failure behavior. -- Keep device recording on the renderer owner thread. -- Reduce rebuild pressure by narrowing private headers where measurement supports it. - -## Non-goals - -- No new `mono.engine/renderer` module. -- No second graph runtime, pass enum, pass-order table, or callback graph. -- No generic backend hierarchy added only to appear portable. -- No SDL GPU type in `Renderer.hpp` or new SDL include in a public header. -- No new ECS mirror or private copy of authored world state. -- No parallel GPU command recording under the current single-device contract. -- No change to surface optics, portal transforms, clipping, or shader contracts. -- No texture allocation per recursive capture entry. -- No blanket removal of `std::function` where recursion is not involved. -- No file writing, script callback, or MCP call from an observation hook. - -## Ownership model - -### Persistent dependencies - -Introduce one private borrowed dependency aggregate. It is wiring, not storage: - -```cpp -struct RenderContext { - DeviceState &Device; - PipelineState &Pipelines; - ResidencyState &Residency; - ViewTargetState &Targets; - ReadbackState &Readbacks; - SubmissionState &Submission; - DataFactoryHookBind &Hooks; - RenderTelemetry &Telemetry; -}; -``` - -The exact owner names may follow types already present when extraction begins. -The important rule is that every member names a coherent existing owner. -`RenderContext` must not become another spelling of `Renderer::Impl` with every -field copied into it. - -All references are required after successful renderer initialization. Optional -features remain optional data inside their owning service. Nodes must not look -up dependencies through a global locator. - -### Per-view records - -Split the current `ViewRecording` fields into three records: - -```cpp -struct ViewInput { - // Borrowed caller data. Valid only during synchronous recording. -}; - -struct PreparedView { - // Resolved camera, ranges, lighting, targets, and capture decisions. -}; - -struct RecordingState { - // Command identity, attachment state, profiling marks, and failure state. -}; -``` - -`ViewInput` begins as the current `ViewRequest`. It carries spans and host hook -pointers whose lifetime ends with the synchronous call. It must never cross a -thread or survive the frame. - -`PreparedView` owns or borrows the values derived before node recording. This -includes the resolved camera, scene plan, accepted surfaces, lighting blocks, -draw ranges, graph selection, presentation choices, and immutable capture plan. -It must not own a command buffer. - -`RecordingState` contains data that changes as nodes record. This includes the -active command, load and store state, timestamp slot, open pass, actual work -flags, pending history writes, and submission outcome. - -`ViewRecording` becomes a small composed facade over these records and -`RenderContext`. A field lives in exactly one record. Transitional aliases are -allowed only inside one migration phase and are deleted at that phase's gate. - -### Persistent state split - -Shrink `RendererState.hpp` by moving coherent state, not by creating empty -wrapper types. The intended dependency direction is: - -```text -Renderer facade - -> render context - -> persistent state owners - -> per-view records - -> pass recording helpers - -> node adapters -``` - -Persistent state must never depend on a node adapter. Hook value records must -never depend on a private device record. - -## Proposed private layout - -All files remain inside the existing `mono.engine/render` module: - -| File | Responsibility | +| Record | Owns | |---|---| -| `src/Renderer.cpp` | Public facade, owner-thread checks, and named batch entry | -| `src/RendererState.hpp` | Thin composition of persistent state owners | -| `src/state/DeviceState.hpp` | Device, formats, fallback resources, and common samplers | -| `src/state/PipelineState.hpp` | Installed graphs, schedules, shaders, and pipeline variants | -| `src/state/ResidencyState.hpp` | Mesh, texture, instance, index, skin, and particle residency | -| `src/state/ViewTargetState.hpp` | Scene slots, PBR targets, surface banks, and capture pools | -| `src/state/ReadbackState.hpp` | GPU copies, fence polling, resource tokens, and completed images | -| `src/state/SubmissionState.hpp` | Batch command ownership and pending commit state | -| `src/recording/RenderContext.hpp` | Borrowed persistent dependencies | -| `src/recording/ViewInput.hpp` | Synchronous caller input | -| `src/recording/PreparedView.hpp` | Immutable derived view data | -| `src/recording/RecordingState.hpp` | Mutable command recording data | -| `src/recording/ViewRecording.hpp` | Small composed recording facade | -| `src/recording/ViewPreparation.cpp` | Validate and prepare one view | -| `src/recording/ViewExecution.cpp` | Build handlers and execute the compiled graph | -| `src/recording/ViewPresentation.cpp` | Game output, host chrome, clear, and explicit screenshot adapter | -| `src/recording/ViewSubmission.cpp` | Submit, commit, discard, and retire | -| `src/recording/GraphResources.cpp` | Resolve graph resources and stage history writes | -| `src/recording/RecordingProfile.cpp` | Node timings, timestamp marks, and stage probes | -| `src/passes/SceneDraw.cpp` | Open scene passes and record world, blended, and effect draws | -| `src/passes/ImageDraw.cpp` | Fullscreen, image, overlay, and composition draws | -| `src/passes/ResidencyUpload.cpp` | Existing upload recording helpers | -| `src/capture/SurfaceCapturePlan.hpp` | Capture request, entry, frontier, and result records | -| `src/capture/SurfaceCapturePlan.cpp` | Pure bounded frontier planning | -| `src/capture/SurfaceCaptureRecording.hpp` | Narrow capture recording API | -| `src/capture/SurfaceCaptureRecording.cpp` | Target resolution and capture draw recording | -| `src/nodes/*.cpp` | Thin authored-node adapters grouped by family | - -This layout is a destination, not a command to create every file at once. -Create a file only when a coherent responsibility moves into it. - -The current render module policy names `ViewRecording.cpp`, `ScenePasses.cpp`, -and `src/nodes/*.cpp` as the pass layout. This plan keeps node adapters in -`src/nodes`. Any change to the documented shared-helper layout needs explicit -policy review during implementation. This planning file does not edit policy. +| `ViewInput` | Synchronous caller data that may not survive recording | +| `PreparedView` | Resolved camera, scene plan, targets, graph selection, and immutable capture decisions | +| `RecordingState` | Command identity, pass state, timestamps, pending history, and recording outcome | -## Main frame flow - -`Renderer::Render` remains the public entry and the only batch coordinator: - -```text -require renderer owner thread -pump completed renderer and hook work -validate all views and resolve graph groups -acquire the batch command and optional swapchain image -begin batch state - -for each graph group in stable order - for each view in stable order - build ViewInput - PrepareView - BuildNodeTable - ExecuteViewGraph - FinishViewPresentation - -submit the final batch command -commit or discard submission-backed state -submit ordered download work -pump only completed readbacks -clear batch state -return FrameResult -``` - -The functions should have narrow results: - -```cpp -ViewStart PrepareView(RenderContext &, const ViewInput &, PreparedView &); - -bool ExecuteViewGraph( - RenderContext &, - const ViewInput &, - PreparedView &, - RecordingState &, - FrameResult & -); - -void FinishViewPresentation( - RenderContext &, - const ViewInput &, - const PreparedView &, - RecordingState &, - FrameResult & -); - -SubmissionResult FinishBatch( - RenderContext &, - RecordingState &, - FrameResult & -); -``` - -Names may change to match local style. The ownership cuts may not. - -Preserve these current rules: - -- Frame and world scopes are reused through `PreparedScopes`. -- Isolated shadows remain isolated per required view. -- Intermediate batch views never submit the shared command buffer. -- Only the final batch view records final host presentation and submits. -- A graph node owns every ordinary game render pass. -- Host chrome remains after graph output and outside the authored graph. -- An untouched swapchain image is cleared before presentation. -- Graph history advances only for work backed by a successful submit. -- Failed acquire or submit keeps retryable damage and history pending. - -## Graph and pass split - -The graph remains the only description of order, resources, and demand. -`GraphRunner` remains the SDL-backed `graph::NodeRunner`. Keep its missing-node, -rejected-node, submitted-count, timing, and dropped-mark diagnostics. - -Keep the current retained-node filter. Keep stage probes wrapping actual graph -execution. A stage probe may observe before and after a skipped handler, so it -must not become the hook scheduling path. - -Node adapters should become small. An adapter validates the authored node and -resource contract, resolves its narrow recorder, and records the node. It does -not contain a private recursive scheduler. - -Split large families by work that can be understood and tested alone: - -- geometry preparation and opaque drawing -- transparent ordering and drawing -- shadow recording -- mirror and portal capture recording -- surface composition -- lighting and environment -- post processing and tonemap -- game output and capture output - -Do not create a `Pass` enum, `PassOrder`, or a second table that duplicates the -graph. A new way of drawing remains a graph node with one registered backend. +Use a private borrowed render context for the existing persistent owners. It is +wiring, never a second `Renderer::Impl`: device, pipelines, residency, targets, +readback, submission, hook binder, and telemetry keep one authoritative owner +each. Extract preparation, graph execution, presentation, and submission as +separate calls only after their current failure behaviour is characterized. ## One explicit surface frontier -### Path to keep - -`SurfaceCapturePlan` becomes the only camera expansion plan for mirrors and -portals. Its output remains plain CPU data. `SurfaceCaptureRecording` walks the -plan and records GPU work in the plan's proven order. - -The first change replaces only the recursive `visit` in -`PlanSurfaceCaptures`. It must produce byte-equivalent entry fields, root -indices, child links, pixel counts, failure status, and postorder for existing -fixtures. - -Only after planner parity should `MirrorNodes::fillMirror` and -`PortalNodes::fillLevel` be migrated to the shared plan. - -### Frontier record - -Use a bounded vector as a stack. Do not use a priority queue or breadth-first -queue. The comparison with A* is only that pending work is explicit data. - -```cpp -enum class CaptureFrontierPhase : uint8_t { - Enter, - NextChild, - Record, - Leave, -}; - -struct CaptureFrontierEntry { - CaptureFrontierPhase Phase = CaptureFrontierPhase::Enter; - uint16_t Parent = NO_SURFACE_CAPTURE; - uint16_t PlanEntry = NO_SURFACE_CAPTURE; - uint16_t NextSlot = 0; - core::CFrame Frame; - glm::mat4 Projection{1.0f}; - uint32_t Width = 0; - uint32_t Height = 0; - uint32_t RemainingDepth = 0; - int16_t Arrival = -1; -}; -``` - -The exact fields may be reduced after the parity test exposes what each phase -needs. The stack and expanded entry count are both bounded. Depth alone does -not bound branching. - -### Required traversal order - -Preserve depth-first traversal and source-slot order exactly: +`SurfaceCapturePlan` is the sole expansion plan for mirrors and portals. +Replace recursive planning and recording only after plan parity is proven. The +frontier is a bounded depth-first stack with explicit enter, child, record, and +leave phases. It must retain source-slot order and child-before-parent +recording: ```text enter parent - descend child A - finish descendants of A - record A - descend child B - finish descendants of B - record B -record parent while sampling completed A and B + complete child A and record it + complete child B and record it +record parent from completed children leave parent ``` -A breadth-first walk followed by reverse depth is not equivalent. - -Targets are pooled by viewport, kind, recursion level, and surface slot. Two -sibling branches can reuse the same lower-level target because the first -sibling records all commands that consume its descendant before the next -sibling overwrites that target. Reordering by depth, kind, material, or target -key breaks this lifetime. - -### Target rules - -- Never sample the texture currently used as a render target. -- Reacquire a pooled target by stable key after descending. -- Do not retain pointers across vector growth or target allocation. -- Keep root mirror ping-pong and history behavior. -- Keep inner mirror and portal targets non-cycled unless measurement changes it. -- Keep matrices describing the image that was actually written. -- Preserve readiness and successful-write rules. -- Do not allocate one texture per capture entry. -- Add a debug generation to target keys if needed to assert legal reuse. - -### Camera and visibility rules - -- Derive every child camera from its parent camera. -- Mirrors keep fitted reflected lenses. -- Portals keep warped cameras and the existing oblique clip contract. -- Mirrors skip their own pane. -- Portals skip the arrival partner and external images. -- Visibility is tested from the current derived view. -- Transparent geometry is ordered from each capture camera. -- Full-scene caster inputs remain distinct from camera-culled screen inputs. -- Filters, ribbon facing, particle facing, and seam light behavior stay intact. -- Pane-less surface cameras retain their existing iterating fallback. -- Terminal depth retains the existing flat or history fallback and bounce probe. - -### Budget parity - -The existing mixed plan validates slots, finite matrices, dimensions, depth, -entry count, and total pixels. It fails atomically and clears partial output. -Keep those semantics during the recursion replacement. - -Legacy mirror and portal recorders do not admit work at the same point. Mirror -admission occurs before descent. Portal admission occurs after descent. Do not -silently normalize these behaviors during extraction. Any unified admission -rule is a later behavior change with its own image, budget, and profile proof. - -## Hook integration - -`DataFactoryHookBind` is injected through `RenderContext`. Its ownership and -API remain exactly as defined by `RENDER-HOOKS.md`. - -The binder owns: - -- immutable hook registration -- session connections -- armed, queued, submitted, ready, and terminal batch state -- generation-checked hook, connection, and batch handles -- fixed capacity and retained-byte budgets -- cancellation, expiry, teardown, and complete bundle publication -- capability descriptions and stable hook names - -The renderer keeps GPU copies, device resources, fences, submission, and image -conversion. The external data factory keeps file writing, checksums, and -manifest commit. - -The first limits remain: - -- 12 renderer resource image slots -- 6 live capture jobs -- 64 MiB retained-byte ceiling -- admission counted by unique capture node - -Different hooks may observe different authored nodes. Each result must match -the node in its own hook spec. Node names are not required to match across a -bundle. - -### Scheduling seam - -Preparation arms a connection for the matching prepared view. It does not -invoke the hook. - -The matching output node schedules the hook after its declared outputs exist -and before those resources can be recycled. It passes an immutable owned -`RenderObservationContext` to `DataFactoryHookBind::CallHooks`, or to the final -`ScheduleHooks` spelling if that rename is chosen. - -If the node is skipped, no observation is fabricated. If admission returns -`Backpressured`, ownership does not change and the caller may retry at the next -eligible view. A required capture becomes terminal only under the expiry rules -defined by `RENDER-HOOKS.md`. - -Submission changes queued hook work to submitted. Failed submission, world -destruction, pipeline replacement, disconnect, expiry, and shutdown cancel -every owned resource token. `Pump` runs on the renderer owner thread and checks -only completed work. It never waits. - -`CaptureRecordValidation` remains the final bundle alignment check. Optional -unavailable channels stay explicit. A required failure rejects the bundle. - -### Capture paths that remain separate - -The current explicit screenshot path waits for a fence and writes a file from -`ViewRecording::Finish`. Those actions are not allowed for binder observations. - -Move the explicit screenshot path into `ViewPresentation.cpp` as a named legacy -adapter. Do not route binder work through it. Whether explicit screenshots -later become asynchronous is a separate change with separate product behavior -and tests. - -## Failure and cleanup - -Every extracted function begins with shallow guards, but cleanup cannot depend -on reaching the end of a long function. Use one scoped batch owner or the -project's existing cleanup pattern to leave command, timing, upload, history, -download, and hook state valid on every return. - -Do not invent universal abort semantics during the split. The current -non-batch incomplete-view path can submit its partial command and commit -resident or history work when that submit succeeds. Preserve and characterize -that behavior before deciding whether it should change. - -Classify outcomes explicitly: - -| Outcome | Required action | -|---|---| -| View abandoned before recording | Release or retain acquisition exactly as today; schedule no hook | -| Node rejected | Close active pass, name the node, and follow current incomplete-view behavior | -| Scene submit failed | Discard pending history, fail resident uploads, abandon timings, and fail queued hooks | -| Scene submit succeeded | Commit submission-backed uploads and history; mark hook copies submitted | -| Download submit failed | Keep rendered frame result, fail affected readbacks, and release tokens | -| Batch intermediate view | Keep shared command ownership; do not submit | -| Shutdown or replacement | Stop new scheduling, cancel tokens, release completed ownership, then invalidate generations | - -Tests must pin each row before cleanup code moves. - -## Migration phases - -### P0: freeze contracts - -Record current behavior for view ordering, graph scopes, retained nodes, node -errors, surface plans, hook scheduling, history commits, incomplete views, -explicit screenshots, and failed submissions. - -Gate: existing tests pass, new characterization tests pass, and the hook system -meets every acceptance test in `RENDER-HOOKS.md`. - -### P1: extract persistent owners - -Move one coherent group at a time out of `RendererState.hpp`. Begin with -readback or pipeline state because each already has clear operations. Keep -`Renderer::Impl` as a composition root while callers migrate. - -Gate: each field has one home, no copied state exists, public headers are -unchanged, and the render suite passes after every move. - -### P2: separate view records - -Turn `ViewRequest` into `ViewInput`. Move derived values into `PreparedView` and -command mutation into `RecordingState`. Keep `ViewRecording` as a thin facade -so node families can migrate independently. - -Gate: every moved field is deleted from its old home, lifetimes are documented, -and no borrowed input survives synchronous recording. - -### P3: split preparation and execution - -Extract `PrepareView`, `BuildNodeTable`, `ExecuteViewGraph`, presentation, and -submission from `ViewRecording.cpp`. Preserve handler precedence, retained -filtering, profiling, stage probes, batch grouping, and scope reuse. - -Gate: `ViewRecording.cpp` no longer owns unrelated phases, and failure tests -match the baseline. - -### P4: split shared recording helpers - -Move scene drawing, image drawing, upload recording, graph resources, and -profiling into focused files. Keep node adapters as their only graph entry. - -Gate: every old `ScenePasses.cpp` caller has moved and `ScenePasses.cpp` is -deleted. There is still one graph runner and one pass order. - -### P5: replace planner recursion - -Replace `PlanSurfaceCaptures::visit` with the explicit bounded DFS stack. Keep -the plan type and all current ordering and budget semantics. - -Gate: exact CPU plan fixtures pass, the recursive planner is deleted, and -frontier high-water metrics remain bounded. - -### P6: converge mirror and portal recording - -Move `fillMirror` and `fillLevel` to the shared plan and recording path. Retain -kind-specific camera, clipping, filtering, target, history, and fallback rules. - -Gate: recursive GPU recorders are deleted. CPU trace tests prove target reuse, -and GPU fixtures match the accepted baseline. - -### P7: narrow node families - -Split only node files that still combine independently testable jobs. Preserve -authored kind names and backend registration. Delete each old handler when its -replacement becomes the sole registered backend. - -Gate: every supported graph kind has exactly one backend. Unknown and rejected -kinds retain current diagnostics. - -### P8: shrink the facade - -Remove transitional aliases, broad includes, and unused friend access. Keep -`Renderer.cpp` focused on public calls, thread ownership, and batch flow. - -Gate: public ABI and include boundaries remain valid, server and CDN presets -remain free of the graphics stack, and architecture checks pass. - -### P9: final proof - -Run the complete render and graph suites, approved GPU checks, release profiles, -format checks, architecture checks, and a clean-build comparison. - -Gate: every acceptance item below has evidence and no replaced path remains. - -## Test plan - -### CPU and device-free tests - -Extend the existing focused suites rather than creating endless smoke tests: - -- `SurfaceCapturePlan.cpp`: exact entry, child, root, and postorder parity -- frontier trace: enter, descend, record, and leave sequence -- sibling target reuse with generation checks -- stable input-slot tie ordering -- derived parent camera and projection -- mirror self-skip and portal arrival-skip -- external portal exclusion -- depth, entry, and pixel exhaustion -- invalid slots, dimensions, matrices, and duplicate sources -- atomic plan failure with no partial output -- fallback behavior at terminal depth -- retained and skipped node hook behavior -- incomplete-view and partial-submit cleanup -- graph history commit and retry rules -- stale handle and cancellation behavior from `RENDER-HOOKS.md` - -Reuse `GraphRunner`, `Passes`, `FramePreparation`, `GraphHistory`, -`PresentationDamage`, `ResourceImage`, `DataCapture`, and `Readback` suites. - -### GPU tests - -Use existing render fixtures for focused image and lifetime checks: - -- mirror inside mirror -- portal in both directions -- mixed mirror and portal chains -- sibling branches reusing deeper targets -- external portal images -- pane-less surface cameras -- transparent geometry and ribbons from capture eyes -- resize and viewport slot reuse -- retained mirror history and failed-submit retry -- hooks observing named outputs before resource reuse -- optional unavailable and required failed bundle behavior - -GPU work is final verification under repository policy. Ask before running live -or real-device checks. If approval is declined, record the exact skipped gate. - -### Failure injection - -Add narrow seams only where needed to force: - -- target allocation refusal -- command acquisition failure -- graph node rejection -- scene submit failure -- download submit failure -- readback expiry -- hook backpressure -- pipeline replacement during pending capture -- world and renderer teardown during pending capture - -Prefer existing device-free planners and real integration fixtures over a mock -renderer. - -## Profiling gates - -Profile the release preset. Name the backend, scene, view count, surface depth, -resolution, pipeline, and hook channels beside every result. - -Measure: - -- CPU preparation, graph execution, recording, and submit time -- capture frontier entries and stack high-water mark -- surface pixels admitted and refused -- node and draw counts -- transfer and command-buffer bytes -- GPU resource creations, live bytes, and peak bytes -- retained target reuse and history writes -- hook context bytes and allocations -- readback bytes, latency, queue depth, expiry, and backpressure -- cache hit behavior with upload and allocation counters -- clean build wall time and total CPU seconds - -Splitting headers can improve parallel wall time while increasing total frontend -CPU work. Report both. Do not call the split faster unless the measured build or -frame path is faster. - -The frontier conversion is accepted for safety and visible control flow first. -Do not claim a frame-time win unless the release profile shows one. - -## Risks and controls - -| Risk | Control | -|---|---| -| A second scheduler appears in pass files | Graph remains sole order source; adapters register one backend each | -| Context becomes a service locator | Required concrete references only; no global lookup or generic registry | -| State is copied during extraction | Delete old field in the same phase; assert one owner | -| DFS becomes breadth-first by accident | Exact frontier trace and pooled-target generation tests | -| Target overwritten before parent samples it | Preserve sibling subtree completion and command order | -| Camera derives from the root instead of parent | Per-entry camera fixtures for mirror and portal chains | -| Budget behavior changes during cleanup | Exact status, count, pixel, and partial-output tests | -| Hook schedules for a skipped node | Schedule only in the executed output adapter | -| Hook inherits screenshot waits | Separate binder readback from legacy screenshot adapter | -| Failed submission publishes a bundle | Move queued work to submitted only with successful device submit | -| Split changes partial-submit behavior | Characterize and preserve before any policy change | -| Too many tiny files hurt locality | Split by coherent job, not by function count | -| Private SDL types leak outward | Keep all new records under `src/` | -| Build gets slower overall | Measure wall time and total CPU seconds | - -## Policy dependencies - -`mono.engine/render/AGENTS.md` still names `RENDER_PIPELINE.md` as authority, -prescribes the current `ViewRecording` and `ScenePasses` layout, and describes -`fillMirror` recursion. It also contains an older stage statement that conflicts -with its later graph sections. - -These are policy dependencies to resolve with the required human review during -implementation. Do not silently edit protected policy files as part of this -plan. - -Keep `graph` shared at L9 and `render` client-only at L12. No new module or tier -escape is needed. If a proposed extraction creates a new dependency edge, stop -and resolve the design instead of widening the layer rule. - -## Completion checklist - -- `Renderer::Render` is the only batch coordinator. -- The compiled graph is the only render scheduler. -- `GraphRunner` remains the only graph-to-device adapter. -- Every mutable field has one owner. -- View input, prepared data, and command state have explicit lifetimes. -- Node adapters depend on narrow recording helpers. -- No recursive surface planner or recorder remains. -- One bounded DFS frontier preserves exact child-before-parent order. -- Pooled targets are not overwritten before their consumers record. -- Mirror, portal, and mixed capture behavior passes focused GPU fixtures. -- `DataFactoryHookBind` remains the only hook owner. -- Hook scheduling occurs only at declared executed node seams. -- Hook polling never waits and never writes files. -- Legacy screenshots remain separate and honestly documented. -- Submission, history, residency, download, and hook failures are covered. -- Replaced files, aliases, handlers, and state homes are deleted. -- Public headers gain no SDL dependency. -- Architecture, format, render, graph, and approved GPU checks pass. -- Release profiling records frame cost, memory, traffic, and hook backpressure. - -The desired end state is boring: one graph, one batch runner, one explicit -surface frontier, one hook binder, and one owner for every piece of state. +This order is a target-lifetime rule. Siblings may reuse a lower-level pooled +target only after the preceding subtree has recorded every consumer. Preserve +stable target keys, successful-write readiness, root mirror history, mirror +self-skip, portal-arrival skip, external-image exclusion, derived child +cameras, clipping, visibility, and terminal fallbacks. The frontier validates +depth, entry count, dimensions, finite matrices, and total pixels before +publishing any plan. + +After CPU planner parity, route `MirrorNodes` and `PortalNodes` through the +shared plan and narrow recording adapter. Delete their recursive GPU recorders +only when image fixtures and target-reuse traces pass. + +## Delivery gates + +1. Freeze current graph, hook, surface-plan, history, and failure fixtures. +2. Extract one persistent owner at a time with no copied mutable state. +3. Separate the three view records and then the preparation, execution, + presentation, and submission calls. +4. Replace planner recursion with the bounded frontier, retaining exact CPU + plan fixtures and reporting frontier high-water mark. +5. Converge mirror and portal recording on the shared plan, then delete legacy + recursive paths. +6. Run focused CPU traces for ordering, budgets, failure atomicity, target + reuse, and hook lifecycle. Finish with approved GPU fixtures and a release + profile reporting capture entries, pixels, resource bytes, and readback + latency. + +No phase adds a second pass list, graph runtime, callback graph, or permanent +frame runner. diff --git a/docs/future-work/RENDER-REFACTOR-TASKS.md b/docs/future-work/RENDER-REFACTOR-TASKS.md deleted file mode 100644 index b350fcf52..000000000 --- a/docs/future-work/RENDER-REFACTOR-TASKS.md +++ /dev/null @@ -1,555 +0,0 @@ -# render refactor execution - -Implementation of [RENDER-REFACTOR.md](RENDER-REFACTOR.md), all R01-R17 and P0-P12. -The implementation request authorizes the planned destination. A checked phase -requires its functional and optimization evidence, not merely code or a build. - -Current continuation order is at the top of -[RENDER-REFACTOR.md](RENDER-REFACTOR.md#continue-here-portal-crossing-2026-09-07). -The [handoff](PORTAL-HANDOFF.md) records known failures, test evidence and retained -diagnostic paths. The full working-tree checkpoint is not a completed phase. - -## continuation 2026-09-08 - -- [x] P8 gameplay departure retirement: repeated lease requests receive an - authenticated `LeaseAdopted` reply after destination adoption. Source checks - the accepted claim, attempt and endpoint before removing its departure while - leaving its connection available for presentation. Destination retry state - remains bounded by the existing lease timeout. Both missing behaviors were - reproduced before the fix. Codec/lease tests pass 2,660 assertions / 7 cases; - server lease and process crossing tests pass 748 / 6. Full game passes - 4,124 / 93 and full server passes 1,543 / 76. Detailed evidence is in [PORTAL-HANDOFF.md](PORTAL-HANDOFF.md). -- [x] Retain one admitted source observer and its content session after product - adoption. Stop its gameplay input/scripts while polling snapshots and serving - content through its own connector. Share the intake budget across explicit - world/session pumps. Delayed source content plus newly authored source and - destination references pass 95 assertions with local fallback/cache disabled. - Full headless Client passes 10,215 / 172; successor/observation checks pass - 3,866 / 5; 30/60 Hz product image handoff passes 17,098 / 1. Builds and format - checks pass. Evidence and limitations are in [PORTAL-HANDOFF.md](PORTAL-HANDOFF.md). -- [x] Share the producer's world and camera collection through engine-owned - `WorldViewFrame` and `WorldCameraFrame` packets. Preserve published replica - interpolation, detach particle inputs, and copy per-camera spatial placements - before leaving the store. Interface submission now accepts the owned packet. - Waiting nested captures retain their preparation gate. Full render passes - 46,592 / 465; full Client passes 10,215 / 172; device `[portal-runtime]` passes - 24,161 / 18. Build, formatting and whitespace checks pass. This is the shared - collection boundary; complete resource-aware foreign-eye binding remains open. -- [x] Bind retained source-world packets to the Client eye after adoption, - including lighting, particles, ribbons, spatial UI and foreign straddlers. - Keep screen UI with the active player through `WorldViewInterface`. Refuse - failed presentation and hold the admitted eye while nested captures change - from body layers to complete-room demand. The initial run failed three - landmark assertions; after the gate, cold/warm 30/60 Hz handoff passes - 16,244 / 16,323 assertions and the 16-variant camera matrix passes 131,965. - Full headless Client passes 10,215 / 172; world-view/interface checks pass - 90 / 3. Inspected evidence and the then-unresolved gray portal-border case are in - [PORTAL-HANDOFF.md](PORTAL-HANDOFF.md). Resource namespace, shader/editable - preparation and complete current-camera foreign rendering remain open. -- [x] Select explicitly admitted, ready local replicas for nested portal - captures. Retain the previous observer while a visible portal needs it and - present it before native portal demand. Host routing passes 33 assertions; - full headless Client passes 10,232 / 172. Product checks now enforce producer - ownership and matching position/rotation for the identity-seam fixture. -- [x] Close the reproduced return-adoption camera/body transition. Admitted - local captures use complete world/body rendering instead of delayed body - layers. Authenticated successors with ready rigs share the direct packet - path and receive the existing prediction continuation before presentation. - The initial local-capture and successor-only attempts still failed landmarks; - copying the continued body pose closes the reproduced size jump. The 24-run - product matrix passes 202,963 assertions / 4 cases with unchanged landmark - thresholds and explicit current-camera/producer checks. -- [x] Resolve first-person body identity in directly viewed destination stores - and retain account selection after source-player retirement. Final demand, - rendering and lifetime checks pass: full render 46,636 / 466, full Client - 10,232 / 172, focused device-enabled body/shadow checks 967 / 9. The final - account-selection adjustment follows the product matrix and is covered by - those host/device checks. Fix the reproduced empty-world test registration - order so the full render gate is independent of that test order. Builds and - formatting pass. Artifacts and limitations are in [PORTAL-HANDOFF.md](PORTAL-HANDOFF.md). -- [ ] Complete observer endpoint/lifetime failure coverage and same-name content - isolation, prepare complete foreign-world layers and close the moving-camera - image gate. The prior image staging prototype remains rolled back; this - packet path now draws retained sources and authenticated ready successors. - Unadmitted eyes and remote nested views still use retained images. Staged - content, per-world shaders, editable resources and viewport widgets remain - part of the required preparation work. - -## phase tasks - -- [ ] P0: audit current contracts, policies, hidden work and shader consumers; - record baseline tests and release costs. In progress. -- [ ] P1: per-step image/projection harness, independent oracles, bounded - captures, failure artifacts and `just render-check`. -- [ ] P2: graph-owned preparation, residency, uploads, simulation, capture and - composition; shared worlds and parallel active-view collection. -- [ ] P3: shader runtime schema, cook/compiler split, reflection, variants, - published bundles, backend payloads and complete cache keys. -- [ ] P4: material definitions/instances, capability flags, effect attachments, - resident records, VM bindings, save and replication. -- [ ] P5: compositor/material authoring, incremental canvas, cook previews, - groups, undo/redo and hidden-work gates. -- [ ] P6: lighting, PBR, colour, AO/GI, shadows, post, velocity/history and all - requested AA choices with numeric and image proof. -- [ ] P7: editable packing/quantization, mip/atlas streaming, four authored LODs, - decimation, meshlets, tessellation and visual displacement. -- [ ] P8: portal projection, clipping, light transport, physical overlap, - cross-world ownership and inspected moving demo. -- [ ] P9: real hybrid/progressive tracing, acceleration, transport, accumulation, - reset, denoise, portal rays and bounded GPU queues. -- [ ] P10: particle/environment nodes, TornadoSim and retained scene-producer - requirements with deterministic authoritative simulation. -- [ ] P11: all requested examples, backend/tier verification, full-frame - benchmarks, pressure tests and latency/quality comparisons. -- [ ] P12: delete replaced paths, enforce cooked packaging, finish build/test/ - fuzz/soak gates, reconcile documentation and audit R01-R17. - -## workflow for the current phase - -- [x] classify: engine-wide implementation, preserving the full plan. -- [ ] discover-core: inspect graph execution, device capture and shader loading. -- [ ] specify: map baseline and image contracts to concrete tests. -- [ ] localize: name production seams and test commands before editing. -- [ ] prototype: only unresolved device/format behavior needs a probe. -- [ ] stubs: review data shapes and function logic before filling bodies. -- [ ] implement: build in dependency order without placeholder success. -- [ ] validate: headless first, then device evidence at final verification. -- [ ] optimize: release measurements with quality and memory held explicit. -- [ ] review: reconcile code, tests, policies and residual gates. - -## evidence and current boundaries - -- Starting revision: `4daba0b6`; clean worktree before implementation. -- The source plan contains 23 sections, 17 requirements and 13 phases. -- `render/AGENTS.md` still requires live client shader compilation and exempts - host chrome/window clear from graph ownership. P0 must reconcile these with - the explicitly requested implementation and verified current code. -- Four offscreen Vulkan image fixtures now pass. The user explicitly requested - portal visual checks, which are being added to that harness. Interactive Studio - inspection remains a separate final verification step. -- No phase is complete yet. No renderer speedup is claimed. - -## current implementation slices - -- [x] P0: locate hidden frame work. `Renderer::Render` flushes meshes before - graph execution; `ViewRecording::Begin` executes entity selection and packing; - upload handlers report that completed work. Particle preparation, interface - preparation, thumbnail capture and final capture/chrome remain migration work. -- [x] P0: add bounded signature benchmarks for 1,024/16,384 rows, 1/2/8/32 - cameras and unchanged/one-row edits. `bench_render` builds; all 16 cases run. - These diagnostic runs had background work, heap hooks and Tracy enabled. -- [x] P1: independent CPU comparison of byte colour, float and integer-ID images - with stride validation, per-pixel outliers, RMSE, non-finite rejection and - mismatch bounds. `[imagecomparison]` passes 112 assertions in 8 cases. -- [x] P1 slice: real-device plane fixtures and failure artifacts. Four Vulkan - cases pass, including lens/clipping, edited objects and multiple worlds/views. - A final graph observer retains captured intermediate resources; this preserves - ordinary aliasing elsewhere. Orthographic/oblique, skinning, PBR, temporal, - portal and broader lifetime families remain required in their feature phases. -- [x] P2 slice: conservative `View` damage includes object inputs, rather than - reusing stale resident rows after same-count edits. The GPU edit case reproduced - this defect and passes after the fix; hosts can still supply precise damage. -- [x] P2 slice: frame setup runs once per resolved pipeline, with shared resources - available to each world/view. Duplicate prefix reproduced in headless tests. - Planner, mixed-writer, fallback aliases and idle-view cases pass headlessly. - This closes scope bookkeeping only; actual hidden-work migration remains. -- [x] P3 slice: retain accepted shader words on failed edits, invalidate removed - consumers, and key attempted sources by storage incarnation/entity/revision. - Replacement, duplicate selection, cross-world contamination and snapshot tests - pass. Snapshot application conservatively invalidates source caches, so unchanged - shaders may recompile until the content-key cook cache exists. -- [x] P3 slice: bounded canonical cooked shader transport, reflected interface - identity, corruption tests and sanitizer-backed parser fuzzing. Cooking, - executable admission and delivery consumers remain required; this is a format - unit, not a published shader pipeline. -- [x] P1 slice: resolve named resource readbacks through graph alias storage and - report their actual dimensions. Portal captures reproduced missing textures; - all eight camera/ambient combinations now reach the pixel comparisons. -- [x] P8 slice: preserve dim-light portal radiance. The initial two-sided image - oracle matches aperture coverage but fails its colour bound at ambient 0.25. - The UNORM8 radiance intermediate produces a three-code error after display - conversion. HDR capture and matching attachment pipelines now pass 13 samples, - including custom materials, spatial UI and transparent geometry. The additional - logical target cost is four bytes per portal pixel; no speedup is claimed. -- [x] P8 slice: real Humanoid camera subjects, per-camera selection and one root - resolver across follow, obstruction and transit. Walking through turned portals - and back passes headlessly. Authored documents, clones and product follow paths - preserve automatic/explicit mode and remap Humanoid root references. -- [x] P1/P8 slice: explicit fitted view projection, consistent culling and general - depth reconstruction. Off-axis, orthographic and oblique fixtures pass after - translation/rotation too. A projection-only culling matrix reproduced missing - portal interiors; supplying full view-projection fixes the 13 portal samples. -- [x] P8 slice: bounded named presentation bus outside simulation mailboxes, - with authenticated endpoint incarnations, owned payloads, backpressure and - real process-channel transfer. Parser fuzzing passes. Actual portal image - producers/consumers still need to use this route. -- [x] P8 slice: bounded canonical image request/reply codec, including HDR hash, - pose/lens/clip checks, truncation and malformed-length tests. No image exchange - is claimed until the renderer adapters run through the bus. -- [x] P8 slice: graph-owned nonblocking HDR export, bounded source inbox and - renderer import. Export uses the existing capture node and scene fence, with - no extra submission. A failed graph cannot publish a successful image, and a - cancelled download remains owned until its fence completes. Import uses one - bounded staging buffer and reuses unchanged content without another upload. -- [ ] P8 slice: connect actual image producers and consumers through the - presentation bus. Two independent Vulkan renderers now exchange destination - images through the bus without changing the destination's active camera. - Complete-world fixtures include HDR transparency, effects, nested surfaces - and spatial interface. Shared-renderer requests can instead exchange an owned - resident-image receipt without CPU pixel transfers. Product host wiring and - full child lighting/environment parity remain required. -- [x] P8 host adapter slice: `PortalImageHost` owns bounded viewport sources, - shared destination producers and resident receipts. Caller-provided routes - resolve authored world names to the selected player replica. View removal - closes its endpoint and purges queued work; world removal retires dependent - images. Two viewport images have distinct ownership and retire independently. - Client/Studio call sites, complete straddler image sequences - and process-host adapter verification remain required before replacing - `AttachForeignSurfaces`. -- [x] P8 authored demand collection: gather linked cross-world seams from ECS - with the actual viewport lens and explicit surface slots. Full camera paths - identify requests; ambiguous duplicate paths are refused. Cross-world claims - exclude the legacy reflection even for unsupported filters. No active-camera - resource, camera pose or authored surface index is changed. Demand tests pass - 1,117 assertions / 6 cases. The old attachment also carries source straddlers - into destination images, so replacing product call sites still requires those - owned geometry inputs in the image producer; enabling only background images - would remove the far half of a crossing character. -- [x] P8 crossing-image wire data: `PortalGeometry` carries drawables, - nine asset bindings, mapped poses, material controls, clip/light vectors, - shadow/alpha/sampling policy and owned skin palettes. No source ECS identity - or interned-name number is serialized. The codec bounds 256 rows, 4,096 joints - and 1 MiB, and validates palette ranges before committing decoded output. - Diagnostic draw names may be empty or repeated: these rows are a complete - picture, not transferred ECS identities. Initial codec tests passed 774 - assertions / 3 cases; the integrated gate below supersedes that count. -- [x] P8 crossing-image runtime slice: source draw conversion copies referenced - skin ranges and material/clip fields without source entity IDs, tag bits or - surface slots. Version 3 image requests carry bounded geometry; body-only - changes supersede pending requests with a still camera. The producer appends - decoded rows/palettes to each requested destination view. Copied and resident - GPU fixtures hide the destination wall and reproduce its expected pixels only - from the transported body. Combined codec/conversion/runtime/host/table tests - pass 3,265 assertions / 24 cases. An unnamed-draw refusal and order-dependent - effects-registration abort were reproduced and corrected. Actual seam clone - collection is connected below; moving skinned crossing images, product call sites and process - image sequences remain open. -- [x] P8 authored crossing-image collection: `CollectPortalImageDemands` now - encodes actual far-half clones using the gathered seam and viewport slots. - The shared scene clone implementation retains body-fit and complementary - clipping rules without gathering again or changing the active camera. - Referenced skin palettes travel with the request. Invalid geometry refuses the - demand instead of silently omitting a body half. Demand/geometry tests pass - 1,932 assertions / 11 cases, including mapped placement, material preservation, - skin data, source-row preservation and malformed-palette refusal. Shared scene - surface tests pass 4,953 assertions / 76 cases. This is headless collection - evidence; the complete moving product image gate is open. -- [x] P8 authored crossing-image pixel slice: create an authored source portal - and a body spanning its plane, then feed the collected request and mapped - sampling into the real producer and compositor. The destination wall is hidden; - the transported far half supplies the expected red centre pixel under - destination lighting. Vulkan copied and resident delivery pass independently, - including zero resident upload checks. Combined runtime/demand tests pass - 2,500 assertions / 15 cases. This - centre-pixel gate does not prove moving Humanoid silhouettes, reciprocal - destination mouths or complete product wiring. -- [x] P8 reciprocal-mouth pixel slice: the authored destination now has a real - return portal aimed at the source world. Six centre/off-centre eyes on both - faces retain the transported body's expected centre pixel in copied and - resident delivery. These cases pass without changing the renderer: the tested - aligned pair is already excluded correctly by destination clipping. The full - runtime/demand subset passes 3,262 assertions / 15 cases. This does not close - moving endpoints, aperture-edge comparisons or nested cross-world recursion. -- [x] P8 Client call-site slice: Client owns and tears down `PortalImageHost`, - configures its local presentation bus, collects authored demands from its own - composited rows, resolves destinations against player replicas and samples - completed images. Hidden views release their image endpoint. The legacy - attachment retains destination-side foreground clones while skipping its - background and outgoing-body copies; Studio integration follows below. - Request/capture/reply and source-copy byte counters accompany the new scope. - Both-direction foreground tests pass; full Client tests pass 9,222 assertions - / 163 cases. A two-world headless run exits and an inspected offscreen capture - contains geometry, but that distant composite view is not portal image parity - or player traversal proof. Product screenshot sequences, Studio integration, - process-host delivery, replicated interpolation and removal/recreation checks - remain required. No cache-efficiency or release-speed claim is made. -- [x] P8 integration audit repairs: remove stale implicit-camera-marker - expectations from the existing presentation test, classify the transfer ledger - as local world state, and allow its empty unconfigured snapshot to round-trip. - Active state still requires a nonzero incarnation. The full Client audit above - and 404 script transfer assertions / 13 cases pass after the reproduced failures. -- [x] P8 replica presentation preservation: the producer no longer recollects - an adopt-only destination from its latest ECS transforms after presentation. - A GPU fixture publishes the visible interpolated row while the latest transform - is offscreen; both portal and direct probes reproduced a 231-level red-channel - error before the fix. Copied and resident captures now preserve the published - row and leave the latest ECS transform untouched. Runtime/demand/host tests - pass 3,420 assertions / 18 cases, and Client relinks. This fixture isolates - the producer boundary; a complete received-snapshot player sequence remains - required for product interpolation and camera continuity evidence. -- [x] P8 shared Studio image path: Client and Studio now use one product adapter - for authored demand, replica selection, image submission and surface claims. - Studio keeps image ownership per viewport and releases it on viewport closure, - preview-slot changes, world removal/rename, Play replica teardown, game load - and shutdown. Foreground crossing clones remain attached while legacy - background collection is removed from both products. `AppendForeignPortalClones` - gathers authored seams independently of surface slots and appends only crossing - bodies from the viewer's destination replica. The obsolete background adapter - and its product-owned vectors are removed. Focused foreground tests pass - 32 assertions / 2 cases, including unassigned surface slots and replica routing. - Scenes without enabled cross-world portals skip row copies and destination - surveys. No measured speedup is claimed. -- [x] P8 completed-presentation reuse: the producer can consume draw rows from - the host's completed destination presentation without running PreRender again. - This preserves each destination's interpolation alpha and avoids advancing a - replica snapshot buffer twice. A GPU test verifies retained draw rows and host - frame timing; the runtime/demand/host subset passes 3,488 assertions / 18 cases. - Full Studio passes 6,670 / 519 and Client passes 9,222 / 163 after integration. - An isolated two-world Studio server run with two viewports exits cleanly and - produces an inspected scene capture. Its distant camera does not establish - seam quality. Moving player captures, actual process delivery, static capture - reuse and interactive Studio inspection remain open. -- [x] Studio scripting timeline clamp: a zero-duration span at the right edge - reproduced invalid `std::clamp` bounds with standard-library assertions enabled. - Bar layout reserves its minimum visible width before clamping the start, including - subpixel and zero-width panels. The focused suite passes 318 assertions / 16 - cases; full Studio passes 6,912 / 520. The isolated arithmetic also passes with - UndefinedBehaviorSanitizer and standard-library assertions. The Windows screenshot - has no call stack, so matching this defect to that exact crash remains unverified. - A second invalid clamp occurs when a caret move returns an empty completion - list: its old bounds were 0 and -1. This also reproduces with standard-library - assertions. Empty completion results now reset the selection; nonempty results - retain valid choices. Combined completion/diagnostics tests pass 569 assertions - / 34 cases, full Studio passes 6,918 / 521, and Studio and Client build. - After removal of the old portal background adapter, full Client passes 9,177 - assertions / 159 cases. Removed cases exercised the deleted adapter; image - runtime and foreground tests retain the replacement feature coverage. -- [x] P8 capture-revision prerequisites for reuse: the producer includes the - renderer's current flipbook-cell signature alongside spatial-interface state. - Inactive or stationary cloud clocks are excluded from the copied lighting - value, so clock advances cannot invalidate an otherwise unchanged capture. - A Vulkan fixture checks identical pixel hashes and revisions within one cell, - then changed pixels and revision after the next cell. The stale-cell identity - risk and unnecessary clock invalidation are corrected; runtime/demand/host - tests pass 4,033 assertions / 20 cases. Source-owned image renewal is covered - in the separate slice below. - No speedup is claimed. -- [x] P8 resource replacement revisions: the portal producer now folds the existing - renderer resource epoch into its content revision. Same-name texture replacement - reproduced changed pixels with an unchanged revision. Replacement, removal, - restoration and refused removal are now checked with owned GPU captures. - Lens and post-process shader mutations also advance the existing epoch; their - visual replacement cases remain part of the broader shader gate. Vulkan - runtime/demand/host tests pass 4,085 assertions / 20 cases. The epoch is global - to one renderer, so unrelated resource changes conservatively invalidate it; - per-resource dependency narrowing remains open. -- [x] P8 source-owned image renewal: requests offer the content and lighting - versions of a still-owned matching image. A distinct bounded receipt extends - its lifetime without transferring GPU ownership or capturing unchanged pixels. - Sources reject a receipt whose version differs from the offer. Custom shaders - that receive presentation time conservatively invalidate on clock changes. - Vulkan tests cover copied and resident renewal, unchanged handles and upload - counts, expiry followed by fresh capture, and destination motion producing - changed pixels with an unchanged camera. Runtime, exchange, host, demand, - inbox and resident tests pass 5,739 assertions / 35 cases. Actual process - delivery, narrower CPU invalidation and release cost measurements remain open. This avoids capture - work, but still presents and hashes the destination for each request. -- [x] P8 renewal pressure and late-reply recovery: copied and resident tests fill - the reply endpoint, then verify retry sends the retained receipt without another - capture. Delaying a renewal until its owned image expired reproduced a fresh - request returning Busy. Image expiry now cancels that image's renewal offer, - so the source can immediately request new pixels. The late receipt cannot - revive the expired handle. Runtime, exchange, host, demand, inbox and resident - tests pass 5,749 assertions / 35 cases on Vulkan. Process transport and release - performance measurements remain separate gates. -- [x] P8 in-flight camera request coalescing: one portal/profile request remains - active while the source retains only its newest distinct normalized camera/body - demand. Geometry enters camera identity before that comparison. Imported-image - completion or failure issues the retained demand, while capture payloads wait - for `TakeTree`. A full presentation queue retries only until the deferred - deadline; permanent refusal, expiry and endpoint invalidation retire it. - Focused non-GPU tests cover movement, sampling, payload handoff, bounded retry, - seam and endpoint supersession. -- [x] P8 codec cost benchmark: `just portal-exchange-bench` measures owned reply - encode/decode batches for 1, 2 and 8 views at 512x512 linear HDR, alongside - resident receipts and renewals. Each copied image has a 2 MiB pixel payload. - Decoding validates its hash and size; receipts must round-trip exactly. - The release-derived `bench` preset built and all nine rows ran with five - samples on a Ryzen 9 9900X, with heap profiling enabled. Measurements remain - on the terminal. No GPU backend, world presentation, bus delivery or process - transport is included, so full-frame and residency benchmarks remain open. - The unity build also reproduced private constant/helper collisions in the - presentation and portal geometry codecs; specific helper names fix them - without changing either wire format. Dev exchange/geometry tests pass 2,109 - assertions / 12 cases and presentation-bus tests pass 944 / 8 after the repair. -- [x] P8 standalone process image producer: `PortalImageHost::Serve` opens a - bounded local producer without requiring a local viewport. Its returned - endpoint can be distributed by authenticated host control traffic. A real - child process owns a Vulkan renderer, captures its world's HDR image, and - sends copied pixels through `HostLink` and authenticated presentation buses. - A second request returns a renewal and preserves the parent's owned image; - the child verifies exactly one capture and one renewal. Producer removal and - reopening change endpoint generation. Runtime/host/demand tests pass 4,289 - assertions / 22 cases plus 17 child-process assertions. Client and Studio build. - This initial fixture pre-registers endpoints; product discovery and continuous - player traversal across process hosts remain open. Moving-scene source - compositing is checked in the following slice. -- [x] P8 process image source-compositing slice: a child-owned red wall occludes - a green wall. The unchanged camera first receives red pixels, then renews - without upload, then receives green pixels after the foreground wall moves. - The parent composites each received image onto a portal under different source - lighting. A 3x3 aperture patch matches the expected destination radiance after - display conversion within 2/255. Upload counts are one, one and two, while the - child verifies two captures and one renewal. Runtime/host/demand tests pass - 4,428 assertions / 22 cases plus 24 child-process assertions on Vulkan. - This is a fixed-camera planar fixture with pre-registered endpoints; full - aperture parity, product discovery and moving player sequences remain open. -- [x] P8 product endpoint lookup: portal routes now carry authored and resolved - world identity only. The shared image host looks up remote request endpoints - in the universe's authenticated presentation registry; Client and Studio no - longer supply an empty endpoint that makes every remote route unavailable. - Lookup uses the existing bounded registry without a duplicate cache. Tests - cover absent endpoints, wrong names, close/reopen, stale close, world removal - and session reset. The real-process fixture resolves its registered endpoint - through the same lookup. Runtime/host/demand tests pass 4,442 assertions / 23 - cases plus 24 child assertions; presentation tests pass 960 / 9. Client and - Studio build. Automatic authenticated endpoint advertisement/withdrawal is - still required: process fixtures currently register endpoints during setup. -- [x] P8 authenticated directory receive path: bounded full endpoint sets carry - a host session and revision over a dedicated `HostLink` control frame. The - supervisor attributes them to the actual connection; the driver checks world - ownership before changing the existing presentation registry. Newer sets - retire missing or replaced endpoints and their queued messages. Retained - endpoints keep their message sequence history. Empty sets withdraw all of a - host's endpoints; retained version records reject old advertisements after - withdrawal or restart. The full world suite passes 28,467 assertions / 213 - cases, including malformed/truncated frames, duplicate identities, ownership, - withdrawal and stale replay through the real driver pump. - Client and Studio build; portal-host tests pass 236 assertions / 6 cases plus - 24 child-process assertions. Renderer-free server hosts explicitly refuse the - directory frame alongside image traffic. -- [ ] P8 directory product lifecycle: emit changed local directories from render - hosts, forward accepted endpoints to consumers over authenticated connections, - retry bounded control traffic, and withdraw endpoints on disconnect/restart. - The process fixture now exchanges advertisements as recorded below; product - host pump wiring and abrupt disconnect cleanup remain required. Combine discovery with the continuous Humanoid - crossing/image/ownership sequence described in the portal acceptance gates. -- [x] P8 directory publication and process discovery: the host link publishes - changed directory versions and skips unchanged ones. A full channel does not - advance the published version, allowing a later pump to retry. The process - image fixture no longer constructs or registers remote endpoint receipts: - both sides advertise their local directories over the authenticated link. - Captured and renewed images still meet the source-compositing checks. Before - shutdown the child withdraws its endpoints, the parent removes the displayed - image on its next submission, and an acknowledgement lets the child exit. - Full world tests pass 28,483 assertions / 214 cases; portal-host tests pass - 248 / 6 plus 46 child-process assertions. Client and Studio build. This proves - the link publisher and process exchange, not automatic product host forwarding - or abrupt disconnect retirement. -- [x] P8 supervised disconnect retirement: a reproduced driver test kept a dead - host endpoint discoverable after link close. Presentation pumping now retires - unlinked hosts. Explicit link replacement, supervised respawn and shutdown also - retire the old connection and discard its buffered advertisements/images. - Registry retirement purges queued image traffic while retaining the old host - session as rejected history; even a higher revision in that session cannot - restore it. A new host session can advertise again. Tests cover observed close, - replacement before the next pump, stale directory/direct registration, queue - retirement and successful restart. Full world tests pass 28,528 assertions / - 216 cases; Client and Studio build. Consumer-host forwarding and the continuous - player crossing remain open, including retirement at non-supervised peer links. -- [x] P8 driver-to-consumer route forwarding: hosts that advertise presentation - endpoints receive a separate driver route snapshot containing the other hosts' - admitted endpoints. Producer sessions/generations remain unchanged; the driver - versions the aggregate set, so disconnect withdrawals supersede old routes. - Consumers apply route frames only through their trusted-driver boundary and - cannot replace a local endpoint. Host-originated route frames are refused. - Unchanged sets emit no frame, failed control sends remain retryable, and the - driver retains its bounded outgoing image queue until route control is queued. - A two-host test discovers both directions, forwards image bytes, disconnects - the producer and observes withdrawal at the consumer. Full world tests pass - 28,764 assertions / 218 cases; portal-host tests pass 248 / 6 plus 46 child - assertions. Client and Studio build. Binding the render-owning product host - loop to this forwarding path and proving continuous player crossing remain - open; the existing GPU child fixture still uses its direct authenticated link. -- [x] P8 client producer host loop: the actual client executable can select one - game world, retain other worlds as remote routes, advertise its producer and - consume driver route snapshots over an inherited process channel. The shared - render adapter pumps control outside ticks, retains replies under link - backpressure, and clears image ownership on stop or disconnect. The real - client process GPU test passes 49 assertions for discovery, a 16 x 16 HDR - reply, clean stop and abrupt driver disconnect. Client and Studio build. - Full client tests pass 9,177 assertions / 159 cases; - portal-host tests pass 248 / 6 on Vulkan. This test checks transport and - lifecycle, not image content or continuous player crossing. Automatic product - launch policy, moving cross-world images and combined player handoff remain - open. -- [ ] P8 slice: transfer the existing rig through an idempotent reserve/commit - protocol, with bounded replayable state, exact receipt identity and no duplicate - authority. Retain camera orientation, zoom and Humanoid selection across the - product session change. Destination admission and session integration are active. -- [x] P8 fresh admission gate: transport admission creates no avatar. The Client - and load-test session explicitly request a fresh player, and repeated requests - retain the same player and character. Admission replies survive send - backpressure with one retained reply per connection; a newer attempt replaces - the pending reply, and disconnect or shutdown clears it. Resume requires a - destination lease and the exact committed transfer receipt. -- [x] P8 slice: preserve full camera orientation and scaled lens/controller - lengths through tilted portals, including skipped presentations and repeated - crossings. First-person thresholds scale with the camera; input directions - follow its mapped basis. Physical gravity still uses the destination's world Y. -- [x] P8 replay gate: preserve future entity allocation across snapshot restore. - The transfer replay test exposed lost free-slot order and receiver page epochs. - The focused ECS reproduction failed 80 assertions. Snapshot version 7 now saves - allocator order and page epochs; strict transfer replay passes. Adopted holes, - released large pages and malformed allocator metadata are covered too. -- [x] P8 session readiness: retain the old replica through a chunked destination - join. Switch only when every destination object and the mapped Humanoid camera - are ready. A disappearing destination cancels its pending successor replica. - This proves session state; the moving visual transition remains required. -- [x] P8 angle oracle: sweep 45 camera positions through both faces, 36 azimuth/ - elevation combinations, roll, near-plane approach and looking away. All 95 - lighting/appearance sections pass their unchanged colour bound. Dynamic objects, - mixed mirror/portal recursion and imported views remain separate - acceptance checks. -- [x] P8 moving-light oracle: hold the viewer fixed while changing the destination - light position three times. Compare each portal image against an independently - unfolded room and require its content hash to change. All 155 assertions pass, - with a maximum difference of 1/255 within the unchanged 2/255 bound. -- [x] P8 shipped immersive demo transfer slice: remove the proximity respawn and correct the - stand-in's half-turn and 0.6-metre plane mismatch. Authored geometry and standing - near either face now pass. The actual two-world round trip exposed immediate - reentry from an admitted previous transform. Admission now retires that segment; - both approaches and return trips preserve pose, momentum, health and limb - placement with at most one authoritative body. All 150 assertions pass. -- [x] P8 mirror HDR/cache slice: preserve half-float radiance, refresh lighting - and retained spatial UI, and enforce shared recursive pixel/depth budgets. - A same-name texture replacement reproduced four stale-capture failures; a - renderer-owned resource epoch now invalidates retained mirrors after successful - resource edits. All 19,410 assertions pass, including unchanged capture reuse. -- [x] P8 authored non-Euclidean opening slice: reproduce twelve missing return - links and ten blocked entrances. Give each entrance a distinct reciprocal - pane, cut openings through the authored walls and align traversable floors. - All 365 geometry/clearance assertions pass. Real fixed-tick humanoid movement - then passes through all 24 openings, with 75 assertions. A separate continuous - walk reproduced the pillar's missing connection. Its rear doorways now connect - both hidden rooms, giving 26 surfaces. Two actual humanoid laps, every opening - and all return mappings pass 512 assertions in four cases. A seekable camera - tour covers 1,170 shots across those mouths, with pause and single-step controls. - Both faces, roll, grazing, near-plane and look-back poses pass fixed-tick checks. - Full examples now pass 100,862 assertions in 61 cases. Inspected demo images and - interactive crossing sequences remain separate acceptance work. -- [x] P8 object/animated-rig transfer slice: the transaction carries ordinary - bodies, tools, animation playheads and bounded clip/buffer dependencies. - Shared source definitions survive. Refusal restores frozen animation bytes; - scaled skinning passes vertex parity. Script tests pass 665 assertions in 74 - cases, with 69 actual process-child assertions. Full scene tests pass 514,473 - assertions in 525 cases after the roll/cut expectation update. -- [x] P8 requested-view collection slice: stable surface slots work without an - authored active camera; request-local beams face the requested eye. Billboard - size derives from the requested projection. Focused billboard pixels pass 66 - assertions after reproducing the incorrect focal scale. The shared child-first - executor now passes the mixed mirror/portal runtime image gate, including - request-facing beams, owned bus images and direct-tone parity. Full child PBR - parity and per-child transparent ordering remain separate work. - -## do not keep a ongoing log here. diff --git a/docs/future-work/RENDER-REFACTOR.md b/docs/future-work/RENDER-REFACTOR.md deleted file mode 100644 index f6ebe2328..000000000 --- a/docs/future-work/RENDER-REFACTOR.md +++ /dev/null @@ -1,3428 +0,0 @@ -# render refactor plan - -## continue here: portal crossing, 2026-09-07 - -This is an implementation checkpoint, not completion of the refactor. Work -resumed on 2026-09-08 with gameplay lease retirement and admitted source observer -and content ownership. Detailed evidence and local artifact paths are in -[PORTAL-HANDOFF.md](PORTAL-HANDOFF.md). - -- Next: finish retained-world endpoint/lifetime and Client-driven GPU owner-retirement checks across content sessions. Renderer checks now cover retirement before submitted-draw readback and twelve owner reload cycles with stable surviving pixels and bounded logical residency. Client source-observation expiry releases its published texture while the successor stays visible; product mesh reclamation and staged cancellation remain open. Client mesh/texture delivery, editable uploads, native/copied views, image callbacks and main viewport widgets use local world residency names. Staged successors pump their own content route and move it at adoption. Late same-name mesh/texture delivery, refused source assets and later local-world demand now pass product checks. Per-owner demand history prevents adoption from fetching completed destination assets again. Gameplay lease renewal stops after authenticated destination adoption; full current-camera rendering remains open. -- Then: complete current-camera foreign rendering. The Client binds shared packets for retained sources and authenticated successors, including the continued body pose before adoption. Admitted local destinations supply complete portal captures at the requested camera. The earlier 24-run product matrix passed 202,963 assertions; newer resource checks are recorded in the handoff. The shader compiler cache supports owner-scoped material/lens modules, and Client material/lens uploads, postprocess selection and screen interface shaders now use those owners. Spatial interface variants now pass owner, clipping and depth-mode pixel checks through both display and HDR graphs. The handoff corrects the earlier format label. Accepted shader hashes now let each interface pass reconcile missed refreshes independently; Client GUI preparation uses that path. Material, lens and postprocess device registration now reuses identical accepted words without resource invalidation. Client main, retained and staged views now share owner-scoped shader preparation. Portal producers now use the same preparation before renewal checks, sharing the Client compiler and postprocess setting. Authored opaque programs now draw through the deferred graph with colour and nearest depth preserved. The real 60 Hz Client round trip now verifies same-name red/blue material shaders. It reproduced and closed missing material resolution before replica collection. The reproduced spatial GUI adoption jump is closed for depth-tested collectors: authored GUI batches now join remote ordered layers through graph-owned scratch colour/depth and layer replay. The current body still composes against those depths. Always-on-top collectors need a separate ordering contract and are explicitly refused by this path. Studio migration, lens/grade shader crossing and shader edits during transfer remain open. Foreign viewport-widget preparation, unadmitted eyes and remote portal-image parallax also remain open. -- Keep the moving-camera `[eye-current-camera]` failure as the image gate: three moving cases remain failing. The old retained-source image staging prototype remains rolled back; the new observer/successor geometry path is a separate implementation. -- Reproduce the original black frame with a valid image handle using the stage probe. A separate missing-image black frame was captured during a topology wait; a common cause is unproven. -- Verify continuous outbound/return player crossing with Humanoid camera subjects, body ownership and obstruction under delayed messages, restarts, refusals and lost acknowledgements. -- Complete visual checks for lighting, clipping, transparency, effects and animated accessories at oblique, rolled and scaled portal angles; inspect the non-Euclidean demo. -- Finally measure release CPU/GPU work, residency, cache invalidation and transferred bytes, including the complete Terrain editable collision worker path. - -Already verified: topology expiry/renewal and ready-reply routing fixes; all 16 -product camera crossing variants (136,117 assertions); stage probe overwrite -checks (756 assertions in two cases); Terrain BVH canonical-layout parity and -builder improvement. These are recorded runs, not a fresh full-suite validation -of this checkpoint. Stage probing stalls the GPU and can change timing. Keep -captures bounded and clean up bulk images after retaining failure evidence. - -## 0. scope and review status - -Implementation requested against this full plan. Progress and evidence live in -[RENDER-REFACTOR-TASKS.md](RENDER-REFACTOR-TASKS.md). Nothing marked planned below -is a claim that the feature ships. Baseline inspected at -`b61c564c`; future implementation must recheck the relevant code and tests. - -This document consolidates `RENDER_PIPELINE.md`, -`future-work/OPTIMISATIONS_RENDER.md`, and -`future-work/materials-and-shaders.md`. Their requirements belong here now. -[TORNADOSIM.md](TORNADOSIM.md) remains the gameplay demo plan; its render needs -are included here. The attached checklist and [ROADMAP.md](../../ROADMAP.md) -v0.24 define the requested work, even where older notes called it future work. - -Review covers the whole destination, the phase order, and the explicit policy -changes below. Completing this document does not complete the renderer. -Each implementation phase must leave a working engine and evidence for its gate. - -### decisions that need review - -| Decision | Proposed resolution | Consequence | -|---|---|---| -| Live compiler versus cooked shaders | Adopt the materials plan: cook published modules; Studio previews use the same compiler through jobs; shipped clients execute published modules only | This changes the current render module policy requiring runtime shaderc. Update that policy with human sign-off before removing the client compiler. This planning change does not silently override it. | -| Everything in nodes | All render work, including residency, uploads, simulation, captures, UI composition and presentation, has graph ownership and declared effects | Device helpers remain ordinary functions called by nodes. A helper is not a second scheduler. | -| GPU state versus ECS ownership | ECS owns authored values and simulation transforms; GPU owns derived visual state and caches | Per-instance capability flags, visual displacement, visibility and LOD choices are GPU-readable. There is no CPU mirror of GPU decisions in the frame path. | -| Parallel scenes | Collect all active scene/camera requests, prepare immutable slices in parallel, join, then record and submit on the render owner thread | Keep world affinity and deterministic tick barriers. Multiple cameras share world residency. | -| Ray/path tracing | Ship compute-based tracing nodes on the supported compute baseline; add native hardware paths only behind measured, probed support | A catalogue label, SSR effect, or fallback image does not count as a tracer. | -| Visual compositor and material authoring | Extend the existing Studio canvas and typed engine documents; material graphs compile through the shader cook | No second canvas runtime or special preview renderer. Older exclusions of visual shaders and tracing do not remove these requested features. | -| Quantization | Support both compact stored formats and explicit value rounding through editable-content policy components | Merely rounding float32 values is not a memory reduction. Native storage, arithmetic and sampling support are separate capabilities. | -| Portals | Finish same-world and cross-world visual/physical seams under explicit ownership and bounded recursion | Visual proxy geometry cannot become a second authoritative body. | - -Protected `AGENTS.md` files are unchanged during planning. Historical mentions -of `RENDER_PIPELINE.md` in policy, old roadmap entries and source comments refer -to the predecessor of this document. Implementation phase P0 must reconcile -those references and outdated policy statements through the approved exception. - -### optimization order and decision rules - -Optimize in this order: avoid undemanded work; reuse valid results; update only -changed ranges; reduce representation and intermediate bytes; batch remaining -work; then tune kernels and overlap. GPU placement is a decision about data and -consumers, not a rule that every small operation deserves a dispatch. - -Every optimization below must name its owner, inputs, reuse key, invalidators, -resident and scratch bytes, update frequency, fallback and proof. Classify it as -exact reuse, equivalent execution, bounded approximation or quality reduction. -The last two need an authored error/quality policy and cannot silently count as -the same image at lower cost. - -Retention trades recomputation for memory and invalidation cost. Keep a result -only when its expected reuse repays lookup, storage, maintenance and eventual -retirement. Fast-changing low-cost intermediates should remain transient; no -requirement here means caching every node output or retaining every world forever. - -## 1. requirements and proof map - -| ID | Requested result | Detailed plan | Required proof | -|---|---|---|---| -| R01 | Easy, thorough per-step image and projection tests | §5 | Real offscreen GPU captures, mathematical oracles, per-pass failure artifacts | -| R02 | Seamless portal light, physics, projection, clipping and crossing geometry; visible demo | §12, §19 | Automated crossing sequences, body ownership tests, inspected portal demo | -| R03 | Per-mesh, world-lighting and camera capability controls | §6 | Inheritance/mask tests and GPU branching without readback | -| R04 | Remove rendering outside nodes; residency and delta upload in same refactor | §3, §4, §20 | One executor, zero hidden frame work, actual zero-traffic reuse | -| R05 | Semi-real raytrace and path-trace nodes | §11 | Real intersections, secondary visibility, convergence and reset tests | -| R06 | Tracing example pipelines | §19 | Named hybrid and progressive pipelines, captures and profiles | -| R07 | Attach compute/post nodes to every visual item; active shader residency | §6, §8 | Coverage matrix for visual families, deterministic placement, inactive no-work checks | -| R08 | Dynamic AO, emissivity, mipmaps, conservative occlusion, sRGB, PBR, tessellation, environment compute, GI, displacement | §7, §9 to §14 | Feature-specific numeric, image and lifetime tests | -| R09 | Blender-like workflows and nodes for all features | §8, §19 | Material and compositor authoring, groups, previews, save/undo/cook round trips | -| R10 | Unity-like visual compositor system | §3, §8 | One typed authoring-to-runtime path with inspectable intermediate outputs | -| R11 | All active scenes, entity lists, resident update, batched cameras; parallel/vectorized prep | §4 | Serial/parallel parity and upload counts independent of camera count | -| R12 | Editable mesh/texture packing, quantization component, many 4K textures, atlas | §13, §14 | Actual byte reductions, decode error bounds, pressure and bleed tests | -| R13 | Different AA choices as nodes | §10 | None, MSAA, FXAA, SMAA, TAA and temporal upscale with honest tier support | -| R14 | Four authored LOD meshes, automatic decimation, projected-triangle/meshlet path | §13 | GPU view-specific selection, seam/error tests, stream fallback and no CPU round trip | -| R15 | Port all material/shader contracts | §7, §15 | Author, save, script, cook, publish, load, reload, fallback and retire | -| R16 | Preserve all optimization research and TornadoSim needs | §9 to §18, §22 | Every old subsection maps to an owned phase or measured candidate | -| R17 | Optimize every section without reducing the requested result | Optimization refinements throughout §0 to §22 | Per-phase ablations, bounded residency, correct invalidation and full-frame cost evidence | - -### cost coverage across requirements - -| Requirements | Main costs to attack | Required negative control | -|---|---|---| -| R01 | Device setup, readback and fixture cooking | Optimization-disabled images and CPU comparison still catch faulty output | -| R02 | Recursive views, repeated geometry/light work and seam candidates | Camera/light/body movement invalidates exactly the relevant results | -| R03/R07 | Per-item policy merging, dispatch count and shader variants | Empty effect mask launches no image work; distinct effect order is preserved | -| R04/R11 | Full-world scans, packing, uploads and per-camera duplication | More cameras do not multiply unchanged world extraction or uploads | -| R05/R06 | Traversal, ray divergence, queues and accumulation | Same sample budget and estimator when comparing exact execution changes | -| R08/R13 | Attachment bandwidth, overdraw and temporal history | Motion, disocclusion and exposure changes reveal unsafe reuse | -| R09/R10 | Graph recompilation, hidden previews and intermediate images | Moving nodes in the editor causes no shader or runtime rebuild | -| R12/R14 | Mesh/texture fetch, packing churn and streaming amplification | Fine-detail/seam quality stays inside its declared error at fixed budget | -| R15 | Repeated parsing, whole-material rebuilds and pipeline creation | One texture edit creates no shader; one uniform edit changes no descriptors | -| R16/R17 | Duplicate machinery and unmeasured optimization complexity | Each candidate is removable or falls back through the same graph contracts | - -## 2. current foundation and gaps - -Current code is evidence; old prose is context. Do not inherit obsolete numbers -or a checked box without inspecting its implementation and consumer. - -| Area | Evidence inspected or located | How to use it | -|---|---|---| -| Graph authoring | `mono.engine/graph/src/PipelineDocument.cpp`, `PipelineCatalogue.cpp`, `NodeSchema.cpp`; Studio `RenderPipelineGraph.cpp` | Keep ordered documents, shared declarations, typed links and round-trip tests. | -| Node handlers | `mono.engine/render/src/nodes/{Upload,Geometry,Shading,Shadow,Portal,Mirror,Authored,Output}Nodes.cpp` | Existing family split is the migration seam. | -| Upload wrapper | `UploadNodes.cpp` registers CPU finish spans and `upload-instances`; CPU work currently happens in `ViewRecording::Begin` | Make scheduling control real execution, not only retrospective labels. | -| Instance packing | `InstancePacking.hpp::GpuInstance` has position, full-float quaternion, scale, packed colour/appearance/surface colour/emission | Current aligned row is 64 bytes. Lower-precision quaternion experiments caused oblique aperture coverage gaps; retain numeric and image gates when changing this layout. | -| World instance residency | `InstanceResidency.hpp`, corresponding tests | Reuse stable slots, generations, dirty spans and acknowledgements. | -| View ordering | `IndexResidency.hpp` holds three in-flight versions and pending acknowledgement | Preserve per-view whitelists and failure retry; do not upload shared rows for each camera. | -| Batched renderer | `Renderer.hpp` and `Renderer.cpp` expose a span of `View` values | Product collection remains work. Studio `Editor::PresentWorld` still builds a round-robin candidate list. | -| Hidden mesh transfer | Batched `Renderer::Render` calls `State->Meshes.Flush()` before grouping worlds/views | Move this transfer into graph-owned residency work with the same batching behavior. | -| Presentation damage | `WorldPresentation.cpp::ScenePresentationSignaturesOf`, `PresentationDamage.hpp` | Keep objects, particles, environment and portals separate; UI and diagnostics have separate damage. | -| Editable content | `scene/EditableMesh.hpp`, existing revision consumers | Reuse world-owned authoring data, mutation revisions and collision rebuild boundaries. | -| Materials | Legacy AMT1 versions and seven-map material records described by the material plan | Verify each map's current consumers before conversion; translate old content into one schema. | -| Device tests | [RUNNING.md](../../RUNNING.md) documents `[gpu]`, `--gpu-tests`, `Renderer::Initialise(nullptr)` and capture | Extend the real-device harness. Ordinary headless runs do not prove pixels. | -| Tracing | `PipelineCatalogue.cpp` contains a `raytrace` declaration; search found no corresponding tracer in inspected render node families | Inventory any previous implementation/history before porting. Backend and actual image proof remain required. | - -The old render plan records registration, capability checks, custom native -handlers, profiling, compiler optimization/reflection, command-buffer grouping, -transient aliasing and tiered defaults as implemented. P0 must verify those -claims with current consumers and suites; this plan does not rerun them yet. - -### baseline frame and data - -The predecessor's default order is `world`, optional `shadow`, `camera`, -`last-frame`, `entities`, `cull-frustum`, `order-draw`, `upload-instances`, -optional `mirror-capture`, `portal-capture`, `portal-tonemap`, `gbuffer`, -`depth-linearise`, optional `ssao`, `deferred-lighting`, `sky`, `tonemap`, -`portal-overlay`, `mirror-overlay`, `transparent`, `present`, optional -`interface`, final `overlay`, final `output-image`. Preserve its reference -images during extraction; §10 and §12 then deliberately correct the colour -and portal composition order with new proofs. - -Resident state includes mesh/index buffers, packed instances, draw-order streams, -source textures, seven material maps, shaders/pipelines, particle pools, retained -game-GUI geometry and glyph atlases, ImGui buffers, and shadow/surface/history -targets. Revisions gate editable content; signatures gate retained geometry; -dirty ranges gate instance/mesh data; overlay uploads use a dirty rectangle. -Lights/cameras upload small structured values; ribbons upload compact geometry. - -No normal frame uploads a CPU-composed GUI or scene image. Full pixel uploads -are source textures or explicit editable images. Readback is for requested -captures, tests, completed timing queries and bounded asynchronous streaming -feedback. Same-frame visual decisions do not wait for CPU readback. - -### external spatial extraction boundary - -An external data factory may pull a revision-fenced raw spatial scene after the -engine has generated it. That record carries stable IDs, transforms, geometry, -cameras, and explicit unavailable facts through bounded MCP reads. It is an -engine export boundary, not a render-thread callback or a new render graph. - -The renderer continues to own GPU work, asynchronous image readback, and its -own resource lifetime. External code owns scene conversion, dataset storage, -and model training. Do not add file writing, data conversion, or training work -to a render hook or frame path to serve this use case. - -### optimization evidence to gather first - -At `ed588cbf`, `WorldPresentation.cpp::ScenePresentationSignaturesOf` still signs -the instance span and folds joint-frame and light spans for a view. Its helper -walks each value's bytes. This is a concrete candidate for avoiding repeated -CPU work; it is not a measured bottleneck or proof that upstream extraction is free. - -Before changing it, count entities/bytes visited, rows packed, allocations and -signature calls per world and camera. Distinguish initial discovery, changed-world -preparation and unchanged presentation. Profile grouping, content lookup and -resident row comparison independently so a zero-upload report cannot hide a -whole-world scan. - -Use existing counters and narrow temporary instrumentation first. P0 records a -baseline for one still world, one moving entity, camera-only motion and many -cameras. These expose different causes and avoid treating a single large stress -scene as evidence for every proposed cache. - -## 3. one graph from authoring to frame - -### ownership and layers - -| Owner | Responsibility | Boundary | -|---|---|---| -| `scene`, ECS and world | Authored components, simulation transforms, revisions, immutable published views | No device handles; cross-world values are copies with stable names | -| `graph`, L9 shared | Documents, node schemas, pure selection math, resource contracts, validation, schedule, lifetimes, diagnostics | No SDL, shaderc or device objects | -| `render`, L12 client | Device probes, resident caches, node backends, command recording, GPU allocation and retirement | No second world registry or gameplay state | -| `resources`, L11 client | Built-in shader names/source and staging | Consumers use `resources::Shader(name)` | -| `msl`, L11 client | Existing SPIR-V-to-MSL translation | One translation rule, entry and binding checks | -| `assets` and delivery | Bounded cooked containers, content identity, signed manifest and verified bytes | No material policy or shader compilation in CDN | -| `bake`, bake graph and tools | Foreign imports, decimation, packing, shader/material cooking and reports | No runtime engine dependency on source importers | -| Proposed shading libraries | Pure shader schemas/records separately from source compiler/optimizer/reflection worker | Determine legal layers before adding targets; runtime reader cannot pull compiler transitively | -| `mono.studio/nodegraph` | Existing generic canvas, layout, model and serialization | No engine render semantics in canvas | -| Studio/client | Active panels/cameras, frame requests, editor documents and authoring jobs | Engine systems stay under `mono.engine` | - -The materials plan proposed one `Engine::shading` library. Split its reader and -compiler targets if needed: a shared runtime schema cannot link client-only MSL -or drag shaderc into the shipped reader. Add exact layers/edges to -`expected_graph.json`, test server-only configuration, and do not create -`mono.engine/renderer` or widen a tier escape. - -### document and compiler contract - -Keep `PipelineDocument` ordered edits and the existing `renderpipeline 2` reader. -A versioned extension must preserve old inputs through one conversion reader. -Names, parameter keys, feature keys, resource names and node kinds serialize as -strings; document positions are authoring metadata, not execution hashes. - -The chain remains document -> `Build` -> `RenderGraph` -> `Compile` -> -`CompiledGraph` -> `CompileSchedule` -> command-buffer plan -> backend executor. -Compile on edits/installation, not per view per frame. Publication lowers -authoring conveniences to cooked module and resource references. - -Declaration order defines effects and each resource version. Reads/writes -validate that order; dependency waves expose independent work without changing -visible composition. Multi-writer resources use versioned writes; history reads -refer to the prior successful frame explicitly, never an implicit cycle. - -Scopes remain `Frame`, `World`, `View`; Final is an execution partition, not a -fourth authored scope. Reject world/shared work interleaved inside a view block -when it cannot retain its semantics. A world node runs once per distinct world -and matching resource key, not once per camera that happens to see that world. - -Unconnected optional entity inputs mean empty; missing required ports fail -validation. Camera fallback to the current view remains explicit in schema. -Disabled nodes leave the schedule; unused pure nodes can be removed by backward -reachability, but simulation, uploads, capture and present declare side effects -and survive if their effects are demanded. - -### resource contracts - -Preserve `Colour`, `Depth`, `Texture`, `Storage`, `Buffer`, `Camera`, `Entities`. -Extend descriptors with access, sample count, array/depth extent, mip range, -colour/alpha space, buffer stride, lifetime, owner and history generation. -Volume density, light lists, acceleration structures and visibility masks need -typed schemas over these resources, not unexplained buffer numbers. - -Keep existing formats: R8, RG8, RGBA8, RGBA8_SRGB, RGB10A2, RG11B10F, -R16F/RG16F/RGBA16F, R32F/RG32F, D24S8/D32F and BC arrival formats. -Add formats only with capability, byte accounting, sampler/storage legality, -conversion and backend tests. Resource kind and pixel format remain separate. - -Texture inputs may accept sampled colour/depth/storage outputs when usage allows; -a sampled asset is not automatically a render target. Validate sample type, -integer/float/depth meaning, dimensions and access, not only channel count. -Implicit narrowing reports `LossyWire`; explicit conversion names its target -and suppresses only the narrowing it deliberately performs. - -Aliasing uses strict nonoverlapping lifetimes and exact compatible descriptors, -scope and owner. External assets, swapchain and retained history do not alias. -Derive RAW/WAR/WAW and alias transitions; do not recycle targets while pending -GPU work, another view or an exported capture still references them. - -### registration and backend contract - -One `NodeKindSpec` declares kind, label, summary, category, scope, queue, -parameters, ports, defaults, requirements, fallback and backend support. -Init-only idempotent registration preserves pointer stability; custom names -are namespaced strings. Registry drives Studio widgets, compile checks and -backend acceptance, including headless CPU-only kinds. - -Keep authored `raster`/`dispatch`, reusable canvas groups and native kinds. -Groups flatten through one compiler with source-node mapping for errors. -Native handlers need a small command interface for attachments, bindings, -draw/dispatch, copies, barriers and timestamps; SDL stays in its adapter. -Do not promise a second backend from an interface alone. - -Installation validates every enabled node, reflected bindings, formats, -capabilities, scope, queue and fallback before admission. Unknown kinds survive -authoring round trips visibly unresolved; runtime refuses with node and reason. -Install replacements atomically; preserve the last accepted pipeline on failure. -Release targets, caches, history, capture receipts and custom handler state by -pipeline/world lifecycle after in-flight use ends. - -Command-buffer fusion merges legal adjacent submission units, not shader source. -Every node keeps its name, resource effects and timing attribution. SDL's unified -queue can serialize transfer, compute and graphics; scheduling eligibility does -not prove actual GPU overlap. - -### compiler, schedule and allocation optimizations - -Split document change classes: layout/labels, uniform values, binding references, -resource descriptors, topology and shader interfaces. Cache compiled topology -by semantic graph/interface/capability key; layout edits touch no runtime state, -uniform edits replace parameter data, and descriptor changes rebuild only affected -allocation/binding plans. Initially retain full compilation as the correctness -oracle; incremental rebuild must produce the same accepted plan. - -At install, resolve stable names to dense local IDs and build contiguous arrays -for nodes, edges, resource versions and handler calls. Parse text parameters once. -Do not perform registry lookup, string parsing or callback-map construction for -every node invocation. Bound cached plans across graph and device generations. - -Keep pure world preparation separate from pipeline-specific work: two pipelines -reading the same world can share extraction/uploads while owning distinct -view resources. Deduplicate identical pure producers only when scope, inputs, -parameters and effects match; differently ordered writes or history cannot merge. - -Resource liveness drives attachment creation, initialization and final stores. -Clear or discard only when coverage proves previous contents unnecessary; retain -depth used by HZB/soft particles and any output read by capture. Prefer legal -same-attachment pass batching over extra stores/loads, with backend support -checked. [Khronos attachment guidance](https://docs.vulkan.org/samples/latest/samples/performance/render_passes/README.html). - -For real concurrent queues, disjoint positions in a linear node list do not -prove safe aliasing. Require a happens-before path from the old resource's last -access to the new resource's first access; otherwise allocate separately or add -an explicitly costed synchronization edge. Captures and previews extend lifetimes -and must participate in this same plan. - -Minimize barriers to declared subresources and real hazards; merge compatible -read transitions and remove redundant state binds through a command-context -cache reset at every required backend boundary. Never cache raw command buffers -across changing swapchain/frame resources unless the backend explicitly permits -it; reusable CPU execution plans are the portable baseline. - -Async compute is an optional schedule: compare serial and overlapped full frames, -including extra memory, queue transfers and contention. Compute and raster that -both saturate memory may become slower together. Select measured presets, with -the same resource/ordering validation, instead of enabling async universally. - -## 4. resident worlds and parallel frame preparation - -### execution chain - -```text -owner-barrier world snapshots + active output requests - -> collect distinct worlds and all demanded cameras - -> parallel immutable presentation extraction, per-world output slices - -> join and canonical merge - -> residency-plan / upload-deltas [world] - -> particle-step / material-resolve / visual-derive [world] - -> camera setup / conservative cull / LOD / indirect lists [view] - -> shared and view shading / portal capture / post / composition - -> output / capture / present - -> successful-write acknowledgement and frame retirement -``` - -The product collector includes active game cameras, visible Studio viewports, -requested asset/material previews, surface/portal/mirror cameras and explicit -offscreen outputs. Hidden/inactive docks request nothing; paused worlds may -still need a redraw after edits. Minimized windows do not acquire a swapchain, -but an explicit offscreen capture remains a valid request. - -Each request has world identity/generation, view identity/generation, camera, -output extent, pipeline, quality, source signatures, history identity and reason -for activation. Deduplicate world work; do not deduplicate distinct cameras or -eye-specific history merely because their current matrices match. - -Capture world-owned immutable data at an owner barrier or through existing -presentation channels. Workers never call `Universe::Enter` on foreign threads, -mutate ECS, issue SDL calls or hold borrowed state across owner mutation. -Each worker writes a disjoint pre-sized slice; join and merge in stable -world/entity/view order before the render thread records. - -Batch related columns and compact hot records; use prefix sums for output offsets -and vectorizable cull/pack loops. Reuse scratch capacity. Measure serial versus -parallel grain in release at 0, 1, small and large worlds/camera counts; write -the crossover beside the implementation rather than assuming parallel wins. - -### stable residency and delta nodes - -World resident identity includes world generation; entity slot identity includes -entity generation. Deletion invalidates membership and retires referenced ranges -after fences; reuse cannot display a previous entity's visual state. -World destruction releases particle pools, instance tables, history and bindings. - -Keep authored transforms and compact input records separate from GPU-produced -visual fields. Proposed GPU rows/sidecar columns carry capability bits, material -slot, visual effect range, bounds metadata and deformation state. Layout is -private, versioned, aligned, byte-tested and decoded by matching shaders. - -View-specific visibility, selected LOD, motion history and indirect counts live -in GPU per-view buffers keyed by stable slots. A single mutable LOD field in a -world row would race cameras and shadows. Shared rows carry LOD policy/level -references; each view stores its own result beside its occlusion output. - -Residency planning computes dirty ranges from existing mutation/revision feeds. -Upload nodes coalesce only changed spans and update each in-flight version that -needs them. CPU authored/staging inputs are allowed; a continuously synchronized -CPU copy of GPU visibility, displacement or particle state is not. - -Publish acknowledged revisions only after the required upload/render succeeds. -Failed acquire/submit keeps damage pending. Capacity growth copies old resident -data on device where supported; measure separately from ordinary delta bytes. -One camera turning must not repack/reupload every shared instance. - -### retained presentation - -Object, particle, environment and portal source changes invalidate scene pixels; -scene changes cascade to game composition, host composition and final image. -Game/host GUI changes begin at their own layer, never invalidate sibling source -geometry. An absent layer is `n/a`, not a cache hit. - -Keep retained game-GUI vertices, glyph atlas and ImGui draw geometry. Diagnostics -use their own refresh deadline and dirty rectangle; an updating counter cannot -force scene, texture or material cache misses. A cache hit owes zero work for -that layer: no upload, no command buffer and no transient allocation. - -Time-varying nodes declare time as input. A static sky may cache; moving clouds, -particle simulation, jittered temporal convergence and a visible video cannot -hide behind unchanged entity signatures. Freeze capture time explicitly. -Portal/history baselines advance only when those outputs were actually written. - -Tests cover scene reorder, entity deletion/reuse, empty lists, failed submit, -world unload/reload, camera create/remove, same-world many-view reuse and foreign -portal views. Check exact transfer ranges and traffic, not only a hit counter. - -### change-proportional preparation and bounded reuse - -Track topology/membership, transform, material, geometry, lights, environment and -simulation time separately through existing ECS mutation boundaries. Maintain -derived per-chunk/page revisions and changed-page lists; world summaries update -when those pages change, not by hashing every row for every camera. If current -write paths cannot guarantee notification, retain a conservative scan until the -mutation contract is covered, rather than trusting a new dirty bit prematurely. - -Publish immutable pages from the owning world, with leases/reference lifetimes; -reuse unchanged pages and copy changed pages only when concurrent readers require -it. Snapshot pages are a derived transport view, not another editable world. -Bound outstanding snapshots and recover from missed delta windows with one -explicit full refresh; do not accumulate a permanent revision history. - -Extract one world payload per published revision, then produce lightweight view -requests and GPU-selected lists. SIMD hot data should be contiguous bounds, -transforms and masks; cold authoring metadata stays outside these loops. Keep -task-local scratch and output ranges disjoint to avoid false sharing. A serial -path handles small inputs without queue overhead. - -GPU transform/bounds/material columns may have different update rates. Compare -48-byte interleaved rows against aligned hot/cold sidecars using bytes actually -fetched and dispatch cost; smaller source structs do not automatically mean -fewer device transactions. Keep previous transform/deformation only for demanded -motion consumers, preserving the previous presented sample rather than blindly -using the previous simulation tick. - -Per-view storage needs its own budget. A uint32 list for one million slots is -about 3.81 MiB before versions; duplicating several lists for every camera can -dominate world storage. Use compact candidate lists, visibility bitsets and -transient per-view scratch when lifetimes allow; retain only useful history, -never an unbounded camera-by-world matrix of full rows. - -Coalesce dirty transfers with a bounded gap threshold: extra copied bytes may -repay fewer copy commands. Compare exact spans, chunk uploads and a deliberate -full update at high dirty density. Report amplification, avoid reading dead -padding, and keep each in-flight destination version's acknowledgement distinct. - -Exact image reuse requires matching all relevant inputs. Reprojection, stale -shadow refresh and lower update rates are approximations with their own policy. -Do not hash floating-point camera matrices approximately and call it an exact -hit. A cached source can still need a final composite/present; attribute that -work to the consumer instead of declaring the whole frame cost zero. - -Separate upload acceptance, GPU completion and presentation success. An upload -submitted successfully can be acknowledged for that destination version while -presentation damage remains pending; storage cannot retire before completion. -This avoids reuploading valid data after an unrelated swapchain failure. - -| Change cause | Resident update | Recompute or invalidate | Keep reusable | -|---|---|---|---| -| Camera pose | View constants | View cull/LOD, shading, compatible temporal reprojection | World geometry/material rows and static asset acceleration | -| One rigid transform | Changed transform/bounds and required previous state | Affected visibility, shadows, instance acceleration and pixels | Mesh vertices, shader modules, unchanged materials | -| Material numeric override | Changed uniform range | Affected shading; alpha/displacement changes also invalidate geometry-related consumers | Unchanged descriptors/modules/pipelines | -| Pixels in an existing texture allocation | Dirty blocks/mips | Sampling-dependent pixels; alpha/displacement/shadow/trace consumers as declared | Binding descriptor and unrelated uniform data | -| Texture allocation or mip view replaced | New allocation plus descriptor generation | Consumers of that texture view | Module and compatible pipeline objects | -| Light change | Changed light data | Relevant clusters, shadows and radiance; conservative GI/path-history reset | Geometry/BVH and unchanged material bindings | -| Exposure or display grade | Small post parameter block | Display-domain post/composite output | Valid scene-linear HDR and geometry | -| Mesh topology | Affected packed geometry and bounds | Mesh acceleration, relevant shadows/culling/history | Other meshes and unrelated shader modules | -| Graph label/position | Authoring data only | Canvas region | All runtime plans, GPU objects and scene images | -| Shader interface/topology | New validated plan/module/bindings as required | Its dependent resources and pixels | Independently keyed compatible assets | - -This is an invalidation minimum, not permission to ignore hidden dependencies. -Custom nodes declare their reads and effects; unknown dependency scope falls back -to conservative invalidation until its narrower contract is proved. - -## 5. render correctness harness - -### fixtures and oracles - -Extend existing `[gpu]` tests using a real offscreen device. Each case declares -scene/world state, camera matrices, dimensions, graph, device tier, random seed, -tick/sample count, exposure and requested intermediate resources. A capture -manifest records backend/GPU/driver, build revision, shader hashes and settings. - -Provide one proposed `just render-check` entry with suite/filter/backend options, -wrapping the existing runner rather than inventing another test registry. -It must fail if a requested device cannot initialize. Ordinary CPU tests remain -device-free; missing hardware is reported as unverified, never image success. - -Use three independent oracles: analytic geometry/pixel probes, CPU reference -math, and reviewed image baselines. A screenshot copied from broken output is -not an oracle. Use full-image errors plus region masks and explicit pixel -assertions, so a tiny missing portal is not hidden by a mostly black image. - -| Test family | Inputs and observables | Failure it must catch | -|---|---|---| -| Projection | Axis triad, checker grid, known clip-space points, perspective/orthographic, oblique and mirrored cameras | Wrong handedness, upside-down image, half-pixel offset, aspect or near/far error | -| Depth | Ordered planes, near crossing, sky, linear-depth and HZB captures | Wrong depth convention, reduction direction or occlusion epsilon | -| Geometry | Winding, nonuniform/negative/zero scales, skinning, quantized mesh, displaced mesh | Culling, normal transform, bounds and decode disagreement | -| Resources | Read/write chain, alias pressure, viewport resize, history, pipeline replacement | Stale pixels, feedback, wrong owner, read-before-write and premature reuse | -| Colour | Linear ramps, known sRGB swatches, alpha wedges, HDR emitter and tonemap | Double conversion, gamma blending, clipped emission or premultiplication error | -| PBR | Roughness/metalness grid, each map, normal orientation, fixed light and environment | Broken BRDF, channel packing, missing map or inconsistent techniques | -| Selection | Per-object mask, per-camera feature override, multiple worlds | State leakage, widened cull set or incorrect capability merge | -| Temporal | Fixed seeded sequence, moving object/camera, resize/cut/portal crossing | Ghosting, stale history, wrong velocity or jitter reuse | -| Portals | Matched direct-view/through-portal geometry, lighting and scripted object/player crossing; angle sweeps and bus-delivered cross-world frames | Seam holes, wrong-side views, stale destination pixels, doubled bodies, camera-subject loss and clipping/light discontinuity | -| Lifetime | Repeated edit/reinstall/unload, failed admission, held frame | Leaks, invalid handles, loss of last valid image | - -Pin the existing zero-to-one clip depth and Y-up convention. Derive frusta from -the exact matrix used for rendering; do not negate projection Y independently -of SDL viewport handling. Include odd and non-square sizes, 1x1 targets, -zero-area outputs and near-plane-straddling boxes. - -Capture linear colour, depth, normal, material, velocity, entity ID, visibility, -LOD and final colour independently. Debug readbacks are opt-in and asynchronous; -fence completion, timeout and failure are explicit. Pad/read row strides and -format conversions correctly before comparing. - -Comparison policies are fixture-specific: exact integer IDs and canonical bytes; -bounded world/pixel error for projection and packing; absolute/relative linear -colour tolerance; bounded outlier count and RMSE for raster images. Stochastic -tracers use fixed seeds, samples, variance/confidence criteria and convergence -checks. Set thresholds from expected precision and baseline repeatability, -not by widening until a failure passes. - -On failure write input manifest, expected/actual/difference images, magnified -regions, numeric probes, graph/resource versions, validation errors and capture -receipts under the build output. Baseline changes are explicit reviewed edits, -never automatically accepted by CI. Test selection can be narrow locally; -release gates cover every supported backend and capability tier. - -### verification tools and commands - -Existing documented commands are `just test`, `just test-all`, -`just test --gpu-tests`, `just shader-check`, `just test-architecture`, -`just typecheck`, `just docs-check` and `just check-server-is-headless`. -`just edit --headless --frames 12 --run play --capture shot.bmp` is an existing -offscreen Studio capture path; it still uses a real GPU. - -New render fixture and benchmark recipes are proposed, not commands available -today. Add them with the harness, document arguments in RUNNING, and keep all -benchmark outputs under the configured build tree. Do not create loose benchmark -report files in the repository. - -During implementation, headless math tests run first. At final verification ask -for live Studio/browser/compute approval as the repository instructions require; -record any declined GPU/interactive checks. This document-only task runs none. - -### optimize verification without losing the oracle - -Reuse a device and immutable cooked fixture assets across ordinary cases; reset -world/view/history state between cases. Keep dedicated fresh-device tests for -initialization, loss and retirement so reuse cannot conceal lifecycle bugs. -Batch readback into a bounded fence-driven ring and compare/encode completed -captures off the render owner thread. - -Run routine probes on small fixtures, but retain full-size cases for odd extents, -packing, atlas bleed and allocation pressure. Optional GPU image reductions can -locate errors cheaply; they cannot be the sole oracle for shaders that may share -the same defect. Periodic CPU comparison and full failure artifacts remain. - -For each optimized path, compare against the unfused, uncached or conservative -path at identical scene state and declared quality. Stress invalidation by -changing one dependency and by removing/recreating its owner. Run captures with -and without aliasing so debug retention cannot accidentally hide a lifetime bug. -Measure performance in separate capture-free windows; readback and image encoding -must not pollute shipped-frame conclusions. - -## 6. capabilities and attached effects - -### separate support, policy and state - -`DeviceCaps` describes backend support and limits; reflected -`ShaderCapabilities` describes a module's stage, resources, formats, workgroups, -minimum buffer bytes and requirements. Authored render policy is a third thing, -not another driver capability record. - -Define world-lighting defaults, camera overrides and per-instance visual policy. -Use tri-state inherit/enable/disable fields for authoring, with stable names at -save/VM boundaries and packed bits in GPU rows. Resolve effective enablement as -authored policy constrained by pass support, device support and selected tier. -Neither a camera nor an instance can enable an unsupported device feature. - -Keep explicit default capability documents: Tier A uses deferred HDR, compute -HZB and optional AO; Tier B removes compute-only work and uses conservative CPU -selection plus supported raster effects; Tier C uses supported LDR/forward -formats while retaining bounded portal/mirror captures. Validate actual device -limits rather than treating tiers as a total hardware ranking. Numeric quality -uses parameters/divisors; fallback substitutions revalidate the whole document. - -Specify each feature's merge rule instead of one arbitrary bitwise OR. Examples: -cast/receive shadows, AO participation, lighting channels, emissive contribution, -reflection/refraction visibility, motion vectors, tracing visibility, culling -eligibility, two-sidedness, displacement and post selection. - -Camera-local visibility and quality apply only to that view. World shadow or GI -work shares results only if participating cameras request compatible inputs; -otherwise key distinct shared resources or make the work per-view. Publish the -resolved policy and refusal reason in Studio without reading back every row. - -### one attachment model - -An attachment contains stable graph/module reference, named entry/technique, -execution slot, selection mask, typed parameters, order, enabled state and -revision. Store authored attachments in ECS; pack active ranges/references into -GPU resident instance/emitter/environment/UI records. Shared modules compile -and reside once; instances change data, not shader variants. - -| Visual consumer | Allowed effect stages | Selection and bounds | -|---|---|---| -| Parts, mesh parts, editable/skinned meshes | Material shading, visual deformation compute, selected post | Stable instance/submesh ID; declared displacement envelope | -| Decals and surface textures | Material and selected composite | Surface mask and UV contract | -| Particles, beams and trails | Resident simulation/field compute, shading, selected post | Emitter/ribbon IDs; finite capacity and conservative bounds | -| Terrain/chunk output | Material, displacement and tile compute | Chunk/meshlet IDs and per-view LOD | -| Skybox, fog, atmosphere and clouds | Environment-generation compute, volume/render composite | World/camera scope and explicit output resources | -| Portal/mirror/surface camera | Capture graph and surface composite | View lineage, aperture mask, recursion and history identity | -| Game UI, text and image widgets | Declared UI material/composite | UI mask, premultiplied alpha, native-resolution text | -| Camera and global lighting | Fullscreen compute/post, lighting and GI graph | Explicit view/world scope and channel policy | - -Effects on selected objects need an ID/stencil/mask input. A fullscreen post -cannot infer its owning object from attachment metadata. Define whether its -neighbourhood may sample outside the mask and how it composites at edges. -Group identical programs into batches; never issue one fullscreen pass per item. - -Declare writes and bounded dispatch domain, time dependence, history use, -resource needs and invalidation. Compute deformation writes visual streams; -physics retains original geometry unless the author separately edits physical -geometry through its existing API. Recompute visual bounds or use a verified -conservative envelope before culling. - -Active demand drives shader, texture, sampler and pipeline residency. Hidden -attachments produce no preview work and no new loads; in-flight resources retire -safely and caches may retain bounded reusable entries. Activation is deterministic -from scene/view policy, never from profiling counters. - -### compile policy once, dispatch by useful work - -Resolve world/camera policy generations once, retain per-instance authored masks -in GPU rows and combine them with the active view policy in a small GPU operation. -A camera shadow toggle must not rewrite all world instances. Precompute compatible -technique/feature families at admission; specialize only when resource layout or -measured divergence justifies a variant, not for every bit combination. - -An attachment selector may produce a tile list, screen rectangle or instance list. -Run selected post effects only over covered tiles plus the filter's declared halo; -use conservative full-view work for unknown/global footprints. Overlapping -attachments with different order/parameters cannot merge merely because they -name the same shader. Keep sequential blending semantics within each batch. - -Compact active effect work on GPU, group compatible kernels and use indirect -dispatch when supported. Subgroup aggregation can reduce append-counter atomics, -but group size/subgroup width are probed and a portable prefix-sum path remains. -Use a fixed bounded launch with early exit where indirect dispatch is unavailable. -Do not read work counts back to decide whether the next GPU node runs. - -Conservative demand includes offscreen shadow casters, reflected objects and -portal/tracing consumers. Main-camera invisibility alone cannot unload their -shaders or stop required deformation. Classify memory as active, in-flight or -warm cached, and trim the last class under §14's device-wide budget. - -## 7. materials and shader publication - -### immutable definitions and sparse instances - -Keep distinct stable identities for material asset, material instance, shader -module family, texture asset and sampler preset. Layout and interface signatures -describe compatibility; they are not authoring names. Asset rename is an explicit -publication move with old-reference handling, not a silent new identity. - -A versioned material definition holds shader module and techniques, bounded -fallback references, canonical sorted declarations/defaults, texture roles, -samplers, static features, alpha/cutoff/two-sided/shadow policy, dependencies, -layout signature and optional labels/groups. Labels do not affect device layout. -Legacy AMT1 versions one through four and seven-map `.amat` records translate -into standard PBR parameters through one reader. - -Techniques have stable names for opaque, alpha-test, transparent, shadow, -depth-only and velocity consumption, plus declared tracing techniques. A pass -asks for a technique; the material resolves it or its fallback. Keep default -white plastic for an unassigned part, a distinct missing-content marker for a -bad reference, and consistent alpha cutoff in visible and shadow passes. - -A world material instance holds one published parent and sparse typed overrides, -plus authored revision. Published instance chains may have a small bounded depth; -resolve once, reject cycles/missing parents/unknown overrides/type mismatches, -flatten and cache by all parent roots plus override bytes/revision. No per-draw -inheritance walk and no copy of the immutable definition into every entity. - -Parameters are bool, signed/unsigned integer, finite float, float2/3/4, explicitly -linear RGB/RGBA, declared matrices, typed texture reference, normalized sampler -and closed enum token. Names/counts/default/override bytes are bounded; numeric -ranges and steps are declared. Canonical little-endian encoding, unique names -and refusal of unknown active types are required. - -Reflection supplies uniform offsets, sizes, alignment and descriptor bindings. -Validate its signature against the selected module before allocation; render -packs directly from canonical scene values. Large runtime arrays are separate -graph storage resources with their own schema/limits, not material parameters. - -### texture and sampler contracts - -Each binding declares semantic role, dimension (2D/array/cube/volume), channels, -sample type, colour space, swizzle, optionality, missing fallback, editable-image -permission and mip policy. ORM channel packing is explicit. Normalize normal -map handedness at cook where possible; do not infer it from filenames. - -Samplers specify min/mag/mip filters, wrap, anisotropy, comparison and LOD range. -Normalize and deduplicate the complete descriptor per device, with a hard cap. -Linear and nearest become built-in presets. Unsupported settings follow declared -fallbacks with a reason, not a silent materially different clamp. - -Editable-image revisions replace only the affected texture. Generated -`editable-image://` and `editable-mesh://` names remain local; publication bakes -ordinary assets and updates references transactionally. Pixel edits must not -compile shaders or invalidate unrelated uniform rows. - -### modules, interfaces and variants - -GLSL remains initial source. Metadata declares stage/entry, approved-root includes, -language version, static feature switches, specialization values, vertex or -fullscreen contract, fragment outputs, resources/access, material parameters, -requirements and fallback. Reject path escape, absolute/network includes, -symlink escape and excess include depth/expanded bytes; map diagnostics back to -original file and line. - -Keep material source fragment-only until a versioned public vertex/deformation -contract exists. Vertex work added for tessellation/deformation uses that contract, -not private `GpuInstance` layout. Fragment, vertex and compute modules all enter -the same publication path. - -Cooked bundles carry bounded variants, sorted feature keys, stage/entry, -optimized SPIR-V (initial existing target environment), supported MSL payload, -reflection, minimum binding sizes, capability requirements, optimization reports, -compiler/translator/ABI/container versions, dependency roots and payload hashes. -Prefer SPIR-V when the device supports both; carry backend form, file and entry -together. MSL uses `main0` where required and the existing SDL binding rules. - -Cook only variants demanded by materials/pipeline profiles and their fallbacks, -not the Cartesian product. Static layout/feature changes may compile; numeric -values, colours, samplers and textures remain data by default. Bound variants, -features, total bytes and device pipelines; report which asset demanded each. -Duplicate feature keys producing different bytes are deterministic-cook errors. - -Validate stage, set/binding, kind, access, dimension/format, local size and minimum -uniform/storage layout against the graph/material contract. Reflection instruction -mix (arithmetic, texture, memory, control) is a static estimate, not GPU cycles, -occupancy or runtime-sized resource bytes. - -### cook and trust chain - -Build an explicit sorted dependency DAG across material parents, textures, shader -includes/fallbacks, mesh submaterials, pipeline modules and capability profiles. -Reject cycles before work. Stages: discover -> bound/parse -> resolve -> demand -variants -> compile -> SPIR-V validate -> optimize -> reflect/match -> MSL translate --> independent shadercheck -> serialize -> ordinary manifest -> sign root once. - -Reuse existing BLAKE3-256 identity, deterministic chunks and signed manifest. -CDN serves bytes, holds no publisher signing key and interprets no shader policy. -Append new AssetKinds without renumbering existing kinds; unknown future kinds -retain the existing Unknown rule. Containers check magic/version, count, offsets, -overflow, strings, order and total bytes before allocation; no partial success. - -Independent compile jobs receive immutable inputs and separate output slots. -Gather/read first, fork bounded jobs, join, then publish sorted results. Compiler -workers need cancellation, time/memory/output/process limits and atomic writes. -Studio authoring jobs may span frames outside simulation; world tick work may not. - -Incremental keys include normalized source/include roots, stage/entry/features, -compiler/optimizer versions and flags, SPIR-V target, MSL translator/options, -interface/policy/ABI and capability profile. Verify cached outputs. Material -default edits avoid shader recompilation; texture pixel changes avoid unrelated -container or module rebuilds. Failed revisions cache diagnostics, never artifacts -that publication can mistake for valid output. - -Preserve explicit optimization reports: constant folding/specialization -propagation/simplification/dead-result cleanup, then local/module common-subexpression -and redundancy elimination, cleanup and ID compaction. Record before/after -instruction counts and whether each stage found work; preserve the entry-point -interface and validate optimized output. Cache these results with the module, -not in a separate Studio compiler path. - -Before migration, authored graph samplers follow read-slot order (set 2), pass -uniforms use the current GraphPassUniforms contract (set 3, binding 0), and compute -dispatch distinguishes explicit groups from cover-target dimensions. Freeze -these fixtures and translate them into named reflected interfaces; do not change -binding layout silently while replacing inline source with cooked references. - -### runtime admission and caches - -Selection order: requested technique/feature -> compatible cooked variants -> -preferred backend form -> authored technique/node fallback -> material fallback --> visible missing marker plus bounded diagnostic. Chains are cycle/depth checked -at cook and load. Equal caps yield equal selection regardless of hash iteration. - -Cache immutable parsed records by content root and reader version. Manifest swaps -create a resolution generation; old in-flight frames keep their consistent roots. -GPU keys include definition/parent roots, canonical overrides, technique/features, -layout/interface signatures, texture roots/editable revisions, sampler descriptors, -device identity/backend and packing ABI. - -Shader keys use module root, stage/entry, variant, device/backend and shader ABI; -graphics pipelines additionally include vertex -layout, formats, depth/blend/raster state, sample count and specializations; -compute keys include valid local sizes. Test each key field by varying it alone. -Do not rebuild shader objects merely because a texture-dependent material key changed. - -Separate budgets for parsed material/shader bytes, textures, uniform slabs, -observable shader bytes, pipeline/sampler counts, pending uploads and deferred -release. Evict least-recently-used unreferenced entries; retain in-flight data -until retirement. Oversized artifacts refuse before emptying unrelated caches. -Reason metrics are bounded names, not asset-derived metric keys. - -### Studio authoring and scripts - -Material editor widgets derive from declarations. Preview standard meshes, lights, -backgrounds, exposure and capability tiers through the real pipeline. Shader editor -shows line errors, reflected interface, optimization deltas, variants, fallbacks -and active-versus-attempted revision. Undo/redo and debounced/manual preview submit -the same cook request; hidden tabs submit no preview work. - -Requests carry immutable sources, dependency roots, profiles and revision. -Worker returns owned bytes/errors/timing/request identity; discard stale results. -Admit successful results on the render owner at a frame boundary and retire old -objects after GPU completion. Invalid source retains the last accepted preview. - -Luau and JavaScript use the same scene methods for get/set/clear overrides, -typed declaration queries, texture assignment, sparse cloning, revisions and -diagnostic selection. Validate type/range/enum/dimension/authority before mutation; -invalid calls change nothing. Generate VM/docs metadata from one schema; generic -parameter names stay data. Cross-VM fixtures compare values and errors. - -Studio/trusted authoring may edit ShaderScript source and request cook tickets. -Packaged games select published modules and bounded feature values; they cannot -submit source, arbitrary SPIR-V/MSL, includes or descriptor layouts. Studio saves -may preserve source; package cooking must resolve every runtime demand first. - -### split cache dependencies and admission work - -Treat the complete material key above as a resolved-view identity, then cache its -parts independently. Uniform packing depends on layout and canonical values; -texture descriptors depend on texture allocation generation/mip view and sampler; -shader modules depend on cooked code; pipelines depend on immutable render state. -A texture pixel update in the same allocation changes content without forcing -new descriptors, uniform packing or pipeline creation. - -Intern immutable resolved parameter blocks by canonical content, not merely a -monotonic edit revision, so repeated equal overrides share device data. Keep -per-instance identity/revision separately for save/notification semantics. -Upload changed uniform ranges into aligned slabs; avoid one buffer allocation -per material. Direct uniform bindings remain preferable at small scale if -slab indirection costs more than it saves. - -Share one in-flight parse/cook/load request per complete content key. Batch -variant work by common preprocessed source where the compiler safely supports -it; cap compiler processes by memory as well as core count. Dependency-root -changes invalidate only their downstream variants; unsuccessful identical edits -reuse bounded diagnostics instead of retrying every frame. - -Prewarm demanded pipelines during load/authoring admission in a bounded queue. -If device pipeline creation must occur on the owner thread, time-budget it there; -a worker cooking shader bytes does not remove driver pipeline-creation hitches. -Use backend pipeline-cache persistence only where exposed, with device/driver/ -ABI keys and safe cache-miss behavior. Warm and cold timings are separate gates. - -Keep fast-preview and final optimized cook profiles explicitly keyed and visible -if a fast profile is introduced. Both validate interfaces; packaging never ships -an attempted preview artifact by accident. LRU retirement batches resources by -completed frame generation and bounds warm caches after editors close. - -## 8. compositor and visual shader workbench - -Use the existing canvas, `render.pass.` types and typed wire families. -Keep resource bindings and hidden metadata losslessly through load/save; final -save validation runs Build/CompileSchedule and interface checks. Engine executes -the compiled graph, never the canvas evaluator. - -### visual-compositor contract - -The compositor is a typed resource graph with separate authoring and execution -representations. Unity's Scriptable Render Pipeline separation of pipeline -configuration from execution, and its Visual Compositor families, are the -references for this boundary. This engine keeps its own stable names, scopes, -ordered resource versions, and device-neutral graph runtime. - -Every compositor node declares its stable kind, scope, queue, typed input and -output ports, required capability set, fallback, and lifetime or history policy. -A wire binds one declared graph resource from an output port to an input port. -The compiler rejects incompatible resource kinds, duplicate writers, reads with -no preceding writer, and scopes that would consume a resource before its -producer runs. Canvas position, groups, comments, mute state, and preview -selection remain authoring metadata and cannot change runtime work. - -Preparation nodes make residency and compact deltas visible dependencies. -`mesh-residency` runs before a view consumes resident ranges, and -`delta-upload` consumes those ranges plus the selected entities before it -publishes instance data. Both record on the frame command buffer. No caller may -submit a mesh-residency transfer beside the graph, because that creates an -untracked ordering path and lets a draw race a newly resolved range. - -Compositor nodes manipulate images, buffers, and selections. Material nodes -lower to bounded shader source and use the existing shader cook path. A node -kind ships only with its schema, backend or explicit fallback, capability -requirements, lifetime policy, help, and a fixture that exercises its declared -ports. The catalogue and default documents are the executable part of this -contract; the canvas discovers from them rather than maintaining a second list. - -Unity separates pipeline configuration assets from execution and exposes visual -compositor image, value, selection and organization nodes. Use that separation -and discoverable palette as references, while retaining this engine's scopes and -ordered resource versions. [SRP fundamentals](https://docs.unity3d.com/Manual/scriptable-render-pipeline-introduction.html), -[visual compositor nodes](https://docs.unity3d.com/Packages/com.unity.visual-compositor@0.27/manual/nodes.html). - -Build Blender-like authoring conveniences over the same contracts: reusable -subgraphs with typed exposed sockets, material-node groups, reroutes, frames and -comments, searchable palette, duplicate/paste, undo/redo, node mute/bypass with -defined type behavior, channel inspection and a selected-output viewer. -No engine execution depends on canvas coordinates or folder layout. - -| Node family | Required nodes and contracts | -|---|---| -| Inputs | World, camera, entity selection, light camera, texture/constant, history, scene depth/normal/velocity/ID | -| Selection | Frustum/distance/tag/channel filters, set union/intersection/difference, deterministic draw order | -| Preparation | Residency plan, delta upload, material resolve, particle step, deformation, bounds, LOD, indirect build | -| Capture/draw | Shadow/cascade/cube, depth, G-buffer, forward opaque/masked/transparent, portal/mirror, authored raster | -| Compute/light | Dispatch, light clusters, HZB/cull, AO, GI, environment generation, hybrid raytrace, path trace | -| Image math | Add/subtract/multiply/divide, min/max, mix/over, masks, threshold, clamp, separate/combine, explicit conversion | -| Spatial filters | Blur/bilateral, dilate/erode, edges, scale/crop/transform, reduce chain, mip generation, upscale | -| Post | Exposure/histogram, bloom, tone/grade/LUT, DOF, motion blur, SSR, AA, sharpen, palette, hatch | -| Outputs | Image, viewer, one-shot/sequence capture, game interface, host interface, diagnostic overlay, present | -| Material graph | Typed constants/parameters, texture sampling/swizzle, math, normal mapping, PBR/unlit/toon/emission closures | - -Material graphs lower to bounded shader source and cook through §7, not to -independent draw-pass callbacks. Compositor nodes manipulate declared images, -buffers and selections. Keep these domains visibly distinct while sharing UI -primitives and parameter schemas. - -Each shipped kind needs a working backend/default shader, schema, capability -requirements, fallback, lifetime/signature policy, test fixture and node help. -A catalogue entry alone is not completion. Preview requested outputs only; -retain unchanged previews and stop work when hidden. Show pending/error state -without an always-repainting spinner. - -Inspector tools show input/output dimensions, colour/alpha space, resource version, -owner, lifetime, allocation alias, selected shader/tier, timings and capture. -Report missing writes, dead resources/nodes, wasted writes, disconnected nodes, -out-of-order effects, overspent formats, unused alpha and feedback. Pixel-dependent -constant-channel/uniform-target/shading-count diagnoses require explicit readback -or instrumentation; do not infer them from graph topology. - -### incremental authoring and selective materialization - -Cache canvas layout, text measurements and wire geometry by affected nodes and -viewport transform; virtualize offscreen nodes and large property lists. A -selected thumbnail consumes an existing GPU image directly when possible. -Do not read pixels back merely to display them in Studio. - -Separate the authored graph from its execution representation. Constant-fold -pure value expressions and share identical pure shader expressions; lower a -compatible chain of pointwise material/image operations into one cooked kernel -only after measuring bandwidth savings against register pressure. This is -compiler-generated fusion, not arbitrary source-string concatenation. - -Do not fuse across incompatible dimensions, colour/alpha conversion semantics, -history, side effects or neighbourhood dependencies without a proved transform. -Preserve rounding/error policy; a removed intermediate format conversion can -change the result. A debug viewer pins a logical intermediate and can request -an unfused or explicitly materialized variant with its extra cost labelled. - -Use GPU tile-local/shared-memory kernels for suitable separable filters after -comparison with ordinary raster passes. Full-screen compute is not automatically -faster on tile GPUs. Cache static subgraph outputs only when their update rate -and memory cost justify it; moving a graph node or opening help creates no new -render work. Profile the editor's own idle cost as well as preview GPU time. - -## 9. lighting, shadows and visibility - -### PBR and indirect light - -Standard PBR has linear base colour, metalness, roughness, tangent-space normal, -occlusion, height and emissive inputs with explicit defaults. Define a shared -BRDF contract for deferred, forward, shadow/depth alpha, velocity and tracer -techniques. Roughness remapping, normal normalization, tangent handedness, -two-sided behavior and emission units cannot differ silently between passes. - -Use a documented microfacet specular model, diffuse energy allocation and bounded -roughness. Test reciprocity/finite output where applicable, a white-furnace -energy fixture, metal/dielectric endpoints, grazing angles and nonuniform scale. -HDR emissive radiance cannot remain limited by the legacy packed colour/strength -range; supply a versioned material value or HDR sidecar and test bright emission. - -Dynamic AO gets a node taking depth, normals, camera and optional motion history. -Provide radius/bias/quality, bilateral filtering and depth-aware upsample. Apply -AO to intended indirect terms, not as an unexplained dark multiplier on emission -and all direct light. Bake AO remains a separate material input. - -GI nodes expose irradiance/radiance, confidence, update policy and history. -Provide environment/probe lighting as baseline, a measured screen-space indirect -option with offscreen fallback, and trace-derived indirect light from §11. -Do not call SSAO or SSR full GI. Emissive GI must reach nearby receivers, not -only bloom around the emitter's own pixels. - -### shadow work, all preserved candidates - -| Work | Algorithm and initial experiment settings | Gate and tradeoff | -|---|---|---| -| Cascades | 1 to 4 directional levels; exponential far bounds `firstFar * pow(maxDistance/firstFar, i/(N-1))`, with N=1 handled separately; compare practical log/uniform blends; initial 10m/150m/2048 settings are tunable | Fit each camera slice in light space; expanded caster frusta retain offscreen casters; test split transitions and light rotation | -| Stable fit | Rotation-only light basis; sphere/body-or-far-diagonal extent, quantized scale and snapped light-space centre | Never assume an integer extent makes world texels powers of two. Prove stationary geometry has stable shadow pixels during camera motion | -| Cascade blend | Overlap band, initial 0.2 fraction; fade to lit beyond maximum | No visible boundaries; sample derivative-sensitive comparison operations safely before divergent weighting | -| Filter menu | Hardware 2x2 PCF; normalized bilinear-weighted 9-tap Gaussian; 8 rotated spiral taps; optional PCSS blocker search plus filter | Explicit comparison sampler support, temporal seed and light size; quality/per-pass timing capture | -| PCSS correctness | Compute blocker/receiver separation in declared light-space distance; derive penumbra under that convention | Do not copy the old sign-sensitive depth formula across normal/reverse depth; receiver/blocker fixtures pin contact and growing penumbra | -| Bias | Raster slope bias plus receiver-normal offset proportional to world texel width per cascade/resolution | Test acne, contact gaps and peter-panning separately; fit enough depth for casters behind the eye | -| Point shadows | Cube/6-layer array, 90-degree faces, near/far and depth convention explicit; tangent-basis filter directions | Cap active lights/faces and refresh work; test face seams and near singularities; reverse-Z is a capability/contract change, not an isolated shader edit | -| Update budget | Near dynamic levels every frame; stagger coarse refresh, bounded age, footprint-based invalidation | Publish last successfully rendered centres, not desired centres; moving sun/caster invalidation and failure retry | -| Arrays/atlas | Start fixed layers; optional shelf/bin-packed tiles with padding and shared viewport/scissor/sample/clear rectangle | Atlas only after measured layer waste; border filtering and tile reuse tests | - -World-shared shadows can share scene/caster data, but camera-fitted cascades -need a camera-set key or per-view fit. Budget and cache keys include light state, -caster revisions, material alpha, visual deformation and portal lighting state. - -### clustered lighting - -Implement a `light-cluster` node used by deferred and transparent/forward passes. -Initial 16x9x24 grid and logarithmic depth slices are test settings, not fixed -quality. Store bounded per-cluster offsets/counts plus flat point/spot index lists; -validate packed-bit capacity before writing. Keep distant-light handling explicit -when cluster far distance is below camera far. - -Frustum-cull lights first. Begin conservative sphere/AABB and cone/plane tests, -then compare tighter Z/Y/X sphere slice refinement and optional convex-volume -raster assignment. Tight assignment earns adoption only if reduced shaded lights -repay extra ALU. Overflow must trigger a correct slow path or declared fallback, -with debug visualization and counters; never silently drop lighting. - -### bounding boxes before finer culling - -Shared resident bounds feed per-view frustum/distance/box rejection. Invalid, -near-plane-straddling, newly spawned, teleported or unknown bounds stay visible. -Visual displacement and skinning expand/recompute bounds before culling. - -Keep the two-phase HZB path: conservative early occluders -> depth -> farthest -depth reduction under the chosen depth convention -> remaining box tests -> -compacted visible/indirect output. Temporal visibility is a hint, never permission -to erase a newly revealed object. Bounded counters and prefix sums cannot overflow. - -Harden odd/non-power-of-two reductions, per-candidate mip choice, footprint -sampling and epsilon, camera cuts, resized targets and occluder deletion. Compare -SPDs or other reduction kernels against exact conservative CPU pyramids before -adoption. Validate shadow-view occlusion separately using light-view depth. -Record candidates, early/late survivors, fallback count and final drawn count. - -GPU indirect work bins by compatible pipeline/material binding/index type and -pass; reset counters, cull, compact, generate arguments and draw. Stable output -is required where order affects blending/replay captures. Native multidraw/count -support is probed; fallback can issue bounded individual indirect draws or use -CPU-built arguments without pretending the unsupported feature ran. - -Preserve CPU software occluders as a measured candidate: curated conservative -proxies, front-to-back SIMD masked rasterization, tiled depth/coverage (8x4 as an -experiment), interleaved queries and disjoint screen-region jobs. It belongs in -a graph CPU preparation node and must match the safe visibility direction. -Use only where CPU headroom and scene structure justify it. - -### spend lighting and visibility work where it pays - -Demand-drive G-buffer channels and lighting inputs. Reconstruct position from -depth where the projection contract permits, rather than always storing world -position; compact normals and material channels only within measured error. -Compare deferred and forward/clustered graphs for bandwidth, light count and -transparency. An optimized default can select a different supported graph by -measured device/workload profile without maintaining a second material system. - -Cache environment convolution, BRDF lookup data and static probe inputs by -environment/material model versions. Light clusters depend on light buffers, -camera, grid and optional depth occupancy; share only equal dependencies. -Use count -> prefix sum -> fill for bounded compact cluster lists where this -beats fixed-capacity arrays. Depth-occupied clusters for opaque shading cannot -exclude transparent surfaces in otherwise empty depth slices. - -Maintain conservative spatial summaries for shadow invalidation. A moving caster -invalidates its old and new footprints; alpha/material/deformation edits also -invalidate shadow content. Consider static/dynamic caster separation only when -depth composition reproduces the correct nearest occluder and moving/static -transitions cannot leave stale shadows. Fewer rendered tiles must show lower -full-frame cost, including tracking and composition. - -For AO/GI, retain only history with valid depth/normal/material evidence; use -half-resolution or checkerboard updates as explicitly approximate modes with -disocclusion fallbacks. Probe/irradiance caches separate visibility, geometry and -radiance epochs so a light edit can relight without rebuilding geometry. Local -GI invalidation needs conservative transport influence; indirect light can travel -beyond the changed object's screen rectangle, so global reset remains fallback. - -Culling has a cost crossover. On an empty/low-occlusion scene, HZB construction, -testing and compaction may cost more than the draws removed. Compare enabled and -disabled graphs at fixed quality; select a deterministic configured policy, not -live profiler counters. Cheap frustum/distance rejection precedes HZB, while -large reliable occluders earn early-depth work by projected area and cost. - -Separate small primitive tests from expensive fine culling. Reuse hierarchy bounds -and update affected ancestors; compact survivors with workgroup-local prefixes -before global reservation. Do not run shadow fine culling from an eye-depth -pyramid. Keep order-independent opaque batching separate from transparency, -where material sorting cannot override the required compositing order. - -## 10. colour, post and antialiasing - -### one colour and temporal contract - -Decode sRGB colour textures at sampling; normals, roughness, depth and masks stay -linear data. Lighting, emission, transparency, portal/mirror captures and bloom -compose in linear HDR. Tone map the completed scene once, then encode for output. -UI composition states whether it occurs in linear display space or a documented -presentation path; text remains native resolution. - -The old default tone-mapped captures before overlay and drew transparency after -scene tonemap. Extraction preserves baseline first; replace that ordering with -HDR-compatible surface/transparent composition and explicit exposure ownership. -Per-camera effects can differ, but a physical portal cannot silently apply both -its destination camera's tonemap and the viewing camera's tonemap. - -Resource descriptors carry straight/premultiplied alpha. Blend, over, blur, -resize and texture edges respect it; conversion is explicit. Colour-space and -normal-map mip generation use semantic filters, not one byte-space average. - -Velocity uses previous/current transforms, deformation and camera matrices with -defined jitter treatment. Temporal resources key world/view generation, camera, -extent, projection, pipeline, shader/material epoch and portal lineage. Reset -after cuts, resize, new content or incompatible policy; disocclusion uses -depth/normal/ID rejection, neighbourhood clamps and a reactive mask. - -### AA menu - -| Choice | Required work | Proof/fallback | -|---|---|---| -| None | Direct resolve with no history | Reference image for other modes | -| MSAA | Supported sample-count targets, matching raster state, explicit colour/depth resolve and deferred edge treatment | Probe sample/format support; reject unsupported combinations; exercise alpha-test and thin geometry | -| FXAA | Luma/edge fullscreen pass after appropriate scene conversion | Edge fixtures, text excluded from blur; cheap spatial fallback | -| SMAA | Edge, blend-weight and resolve nodes with required lookup resources | Test diagonal/subpixel edges and actual three-pass resources | -| TAA | Jitter, velocities, depth/history, rejection/clamp and accumulation | Static convergence, camera/object motion, thin foliage, emissive reactive mask and cuts | -| Temporal upscale | Low-resolution scene plus high-resolution history/reconstruction and optional sharpen | Independent project-sized node group; dynamic-resolution/cut tests; UI at output resolution | - -Mode selection replaces a typed subgraph. No mode can reuse history with another -mode's interpretation. Capability profiles explicitly choose spatial fallback; -quality does not fork an untracked hardcoded renderer. - -### post nodes and measured cost - -Bloom uses down/up pyramids, optional 13-tap downsample and first-level Karis -weighting, tent upsample and HDR additive composition. Specify minimum mip extent -and maximum chain length from quality; the old note's 512-pixel hint is an -experiment, not a universal smallest-level rule. Verify energy and bright emitters. - -Exposure consumes a bounded histogram/reduction with explicit adaptation clock. -Grade/tonemap can use a baked 3D LUT with declared domain, interpolation, gamut -and exposure placement. Compare LUT output with analytic curves and record the -error; dynamic exposure cannot be hidden in a stale baked LUT. - -DOF consumes linear depth and lens parameters; motion blur consumes velocities; -SSR consumes depth/normal/roughness/HDR and falls back for offscreen misses. -Half/quarter-resolution AO, fog and bloom use depth-aware or appropriate -upsampling. Every enabled node has a complete shader, input contract and image -test; a placeholder catalogue default is a failed implementation gate. - -### minimize full-image traffic and history churn - -Construct only the attachment set demanded by the selected post/AA graph. No -motion blur/TAA/temporal upscale consumer means no velocity target or retained -velocity history solely for those features. No alpha consumer can permit a -compact HDR format, but a resource shared with transparency must retain alpha. -Channel liveness is a compiler fact checked against actual shader reflection. - -Keep bloom reductions, exposure and other compatible reductions on shared -intermediates only when their colour domain/filter semantics agree. Fuse -pointwise grade/tonemap/output operations under §8's rules; preserve nonlinear -ordering and explicit conversions. Reuse pooled target size classes with bounded -hysteresis instead of reallocating on every viewport pixel change. - -Prefer inline MSAA resolve and avoid storing multisample attachments whose only -consumer is the resolve, when the backend supports that path. A later depth or -sample-frequency consumer changes this decision. Treat memoryless attachments -and subpass features as backend options, not portable SDL guarantees. -[Khronos MSAA sample](https://github.com/KhronosGroup/Vulkan-Samples/blob/main/samples/performance/msaa/README.adoc). - -Temporal history validity is finer than resetting on every ordinary camera move: -TAA reprojects expected camera/object motion, rejects disoccluded pixels and -resets on cuts or incompatible contracts. Exact offline path accumulation in -§11 instead restarts when its sampled scene/camera changes. Keep both policies -explicit; a universal global history epoch would either smear images or destroy -temporal reuse. - -Cache source layers separately from post state. Exposure/grade edits can reuse -valid scene HDR but still change all display pixels; neighbourhood filters expand -damage by their support, and global reductions invalidate their global dependents. -Partial redraw is enabled only with conservative damage and known full coverage; -otherwise recompute the affected full-view stages. - -Dynamic resolution is an optional declared controller with bounded scales, -hysteresis and frame-boundary decisions, not a timing-driven branch inside -shaders. Because current metrics are reporting-only, default plans use configured -quality; any adaptive control needs its own reviewed policy/input rather than -reading profiler counters. Record resolution in every comparison. - -## 11. tracing and global illumination nodes - -### port boundary - -First inventory the prior semi-real raytrace/path-trace code and fixtures in the -working tree and available history. Port useful algorithms into node handlers -and shared material contracts; retire their old orchestration. If there is no -usable prior implementation, build the missing node rather than calling a named -catalogue entry a port. Record provenance and any retained licences. - -Define semi-real raytrace concretely as hybrid rendering: raster primary depth, -normal and material plus real secondary ray intersections for reflections, -shadows and bounded indirect lighting. SSR may be a fast candidate/miss fallback, -but rays must hit valid offscreen geometry in the demo. - -Compute tracing provides a portable baseline using a bounded acceleration -structure over resident geometry. Mesh-local static BVHs can be cooked; instance -acceleration updates/refits on transform changes; editable/topology changes -rebuild only affected structures. GPU visual deformation must update traced -geometry/bounds or declare an explicit nonparticipating fallback. - -Nodes: `trace-geometry`, `trace-acceleration`, `ray-generate`, `trace-hybrid`, -`trace-path`, `trace-accumulate`, `trace-denoise`, `trace-composite`. Names are -proposed schema IDs. Separate world geometry work from per-view ray/history work; -do not rebuild or reupload the same world BVH per camera. - -Hardware ray queries/pipelines require backend implementation, capability probes, -shader forms and parity tests. Compute/no-compute fallback is visible in the -selected pipeline report. No vendor-only requirement silently becomes baseline. - -### path transport contract - -Progressive path tracing samples camera rays, intersects actual triangles, -evaluates the same material parameters, samples lights and BSDFs with explicit -PDFs, accumulates throughput/radiance and terminates with a bounded bounce cap -and controlled Russian roulette. Include emission, environment, alpha policy, -shadow visibility and diffuse/specular transport; state whether transmission is -supported for each technique. Use multiple importance sampling for direct-light -and BSDF sampling to reduce variance. [Path-tracer reference](https://pbr-book.org/4ed/Light_Transport_I_Surface_Reflection/A_Better_Path_Tracer). - -Use robust origin offsets, conservative traversal, finite-value guards, bounded -stack/queue sizes and overflow fallbacks. Seeds depend on view/pixel/sample and -purpose, not scheduling order. Separate accumulation count, moments and denoised -display; denoising cannot overwrite the raw convergence evidence. - -Reset history on camera/projection/extent changes, scene/material/light revisions, -deformation/topology changes and relevant portal updates. A frozen interactive -preview may continue samples; a hidden preview stops. Resource/iteration budgets -are declared settings, not a driver timeout assumption. - -Ray masks and per-instance capability bits live in GPU rows. Portal rays transform -origin/direction and carry bounded lineage; physical transport, lighting and -recursion rules agree with §12. If a material/volume cannot be traced, report its -technique fallback instead of silently disappearing. - -Proof includes ray-box/triangle degeneracies, BVH versus brute-force intersections, -offscreen reflection, shadow visibility, mirror/diffuse/emissive scenes, fixed-seed -repeatability, statistical convergence across increasing sample budgets and -invalidation after one edit. Individual stochastic estimates need not improve -monotonically; compare error distributions against the reference. -CPU references test tiny scenes; real GPU output proves shader traversal and packing. - -### resident acceleration and efficient ray work - -Separate mesh geometry acceleration from world instance acceleration. Rigid -instances share one mesh BVH; transform edits refit/update only instance bounds. -Topology edits rebuild that mesh, and deformation refits or rebuilds according -to measured traversal quality. Retain a conservative build/refit fallback when -refit quality degrades; double-buffer replacement structures only under a bounded -memory allowance, not a second permanent copy of every world. - -Store traversal bounds/child references in contiguous compact arrays; geometry, -material payload and textures are fetched on demand after a hit. Quantized BVH -bounds round outward and are tested against brute-force visibility. Share cooked -static geometry across worlds at the device asset layer while keeping world -instances and temporal history separate. - -Compare a simple kernel with a wavefront implementation: resident SoA queues for -intersection, material/light evaluation, shadow rays and continuation. Queue -compaction and grouping can improve coherence but add dispatches and memory -traffic; keep the simple path for workloads where they lose. -[GPU path-tracing tradeoffs](https://www.pbr-book.org/4ed/Wavefront_Rendering_on_GPUs/Mapping_Path_Tracing_to_the_GPU). - -Chunk ray work into bounded tiles/sample batches; use indirect counts or bounded -launches without per-bounce CPU count readback. One sample's continuation/emission -ownership is explicit, so batching and overflow handling cannot double-count or -drop radiance. Flush/retry smaller batches on capacity limits; shading order must -not change sample seeds or silently change PDFs. - -Cache light sampling distributions and environment importance maps by content and -light epochs. Classify hybrid tiles by roughness/material/ray mask before launching -expensive rays. Ray-length/sample reductions and denoise reuse are quality modes, -not equivalent-execution speedups. Adaptive sampling uses minimum samples and -variance/confidence policy; raw equal-sample comparisons remain the baseline. - -Accumulate in GPU memory with sufficient radiance/moment precision, and allocate -history only for active views. Stable completed preview tiles may sleep under an -explicit convergence target; changes wake/reset affected state conservatively. -Geometry/material/light changes default to full radiance reset because transport -can affect remote pixels. Reservoir reuse or radiance-cache research may follow -only with estimator/visibility validation, not as an assumed free improvement. - -Tune workgroup shape/register/shared-memory footprint per supported backend -profile; fewer instructions or higher occupancy alone is not the objective. -Measure queue bytes, active ray counts, traversal cost and full-frame latency at -equal sample quality, including BVH maintenance and denoising. - -## 12. portals with one seam contract - -### transform, projection and geometry - -Define a rigid seam transform from entrance frame, the engine's facing-turn -convention, and destination frame. One pure function supplies camera, points, -directions, normals, velocity and ray mapping. Test forward/inverse round trips; -mirror handedness is a separate operation. Initially reject non-rigid/unequal -scale pairings unless scale physics and projection are explicitly designed. - -Resolve portal cameras through scene camera math. Clip to the destination plane -with the correct zero-to-one oblique projection or explicit clipping contract; -clip the entrance aperture using a common polygon/mask. Test edge-on views, -camera on the plane, near-plane crossings, nested panes, backfaces and mirrored -winding. The surface must not show geometry from behind its exit wall. - -The aperture behaves like an opening into the destination from every supported -viewpoint. Sweep azimuth, elevation and roll on both sides, at grazing angles, -from off-centre positions and across the plane. Include portals larger than the -near plane and entrances partially outside the viewport. Match the unfolded -direct-view reference inside the aperture and the local scene outside it; a -centred, front-facing screenshot cannot satisfy this gate. A two-sided portal -must resolve the correct destination side rather than mirror, blank or reuse -the front-side camera. Any intentionally one-sided authored portal declares -that behavior separately and cannot stand in for the seamless two-sided demo. - -A body straddling the seam draws clipped source and transformed destination -proxies from the same stable entity identity and authoritative transform. -Both halves share material/skinning/deformation, normal basis, lighting inputs, -shadow policy and motion history. Do not duplicate uncut geometry or rebuild -physical ownership merely to show its far half. - -Recursion is a bounded view graph with stable world/view lineage. Render deepest -required captures before consumers; cycles use the last valid history with a -visible diagnostic when exhausted. Bound depth, total views, pixels, memory and -per-frame work, and invalidate history when either portal or destination changes. -Missing/deleted destinations preserve the established mirror fallback where -applicable, with an explicit status rather than undefined memory. - -### light transport and composition - -Portal and mirror captures use the same PBR/material/colour pipeline as the scene. -Carry the destination environment and light state through the view contract; -avoid tinting the physical portal by a default grey pane or double exposure. -Composition uses proper depth/aperture coverage and HDR colour before tonemap. - -Cross-seam lighting needs a generic portal-light transport node, not just a camera -picture. Clip transported light influence to aperture geometry, transform light -direction/position, account for both-side shadow blockers and cap light-path -recursion. Trace paths follow the same seam mapping. A light crossing the portal -must not double its energy or vanish at the plane. - -Test source and destination light configurations, offscreen casters, alpha-test -casters, emissive objects, moving lights, shadow bias and exposure. Keep a direct -unfolded reference scene to compare with the equivalent portal scene. - -### physics and world ownership - -Detect swept crossing against the aperture, not only a sign flip at frame end. -Map position/orientation, linear/angular velocity and remaining movement through -the seam at a deterministic world barrier. Prevent immediate reentry using -oriented crossing state with a finite separation rule; a time-only cooldown must -not trap slow bodies or miss fast crossings. - -During overlap, collision queries against the far side transform into the other -space and return owned contacts/constraints to the authoritative solver. Proxies -are query shapes, not independent simulated bodies. Define contact normal, -impulse, inertia, gravity-frame and constraint behavior across the seam; chains, -ragdolls and compound bodies require whole-island or explicitly constrained -transfer, never silently broken joints. - -Same-world portals retain one entity/body owner. Cross-world transit is a named, -versioned transfer payload, accepted once at coordinated barriers. No ECS handles -or pointers cross worlds; requests include stable identity/generation and tick. -Destination absence or rejected transfer retains valid source ownership and -collision. Acknowledgement prevents duplicate removal or double spawn. - -Portal physics math belongs in scene/collision/physics/world at legal layers, -not render. GPU-only visual displacement changes neither collision nor transit -authority. Multiplayer tests cover ownership transfer, rollback/replay inputs, -stale destination, simultaneous bodies and high-speed tunnelling. - -### player cameras and cross-world images - -Exercise the actual player character path with `CameraSubject` set to its -`Humanoid`. Move the complete character through the aperture, including body, -attachments, animation and locally controlled ownership. Preserve the subject -relationship by stable identity when the destination creates new ECS handles. -Transform camera pose, look direction, follow/orbit offset and remaining camera -motion at the same accepted crossing boundary. First-person and third-person -cameras must not snap to an old world, detach from the subject or interpolate -through the space between worlds. Camera obstruction queries must follow the -same seam and use the correct world's collision space. A free camera crossing -alone does not prove the player-camera behavior. - -Track the eye's world separately from the body's authority and replica session. -The eye can cross during transfer preparation, or trail behind the transferred -body on a third-person arm. Select the named presentation endpoint from that eye -path and map the complete view through its seams. Keep the Humanoid subject and -input attached to the accepted body. A session acknowledgement alone must not -switch the visible room. Retain only the required bounded presentation state -until the eye leaves; do not keep a second authoritative body or copy a whole -destination scene into the source world. Identify the receiving mouth explicitly -so its pane cannot occlude its own incoming capture. Preserve unrelated surfaces. - -First-person body exclusion belongs to the primary eye's visibility selection. -Keep the rig available to shadow, mirror and portal child views, including its -clipped seam copies. Resolve the viewer through the accepted player/transfer -identity; a held camera root can be detached from Workspace, so its current full -path is not sufficient identity for the remote producer. Resolve a new selection -when the subject changes; clear it for a scriptable camera or missing Humanoid. -Carry bounded named identity in whole-eye requests and resolve local handles at -the destination. Child seam requests must not inherit the primary-eye exclusion. -Copied geometry carries its account identity as bounded canonical text. Keep -request-local selected row indices separate from scene storage, and remap only -those indices when unavailable meshes are filtered. Preserve retained visuals -when source entities retire; use the held character's exact source root for -ownership, never a diagnostic path or coincident handle from another world. -Client now supplies source presentation rows to the shared whole-eye host, which -maps direct crossing geometry into the requested eye world. Extend this to the -Studio caller, remote child captures and destination-adoption deduplication. A manually supplied -geometry fixture proves transport selection but does not close product crossing. -While the source character hold is active, Client uses an available source eye -image instead of drawing the retired replica's empty body rows. Product capture -checks require the third-person avatar throughout the source-owned walk and at -adoption. Captures expose gaps both when prediction clears the mouth before -authority transfers and while remote body rows and replacement images arrive. -Continue the body's mapped presentation through both intervals, including -nested captures and connection replacement, before claiming visual continuity. - -Client now tracks the presented root crossing a fitted mouth and continues its -far-side geometry after the root fully clears the plane. This local history -ends on return, unheld root retirement or changed mouth geometry, and resets on snapshot -load. A held camera now retains bounded body rows and skin palettes, carrying -the last pose with its predicted root after retirement. Source-world eye requests -carry the live or held local body into the producer, and incoming copies forward -into child requests. Import replaces native body rows with matching account -identity before rendering. Cross-world source cuts also survive identity mappings; -coincident-copy suppression applies only within one world. Product captures still -expose a body gap before retirement as well as previously observed adoption gaps. -Live limb animation and continuity across in-flight image replacement remain -unfinished. -Keep those remaining intervals in the completion criteria; a visible head alone -does not prove that the whole avatar is rendered correctly. - -The product trace now identifies a separate temporal mismatch: requests with no -crossing body complete while the predicted body has already cleared the mouth. -In `body-coincident-third.log`, the first six source-portal round trips take -131 to 134 ms. Request 4 first carries body geometry, but its image arrives at -frame 97, after ten frames with no visible body. This is dev/offscreen evidence, -not release performance. Correct clipping cannot repair a picture sampled before -the body entered it. - -Separate the locally controlled body's final presentation from the retained room -image. The receiving renderer needs destination depth in the same capture frame -as that image, plus the capture camera and seam mapping, to depth-test the latest -local pose through the aperture. A color-only overdraw would show the body through -walls. Portal producers now capture and transport paired color and depth through -both copied and resident paths. Connect that depth to body composition; an uncut -source row or faster request loop is insufficient. Preserve copied geometry for remote observers, -child views and shadows; exclude its primary visible copy when the receiver owns -the current body layer. Account identity and endpoint incarnation define that -ownership, including retirement and successor adoption. - -The PIMG v12 copied-reply codec defines depth as tightly packed little-endian -float32 distance along the capture camera's forward axis in destination world -units. Positive zero denotes no surface; negative values, negative zero and -nonfinite samples are refused. Color and depth share one request/capture key, -extent and revision set, with separate hashes and bounded lossless compression. -The inbox charges both decoded payloads before allocating a replacement and keeps -the previous image charged until transactional decoding succeeds. - -The graph capture node now accepts an optional R32F depth input. Resource-image -export copies it alongside color in one submission, either into a shared bounded -staging buffer or two resident textures. Resident adoption transfers both textures -and charges both; replacement and cancellation release the pair. Copied portal -GPU import now validates and uploads both planes, reusing a pair only when both -digests match. Depth-only changes invalidate the image, and color-only replacement -releases its old depth. Both allocations must succeed before old attachments are -released. Upload and download layouts align rows and offsets for the supported -Direct3D constraints; residency and transfer counters include both planes. -Portal producers request paired capture. A separate per-view depth export uses -positive zero for background while the lighting resource retains its FarPlane -clear. The export writes its own named R32F target before presentation; it does -not alias lighting depth. Copied replies hash both planes, and resident publication -retains the pair under the existing capture identity and renewal lifetime. - -This capture infrastructure does not prove final portal depth correctness. -G-buffer depth precedes transparent composition, nested portal radiance and lens -processing. Define and implement the matching visibility/depth contract for those -stages before using it to occlude the current body pose. The GPU fixture verifies -camera-forward depth and color consistency for an opaque wall with translated and -rotated cameras, not those remaining composition cases. - -The sampling transform is part of the retained image, not the latest camera. -For seam captures it maps source positions through the seam into capture clip -space; for whole-eye captures it maps destination positions directly. Its clip-w -coordinate equals camera-forward distance in destination units, including seam -scale. Whole-eye demand now constructs this matrix with the request instead of -leaving identity in the binding. Compare body depth in these same units and use -the matrix belonging to the accepted reply. Camera motion must not relabel an -in-flight image with a newer transform. - -Resizing a paired eye image must preserve sample identity. The eye-image node -uses nearest sampling for both color and depth when exporting the pair; blending -colors across a depth discontinuity while selecting one depth invents radiance -for the selected surface. Color-only display retains linear filtering. This is -a conservative point reconstruction, not a higher-quality edge-aware filter. - -Opaque finite-aperture composition requires two complementary current body -halves. Clip the far half away from the source eye and compose it against the -retained destination color/depth pair before sampling through the finite mouth. -Draw the near half on the source side, preserving source foreground occlusion. -Importing the composed image alone cannot show limbs that project outside the -opening while lying in front of its plane. The GPU prototype compares this split -against a directly rendered complete body, including an oblique mouth and the -Humanoid-selected first-person exclusion. It uses a static emissive opaque room; -scaled cross-world mapping, later layers and product ownership remain unwired. - -`SplitPortalBodyDraws` now provides the bounded draw preparation shared by that -prototype and future product composition. The caller supplies selected ordinary -body rows and an explicit source-side plane. The helper preserves that side as -the body moves, maps the complementary plane and geometry through a similarity, -and compacts shared skin ranges once for both halves. Source tag bits stay on the -near half. Invalid geometry, incompatible existing cuts, aliases and budget -overflow leave the preceding output unchanged. This helper chooses no world, -session or body authority; the host must supply the accepted owner and mapping. - -`PortalImageSource::Capture` exposes a value snapshot of the retained image's -producer incarnation, accepted binding, camera pose/frustum/clip plane, excluded -player identity and extent. Pending requests keep separate camera metadata. -Acceptance of copied pixels, a resident receipt or a renewal advances the -captured metadata together; pending work and failed replies cannot relabel the -old image. Polling expiry or withdrawing its endpoint removes this snapshot. -Use the accepted camera and sampling matrix to prepare body views rather than -the latest request. Product body composition still needs to consume this API. -`PortalImageHost::Capture` exposes the same snapshot through the product adapter, -keyed by viewport and portal. It forwards to the owning source without caching -another copy; pending camera requests preserve accepted metadata, and viewport -removal or receipt expiry makes the snapshot unavailable. - -PIMG v12 carries optional evaluated lighting in copied replies, resident receipts -and renewals. `PortalCaptureLighting` includes sun direction, ambient terms, -direct intensity, fog color/distances and up to 16 selected point/spot lights in -capture-world units. The bound is checked against the renderer's light limit at -compile time. Explicit floats and a bounded count carry no entity IDs or pointers; -nonfinite values, invalid ranges/cones/fog intervals and noncanonical unused rows -are refused. The payload costs 69 bytes plus 44 per selected local light. -Accepted snapshots expose it beside the matching camera and binding, including -while replacement requests are pending. A renewal cannot change these inputs -while claiming the retained image version. Failed captures carry no lighting. -Shadow maps, environment textures and later radiance layers remain separate work. - -`ResolvePortalCaptureLighting` is the shared conversion from that payload to a -render view. It validates through the codec's shared validator before changing -any view fields or caller-owned local-light storage. It replaces the captured -shading terms and enables their override while preserving camera/ownership and -other environment/layer fields. The caller keeps light storage alive through -rendering. Producers use this same conversion before queueing a capture; invalid -destination lighting returns a failure through the bounded retry path, retaining -the receiver's preceding image. Product body composition still needs to bind -the accepted snapshot and remaining environment/shadow resources together. - -`ResolvePortalCaptureCamera` is the shared reconstruction path for producer and -retained body views. It preserves the asymmetric frustum and oblique clipping -projection, with camera-forward depth in the capture's units. Invalid pose, lens -or clipping data leaves the destination view unchanged; successful resolution -changes only camera fields. The producer now uses this same path. - -The finite-aperture GPU prototype now reconstructs a rotated, translated seam -capture at scales 0.25, 1 and 4, maps the far body into that capture, and samples -the composed result through the source aperture. Direct scene comparisons cover -first-person Humanoid selection, third-person body cuts and oblique views. -Both intermediate images can remain resident, with no additional imports; -the fixture separately reads back images for its comparison oracle. -Repeated resident exports now reuse replaced color/depth texture pairs. A -four-entry cache matches exact extent and depth presence, with at most 12 MiB -of cached payload. Cached bytes are reported separately and share the existing -32 MiB imported-texture budget; adoption and copied-import allocation evict the -cache when needed. Dropping the last imported image or shutting down releases -it. Adoption remains valid for submitted exports, with no added device wait. -The repeated-export fixture alternates body color/depth, verifies flat texture -allocation counts after warm-up, then checks extent changes, eviction and fresh -sampled output. GPU pressure checks also cover copied uploads at 30 MiB live -payload and colour-only resident adoption at 31 MiB, each evicting optional -cached pairs before exceeding the shared 32 MiB limit. Final removal clears -live, cached and pending image bytes. This is dev allocation evidence, not a -release timing result. -`eye-image` defaults to `projection=eye`; mapped intermediates explicitly select -`projection=seam`. A capture with the wrong projection is refused in either -direction. This validates the opaque prototype, not product snapshot consumption -or complete transparent and nested radiance layers. - -The producer's `OpaqueLighting` profile now exports `lit` immediately after -deferred lighting, with matching zero-background camera depth. It stops before -sky, volumetrics, spatial lenses and later presentation stages. A live GPU lens -fixture verifies that toggling the lens changes CompleteWorld radiance while -OpaqueLighting radiance and both profiles' opaque depth remain unchanged. -This provides the opaque pair only; later layer transport and product selection -remain separate work. - -An opaque composition backend is now available as `depth-compose`. It reads -foreground and background HDR/depth pairs in one capture projection and writes -the nearest color and camera-forward depth together. Zero means no surface and -equal distances retain the background. Depth uses nearest sampling; each pair -must have matching extents. `eye-image` can expose the imported depth beside its -color, and refuses a requested pair if the owned image or depth is absent. -`graph::DefaultPortalBodyDocument` provides the shared intermediate graph. It -runs body geometry through opaque lighting, linearizes its zero-background -depth, reads the owned room pair and captures the composed HDR/depth pair at -`export`. Eye and seam projections are explicit variants. The shared graph -requires `opaque-lighting` room scope and stops before sky and later world -layers; the host must apply those layers before final presentation. The GPU -fixture uses this graph instead of keeping a private composition implementation. -Its `scope` selector defaults to `complete-world`; an opaque-layer graph selects -`opaque-lighting` explicitly. The imported capture must match that scope, so a -flattened world image cannot silently satisfy an opaque-layer read or vice versa. - -The GPU fixture renders a fresh blue body against a retained red wall, then -compares with directly rendering both objects. Copied and resident room images -match the direct color/depth reference for front, behind and return poses with -identity and rotated cameras. The body extends past the wall, so this checks -both occlusion and uncovered body pixels. Subsequent body updates neither upload -the room again nor allocate more textures after warm-up. Output byte counters -and the existing per-node timing/heap scopes cover composition and eye-image -blits. These are dev/offscreen correctness and allocation checks, not release -performance measurements. - -The opaque fixture also compares non-emissive blocks and six-part Humanoids -under directional lighting, with identity and rotated cameras. Turning off the -current body's sunlight leaves the retained wall radiance and composed depth -unchanged; restoring the light restores the composed image exactly, with no -additional room uploads. This verifies independent body lighting in the backend. -Product composition still needs lighting inputs associated with the accepted -capture, rather than borrowing the source viewport's current lighting. The -fixture disables shadow casting and ambient illumination, so it does not prove -body-to-room shadows, ambient occlusion or transported lighting metadata. - -This backend is not yet connected to the product's current-body selection. -Retained camera matching, aperture mapping, primary ownership exclusion, animated -poses and the transparency/lens work below must be connected before the product -walk can close. The fixture now covers opaque blocks and a six-part Humanoid -with emissive materials to isolate visibility. The Humanoid's limb rows pass -through a half-scale seam transform and a world-plane cut. A changed right-arm -pose changes the captured image; restoring it restores the image. Disabling the -cut exposes more body pixels, and a first-person camera with the Humanoid as its -subject suppresses the body while preserving the retained room color/depth. -These checks do not prove skin-mesh animation, destination-lighting continuity, -finite aperture mapping or product camera/session handoff. -Product integration must request an opaque-layer profile when later -transparent or lens stages exist. Feeding flattened CompleteWorld radiance into -this opaque compositor would lose those foreground layers. Do not suppress the -producer's primary body until the receiver owns a matching, drawable layer set. - -The existing canonical `EyePlayer` selection now also works for seam captures. -It excludes the selected account only from that capture's primary draw order; -native and copied bodies remain available for shadows and child views. No new -wire field is needed. Default seam demand still leaves selection empty: do not -inherit first-person body exclusion into a secondary portal view. A receiving -body layer must explicitly claim primary presentation before setting this field. - -A single final color plus opaque depth cannot insert a body behind glass. With -foreground radiance F, opacity a and background B, the received pixel is -C = a*F + (1-a)*B. Replacing B with the body needs F and a separately; neither C -nor the opaque depth determines them. Retain a bounded ordered representation of -transparent foreground radiance, opacity and depth, then insert body fragments in -depth order. Specify overflow behavior before adding the payload: silently dropping -transparent layers or treating them as opaque fails the visibility contract. -Charge every retained layer and transfer against the existing byte budgets. - -The GPU `depth-compose` node now supports `mode=transparent` alongside its -unchanged opaque default. Each ordered layer supplies straight-alpha foreground -radiance and matching camera-forward depth. The background and output use -premultiplied radiance. Visible fragments blend over the current image, while -opaque depth remains unchanged; equal depths retain the background. Callers must -apply layers back to front before spatial lenses. GPU checks cover zero/half/full -opacity, transparent empty background, opaque occlusion and depth ties with two -layers. This is the composition primitive only. Complete ordered-layer capture, bounded -wire/resident ownership, overflow handling and product wiring remain required. - -The `transparent-layer` graph node peels ordinary transparent geometry using -native device depth from the same projection. A nearest-fragment pass stores its -D32 attachment; a second pass blends every fragment at that exact selected depth -in draw order. A final fullscreen pass reconstructs R32 camera-forward depth -from the selected D32 attachment with the same shader used for opaque body depth. -Interpolated world-position depth is not interchangeable at exact ties. The node -exports premultiplied HDR colour, reconstructed R32 depth and native D32 depth -for the next peel. `opaque-z` rejects opaque occlusion and -`previous-z` rejects preceding layers. The compositor's `mode=premultiplied` -accepts this colour without multiplying its opacity twice. No extra texture or -CPU readback is needed for the gather pass. - -Exact depth ties preserve all contributions. Transformed, mathematically -coplanar panes can round to adjacent device depths and occupy separate layers; -tests require their complete opacity and direct-render pixel parity without a -world-space epsilon. That parity gate is currently failing: native drawing sorts -whole objects, while peeling sorts fragments. Intersecting panes reproduce the -same disagreement with clearly separated depths, independently of coplanar -rounding. The ordering contract must be unified before this gate can close. -Checks cover overlapping coplanar panes, rotated cameras, intervening opaque -bodies and exact opaque ties. Surface shading and declared -shadow sampling match the forward pass; unsupported surface/custom-shader rows -refuse capture. A third depth capture detects overflow in the two-layer fixture. -Particles, ribbons, nested apertures, bounded atomic layer-set publication, -explicit overflow refusal and product primary-body ownership remain open. - -Layer capture admission now reserves one to four existing export slots together. -Requests must share pipeline, view and delivery, with distinct live tokens; -validation or capacity refusal admits none. Copied group collection moves results -in requested order only when every member is ready, including explicit failures. -A missing, duplicate, resident or pending token consumes none of the group. -Each result records the renderer-local frame that actually ran its capture. A -publisher must compare that frame and capture identity before combining layers; -queue admission alone is not proof of a coherent publication. The glass fixture -uses this group path and verifies one capture frame across its four outputs. -This adds no slots, textures, GPU submissions or waits. - -Resident adoption now preflights one to four captures together. Every capture -must be successful and submitted, with matching renderer-local frame, pipeline, -view and extent. Tokens and destination owners must be distinct. The complete -replacement peak must fit the existing texture budget, and every destination -slot must be available before any ownership moves. Refusal preserves capture -tokens, old imports, cache residency and caller output handles. Success transfers -all textures without allocation, readback or a GPU wait, retaining replaced -textures under the existing cache budget. The single-image API uses this path. -This is local ownership only: authenticated layer-set receipts, copied transport, -overflow refusal and product receiver composition remain open. - -Copied layers now have a bounded PIMG kind-5 envelope containing one opaque image -and up to two ordered premultiplied transparent images. Every member retains its -paired depth, lossless image encoding and digest. The outer key and dimensions -admit all member prefixes before decompression; aggregate expanded pixels must -fit `MAX_PORTAL_IMAGE_PIXELS`, and the whole message remains within the existing -4 MiB wire budget. Successful members must share key, extent, capture tick, -content revision, lighting revision and evaluated lighting. Transparent opacity -must be in [0,1], positive-depth fragments must have nonzero opacity, and empty -pixels must have zero colour and opacity. Malformed sets leave output unchanged. -The encoder reserves the actual encoded size and copies each member once into -the envelope. Product routing, authenticated layer-set receipts, overflow proof -and receiver composition are still required. The codec does not prove that the -producer captured every visible fragment or establish endpoint authenticity. - -The receiver body graph can now opt into two ordered transparent imports after -opaque body/room composition. `eye-image` selects `base`, `transparent-0` or -`transparent-1`; non-base imports require paired depth and match the base image's -owner, key, projection, sampling, extent and content/lighting revisions. The -renderer-local binding role keeps all three images under the same portal without -overwriting one another. Ordinary flattened portal sampling only accepts the -base role. Transparent handle changes, withdrawal and reordering invalidate the -portal presentation signature. - -A GPU fixture decodes the copied layer-set envelope, imports all three members, -and compares body/room/glass composition against analytic projection and alpha -blending. It checks bodies before, between and behind the glass and opaque room, -rotated camera coordinates, current body motion without room uploads, swapped -roles and mismatched capture keys. This is an opt-in receiver graph using ordinary -geometry. Atomic copied-set publication, product routing, overflow proof, -Humanoid integration and complete later-layer support remain open. - -Copied sets now enter renderer ownership as immutable groups in new import slots. -Admission validates every member without re-encoding, checks the aggregate CPU -and texture peak while old imports remain live, and prepares all texture pairs -before moving any input bytes or publishing handles. Invalid input, slot or byte -pressure leaves the input, output handles and old imports unchanged. Optional -retired textures may be evicted if allocation needs their budget. Group readiness -requires every exact member's upload to have been submitted; an old set can keep -rendering while the new one uploads. The caller must drive upload work while -waiting, even when its displayed old view is otherwise cached, and switch all -handles only after readiness. - -Individual image updates cannot overwrite grouped imports. Layer sampling rejects -mixed group identities, and dropping any member retires the whole group. Retired -pairs reuse the existing bounded cache; repeated same-extent replacements need no -new texture creation after warmup. The last import release clears that cache. -Product demand/reply routing and readiness-driven presentation are still required. - -PIMG v12 adds an explicit `OrderedLayers` request profile. It requires -`OpaqueLighting`, no recursion and no retained-image renewal. Admission charges -four full-resolution captures against the existing pixel budget: opaque, two -ordered transparent layers and a third transparent layer used only to detect -overflow. This caps square requests at 256 pixels per side. The wire version -change rejects older envelopes rather than interpreting their reserved bytes. - -`PortalImageProducer` installs a separate cached graph for this profile. It -queues all four exports atomically with renderer-generated tokens, collects them -together and verifies successful captures from one renderer frame and extent. -Any nonempty overflow depth returns `BudgetExceeded`, carrying no partial pixels. -Otherwise it sends a single copied layer-set envelope through the existing -presentation bus. Full mailboxes retain the encoded envelope and retry without -recapturing, rehashing or encoding it again. Cancellation retires every token. -Ordinary copied replies now release both pixel and depth vectors after encoding. - -The producer GPU fixture checks zero, one and two layers, visible overflow, -opaque blockers hiding the third pane, successful recovery after refusal, and -full-mailbox retries. It checks every returned pixel's depth, opacity and emitted -colour channel. This is explicit bus-driven producer coverage. Product source -receipt handling, resident layer-set receipts, readiness-driven group switching, -current Humanoid composition and complete later-layer support remain open. The -single-image inbox rejects flattened successful replies to ordered requests; -it still accepts their explicit failure replies. - -`PortalImageInbox` now admits copied ordered sets after authenticating the exact -sender, receiver and pending correlation. The borrowed layer matcher checks the -outer key and dimensions, requires both transparent members, and checks every -nested prefix before allocating or decompressing pixels. Budget admission charges -all member pixels, depth and owned text while the old held set remains charged. -Decode failure preserves the request and old set; successful admission replaces -the complete set together. `TakeLayers` moves all members together, while the -single-image extractor leaves grouped images untouched. Withdrawal and expiry -retire the whole set. Failure replies complete the request without replacing it. -The actual producer GPU fixture now consumes its replies through this inbox. - -`PortalImageSource` now takes accepted layer groups and queues them into new GPU -slots. It keeps the preceding displayed handles and accepted camera/lighting -metadata while uploads are pending. `HasPendingUploads` tells a host when it must -render a view even if its displayed picture is otherwise cached. -Only a later poll observing complete group readiness publishes success, switches -all captured handles/metadata and retires the preceding image. Captured snapshots -include the ordered transparent handles. Restart, supersession, expiry and endpoint -withdrawal cancel pending groups. Layered requests bypass single-image renewal -and resident reservations; single receipts cannot satisfy a layered request. -Switching back to a single image retires the preceding group. - -Host upload scheduling is wired: pending groups force client scene damage, and -any normal view can submit their immutable uploads. Sampling still checks the -original world and viewport ownership. Empty transparent passes clear their -outputs without binding absent instance buffers. - -Before client composition was connected, a repeated physical walk passed its room-landmark assertions but still -shows the avatar disappearing: the 60 Hz world run has zero avatar-yellow pixels -in frames 87 through 98. The cleared-camera image fixture excludes its body -visibility assertion, so that passing test cannot establish character continuity. -`player-crossing-recheck.png` and its JSON preserve the transition evidence under -`.cache/build/dev/tests`. Fix and verify this product path before claiming -seamless character crossing. - -The strengthened physical oracle now checks every third-person source-replica -frame until the camera is actually cleared. It fails at both 30 Hz (frames 86-94) -and 60 Hz (87-91), with 14 failed body checks. All these samples still use a -Humanoid subject and native view (`eye_image == false`), with an external portal -image. The first product integration target is therefore current body composition -inside the external seam, not only the whole-eye handoff. The retained capture -camera and depth must locate the current complementary body half before aperture -sampling. Keep primary body exclusion separate from nested views, and complete -later-world-layer support before replacing flattened captures generally. See -`portal-body-oracle.log`, PNG and JSON under `.cache/build/dev/tests`. - -The renderer now exposes `ComposePortalBodyImage` for the product seam adapter. -It validates a complete ready room group, reconstructs its accepted camera and -lighting, renders current opaque body rows, and adopts the paired composition -export without CPU readback. Its room group stays intact; successive outputs reuse -the existing single-image ownership path. The operation forces body refresh even -when the caller's view is cached. The caller must retire its output and choose a -target extent compatible with other renders using that view slot. Unsupported -transparent/custom body rows are refused. Eye-variant GPU checks pass, but product -seam integration and aperture verification are still outstanding. - -`PortalImageHost::ComposeBodyImage` now owns composed output separately from the -accepted room group. It replaces outputs and retires them on hidden demands, -viewport/world removal, endpoint withdrawal, profile changes and expiry. The -renderer operation's frame export explicitly selects the target slot; graph -instances are cached per projection and viewport. Its temporary body subset also -invalidates the shared slot's source-row cache before a parent view can reuse it. -GPU checks cover nonzero viewport ownership, retirement and parent-row restoration. -The joined client's native portal path now requests ordered room layers for its -local or held player identity. It selects the current mapped body rows from the -seam demand and uses the host-owned composition for aperture sampling. First-person -views omit the primary body. Readiness requires the actual composed aperture -handle. This connection does not establish continuous crossing: the latest normal -physical walk still fails 20 body-visibility assertions at 30 Hz, frames 35-54. -The inspected captures have `image == 0` on the external portal throughout that -interval. The first source image request is logged at frame 48; the local -presentation replica starts supplying captures later. Investigate cold endpoint -availability and initial image admission alongside the later crossing failures. -Do not classify a pre-assignment debugger read of zero as a renderer refusal: -return-value and guard breakpoints did not reproduce such a refusal. - -The ordered-layer pixel test now covers seam and eye projections, translated and -rotated cameras, and the renderer's accepted-camera composition operation. -All 48,702 assertions pass (`portal-body-seam-check.log`). This isolates a working -seam composition primitive, but does not prove product endpoint timing or complete -world-layer support. `portal-body-current-walk.log`, PNG and JSON retain the -physical failure evidence under `.cache/build/dev/tests`. - -The physical fixture now has a separate warm-start case. Only that case waits -for a completed frame with an imported external portal image before beginning -movement. It retains the same body, Humanoid subject, camera-clear and bidirectional -handoff assertions. The original cold-start case remains unchanged and failing. -The warm-start case passes 15,806 assertions across 30 Hz and 60 Hz world runs -(`portal-warm-walk.log`). Inspected handoff images retain the avatar on both sides; -PNG and JSON are saved beside the log. These runs received their first images at -frames 87 and 79 respectively. Server image producers already skip demo creation, -but initialize a GPU and join their world replica before publishing endpoints. -Initial playable-world readiness remains unresolved; do not use a warmed fixture -to claim that a newly joined player can immediately cross an unavailable portal. - -The native image adapter now prefers an authenticated remote image endpoint over -a matching local player replica. Replica snapshot arrival previously opened a new -local producer and switched image ownership; a focused test reproduced that -switch (13 passed / 1 failed assertion). Camera and physics destination selection -retain their existing replica preference. If the remote endpoint is withdrawn, -image requests can still fall back to the ready local replica. - -Route, replica-arrival and copied camera-topology checks pass 163 assertions in -three cases (`portal-image-route-final.log`). The warm bidirectional product walk -passes 15,820 assertions at 30/60 Hz; its log contains no image requests switching -to `client.portal` replicas. Inspected handoff images retain the avatar. The cold -walk still fails one body assertion at 30 Hz frame 86: the external image handle -is zero there and becomes nonzero in frame 87. This is not a startup completion -claim; the duration varies with process and device startup. Logs and retained -PNG/JSON evidence are named `portal-image-route-warm` and -`portal-image-route-cold` under `.cache/build/dev/tests`. Temporary frame sequences -were removed after retaining those artifacts. - -Image producers without GPU particle batches now service captures directly after -world presentation, skipping the unused ordinary viewport and screen-interface -frame path. Capture pumping reuses that prepared world and runs inside the frame -profiler. Producers with particle batches retain the normal GPU step, then service -captures without presenting the world twice. Interface initialization is retained -for that fallback. Producer service frames use the existing monotonic schedule, -defaulting to 60 Hz or the explicit maximum frame rate; update polls use its short -idle wait. Removing the viewport without pacing initially caused 100,000 service -frames in seconds. The paced restart fixture reports 119 service frames in 2.0 s. -This is a scheduling check, not a release CPU/GPU speedup measurement. - -Saved/replicated producer, lighting update, shutdown and server restart checks pass -847 assertions in two cases (`portal-producer-paced-host.log`). The combined warm -and cold walk run passes 31,672 of 31,673 assertions: warm crossing passes, while -the cold case fails its return-handoff landmark check at 30 Hz frame 251. Blue -floor pixels change from 270 to 130 against a minimum of 135. Body checks passed -in this run; this is a distinct handoff-image discontinuity, not the earlier -missing initial image. `portal-producer-paced-handoff.png` and JSON retain the -inspected frames. Initial availability, handoff pixel continuity and full world -layer support remain open. Four temporary frame sequences were cleaned. Final rebuild passes; the saved/replicated -producer check passes 550 assertions after retaining the particle fallback -(`portal-producer-final-host.log`). - -Capture-sequence metadata now records the accepted image identity and camera: -producer world/session/generation, request and seam/camera revisions, projection, -frustum, clip plane, dimensions and viewport slot. Whole-eye records include the -bound handle; external aperture records include their accepted room capture. -These are capture-only diagnostics. The physical fixture verifies that each -whole-eye record names the bound handle and a valid eye request. - -The rerun passes 17,340 assertions (`portal-capture-metadata-walk.log`), but its -metadata exposes a stronger continuity gap than the landmark oracle detects. -At 30 Hz frames 257-258 the accepted whole-eye image retains request 11 and handle -103 across return adoption. Its camera position is about 4.5 metres from the -current eye before adoption. Maximum accepted/current eye-position separation -in the recorded sequence is about 8.36 metres at both world rates. This measures -camera positions in this unit-scale fixture, not a latency estimate. The previous -handoff landmark failure remains valid evidence of intermittency; this passing -rerun does not close it. Retained PNG/JSON artifacts share the log's stem. - -The whole-eye gate must compare the displayed result against the current camera, -including angular motion and depth/parallax, rather than only checking image -availability and body colour. Current whole-eye sampling can display a retained -capture from a different camera. Establish current-eye reprojection/composition -and direct-view image parity, including disocclusion and later world layers, -before marking continuous camera crossing complete. Temporary raw frames were -removed after retaining the handoff samples and displacement series. - -Successor readiness no longer submits its staged camera into the persistent -whole-eye slots. The debugger reproduced `PumpPortalSuccessor` calling -`PreparePortalEye(..., prepareNative=false)` and then `SubmitEye` for slot 3 -(`portal-staged-eye-call-debug.log`). That allowed readiness checks and the -displayed camera to compete for one request stream. The readiness branch now -only checks the matching displayed-eye image; the normal frame remains its -request owner. Camera route resolution and the successor's own drawable slot -remain in place. - -Both warm and cold walks pass 35,120 assertions after this change -(`portal-eye-owner-walk.log`), with successful builds and formatting checks. -This fixes competing request ownership, not the whole camera-lag problem. -Maximum accepted/current position separation remains approximately 8.3-10.4 metres -across these four runs. `portal-eye-owner-walk.json` retains the per-frame series, -handoff metadata and worst-displacement samples; its PNG shows those samples. -Investigate retained full-eye request latency and nested capture dependencies, -then verify current-camera pixel parity. Do not infer that eliminating staged -requests eliminates delayed images. Four raw frame sequences were cleaned. - -The request-age audit correlates consumer issue/receive timestamps in -`portal-eye-owner-walk.log` with frame timestamps and accepted request IDs in -`portal-eye-owner-walk.json`. These are dev/offscreen diagnostic timings from -128 x 128 captures, not release performance measurements. At each run's maximum -position separation: - -| World tick rate | Start | Frame | Request to receipt | Receipt to displayed frame | Total camera sample age | -| --- | --- | --- | --- | --- | --- | -| 30 Hz | Cold | 193 | 285 ms | 284 ms | 569 ms | -| 60 Hz | Cold | 195 | 251 ms | 318 ms | 569 ms | -| 30 Hz | Warm | 277 | 253 ms | 251 ms | 504 ms | -| 60 Hz | Warm | 206 | 317 ms | 318 ms | 635 ms | - -The source permits one outstanding request per compatible binding and displays -its previous accepted image while awaiting the next reply. This accounts for -sample age approaching two request cycles. The `eye-image` node in -`render/src/nodes/OutputNodes.cpp` directly blits the accepted texture; it does -not transform samples from the accepted camera into the current camera. -Reducing request latency cannot by itself establish continuous camera parity. - -Inspection of `PortalImageProducer::Pump` rules out ordinary scene revision -changes repeatedly rebuilding children: each job collects them once, then -revalidates the visible seam set. Seam changes fail the job explicitly. The -consumer log measures 16 local nested replies with a median 99.5 ms round trip; -it does not expose the remote producers' internal dependency timings. Do not -attribute the whole-eye delay entirely to nesting from this evidence. - -Next validation must deliberately retain an accepted eye capture while moving -the consumer camera and compare with a direct render at that new camera. Cover -translation, rotation, depth edges and newly exposed surfaces. Current-camera -composition must handle missing samples and later world layers explicitly; -reusing an arbitrary retained child or warping only colour cannot close this gate. - -The missing gate is now executable in `render/tests/ResourceImage.cpp` as -`[eye-current-camera]`. It captures an emissive room once, imports its colour and forward depth -through the same `DefaultEyeDocument` used by the product, then compares its HDR -output with a direct render from the current camera. The scene has a near red -occluder, a hidden green post and a blue rear wall. Independent colour checks -prove the post is absent initially and becomes visible after translation. - -Dev/offscreen Vulkan builds without warnings. The targeted run -`SDL_VIDEODRIVER=offscreen .cache/build/dev/tests/test_render '[eye-current-camera]'` -fails three image comparisons: translation differs at 986 pixels, rotation at -786, and combined movement at 424, each out of 2,405 pixels. The stationary -control passes. The run has 102 passing assertions and 3 failing assertions -(`eye-current-camera-gpu.log`). This is an unresolved correctness test, not an -expected-failure annotation or a passing compatibility claim. Selecting the -resource-image GPU suite now includes this known failure. - -`render-failures/eye-current-camera/comparison.png` retains expected, actual and -difference panels; per-motion raw HDR samples and manifests retain precision. -The missing green post demonstrates that camera reprojection alone cannot -recover all newly exposed geometry from a single colour/depth image. Continuous -crossing still needs destination scene/layer coverage sufficient for the current -camera, plus correct camera-dependent composition. No runtime fix is claimed by -this test addition. - -Parent captures now defer camera-dependent lights, ribbons and spatial UI while -cross-world child images are pending. The first waiting pump reproduced one -unnecessary prepared view (`portal-wait-preparation-before.log`). The shared -runtime continues validating seams and collecting surfaces for child budgets; -it prepares the remaining layers from the current world state once children -are drawable. `render.portal_snapshot.prepared_views` counts actual preparation, -and snapshot byte accounting excludes retained layers on skipped pumps. -Runtime/host Vulkan tests pass 29,041 assertions in 28 cases -(`portal-wait-preparation-gpu.log`). This removes observed redundant work; no -release speedup or reduction in network round-trip latency has been measured. - -The scheduling change also passes the real cold and warm player walks at 30/60 Hz: -34,610 assertions in two cases (`portal-wait-preparation-walk.log`). The retained -PNG shows the first handoff and worst-displacement frame for each run; the JSON -keeps both handoffs and per-frame accepted/current camera separation. Maximum -separation is still 7.8-10.1 metres. These results verify character/image continuity -for this fixture, not current-camera parity. All 4,800 temporary BMP/JSON frames -were removed after extracting the evidence. - -Destination scene coverage must reuse authenticated, per-viewer replication -admission and filtering. `Server::BeginPresentationProducer` gives its renderer -an independent identity and restricted-world admission; that grant does not -belong to a portal viewer. `Client::InitialisePresentationHost` consumes the -ordinary replicated world through an inherited driver channel. Re-exporting the -producer's entire ECS snapshot through an image reply would bypass that ownership -boundary and include resources beyond the requested visual scene. Do not use -`Store::Save` as an unfiltered portal-view payload. A destination visual replica -must retain its own admitted stream and endpoint incarnation, remain separate -from player/input ownership, and retire with its view subscription. Images still -serve the explicit bus-driven capture path. The image-only versus destination -scene-data product choice was presented to the user and remains unanswered. - -A held Humanoid no longer forces the native source world to display a retained -whole-eye image once its aperture images are drawable. `Client::PreparePortalEye` -now keeps the current native view in that case; foreign eyes and unavailable -native images retain their existing routing. Product walk tests require at least -one held-character frame on the native path, alongside the existing body, -camera-subject and movement checks. The four latest runs cover 17-18 such frames -each. Builds and formatting pass. The initial cold-only run passes 17,119 -assertions (`portal-native-held-walk.log`). - -The combined cold/warm run has 34,000 passing assertions and one failing landmark -assertion (`portal-native-held-final-walk.log`). Cold 30 Hz return frame 257 -reduces the blue floor patch from 300 to 143 pixels, below the half-size threshold. -The body and native-held checks pass. Both failing boundary frames use remote -eye images: request 10 becomes request 11, whose accepted camera is at z=19.56 -while the current camera is at z=15.11. `portal-native-held-return.png` and JSON -retain this failure; do not weaken the landmark threshold or describe the whole -walk gate as passing. `portal-native-held-final.png`/JSON retain native-held, -handoff and worst-displacement evidence. Maximum foreign-eye separation remains -8.1-9.5 metres. All 4,800 temporary capture files were removed. This native-path -change does not close the foreign-eye current-camera composition gate. - -The wider `[portal-product-walk]` matrix now ran all 16 combinations of 30/60 Hz, -first/third person, automatic/explicit Humanoid subject and held/released movement. -It has 138,627 passing assertions and six failures -(`portal-native-held-camera-matrix.log`). First-person 30 Hz with explicit subject -and released movement has no eye image at frame 84. First-person 60 Hz with -automatic subject and held movement has no eye image at frames 86-87. Each frame -fails both image readiness and visible-output checks. These are initial foreign-eye -readiness gaps before adoption, distinct from the return landmark failure. - -The trace places the first-person `walk.destination` request's receipt on the next -frame after the 30 Hz gap and at frame 88 after the 60 Hz gap. In the latter case -it was issued at 13:22:34.288 and received at 13:22:34.589. Preserve this first-image -readiness requirement alongside current-camera parity; a successful transfer alone -is insufficient. Handoff contact sheets and metadata for all 16 combinations are -under `portal-native-held-camera-matrix/`; 19,200 temporary capture files were -removed. Those contact sheets cover handoffs, not the earlier missing-image frames; -the failure log is the evidence for the latter. That run preceded the initial -entry gate described below; its image oracle remains unchanged. - -The player presentation pump now flushes newly queued image packets before the -server sleeps. QUIC pacing needs the current monotonic time for this second flush, -not the earlier tick timestamp. The old timestamp flushed zero active wires; -current-time samples flush 87 wires over 84 calls and 97 over 95 calls. This is -transport evidence in dev, not a matched release performance result. The full -camera matrix after that change has 136,402 passing assertions and 21 failures -(`portal-presentation-current-flush-camera-matrix.log`). Cold 30 Hz third-person -frames 35-55 have no yellow body and an unfilled external portal. The first image -arrives at frame 56. `portal-current-flush-cold-failure/` preserves sampled PNG/JSON -frames and a contact sheet; the 19,200 raw capture files were removed. - -Initial entry now holds keyboard/gamepad movement until visible native portal -images and the nearby prefetched foreign eye are ready. Look and zoom remain -active, so first-person requests use the selected body-hiding profile. This is a -one-time viewport gate that survives body-world adoption, not a freeze at every -crossing. The existing overlay shows `Loading portals`; capture metadata records -`loading_portals`. The product walk checks zero horizontal predicted velocity -while loading and requires an observed loading interval. The loading preference -was unanswered; this proceeds with the stated loading-phase assumption. - -Client/test_client builds and formatting pass. The initial cold/warm 30/60 Hz run -passes 34,184 assertions and fails one return landmark check -(`portal-entry-readiness-walk.log`). Warm 30 Hz return frame 269 changes the blue -floor patch from 345 to 143 pixels, below the half-size threshold. All loading -movement checks pass. `portal-entry-readiness-evidence/` retains loading/ready -scene images and the failing return boundary; 4,800 raw captures were removed. -Scene captures exclude the host overlay, so these images do not verify the -loading label. The first wider run exposed a first-person loading stall: -`CurrentImage` requires no pending refresh, but live look input starts another -request before the gate reads it. The diagnostic run was stopped with SIGINT -(73,560 passing / 29 failing assertions, including interruption). Its log is -`portal-entry-readiness-camera-matrix.log`; first-person frames 100 and 599 are -retained under `portal-entry-readiness-evidence/stuck-first-person/`. The 11,864 -interrupted raw captures were removed. The gate now accepts a usable completed -image with the selected body-hiding profile while a camera refresh is pending. -Endpoint expiry still belongs to the source runtime. This does not claim exact -current-camera rendering. The corrected full matrix passes all 136,954 assertions -(`portal-entry-compatible-camera-matrix.log`): all 16 combinations of 30/60 Hz, -first/third person, automatic/explicit Humanoid subject and held/released movement. -Loading spans 13-39 captured frames across those runs. Per-case loading, first-ready -and both adoption frames are retained under `portal-entry-compatible-evidence/`, -with a JSON summary. All 19,200 raw captures were removed. After entry, the gate -no longer copies capture metadata merely to recompute unused readiness. The final -client/test_client build and `git diff --check` pass. The final authenticated -producer-host check passes 305 assertions in `test_client` -(`portal-entry-client-host.log`). An earlier invocation against `test_server` -matched no tests and provides no validation. Current-camera parity, loading -refusal/retry UX and complete crossing acceptance remain open. - -A retained-source prototype was tested and removed from the runtime. It kept one -previous authenticated connector and advancing snapshots, stopped the old gameplay -script systems, and used a separate local whole-eye slot with a warm remote -fallback. Tests confirmed advancing snapshot ticks and displayed local images. -Reusing the remote slot first discarded its ready image: 34,069 assertions passed -and 81 failed (`portal-retained-walk.log`). A non-increasing scheduler replacement -revision then triggered the safety fallback and all eight retention assertions -failed (`portal-retained-slot-walk.log`), correctly rejecting a false success. - -With script stopping corrected, the retained path passed 36,966 assertions and -failed 103 (`portal-retained-clock-walk.log`). One return was delayed until roughly -frame 486. Frames 240-440 show `proceed=false` and `crossed=false`, with expired -nested successor captures. The delay precedes physical handoff; lease renewal is -not established as its cause. The source nevertheless renews the original transfer -lease while its old connection remains live, which observer lifetime must address. - -Retiring the observer when successor staging begins removed the long delay in the -next four sampled runs. They still fail: 34,812 assertions pass and three fail -(`portal-retained-staging-walk.log`). Warm 30 Hz frame 260 shrinks the floor patch -from 267 to 121 pixels. Warm 60 Hz frame 141 is completely black, while frames -142-143 show the scene. All three use local resident handle 670 with identical -camera and capture metadata. This needs a focused GPU first-use reproduction; -a nonzero handle and an arbitrary one-frame wait are not correctness proofs. - -`portal-retained-staging-evidence/` preserves the black-frame contact sheet, -PNG/JSON boundaries, four-run summary and `prototype.patch`. Earlier failure -samples are under `portal-retained-evidence/` and `portal-retained-clock-evidence/`. -Each run's 4,800 raw captures was cleaned up. The four runtime files exactly match -the pre-experiment copies; client/test_client rebuild, formatter and diff checks -pass after restoration. The restored producer-host check passes 305 assertions -(`portal-retained-rollback-host.log`); the full camera matrix was not rerun after -restoring those exact sources. Observer content delivery, endpoint/lease retirement, full visual -layers and exact current-camera rendering remain open. This experiment does not -claim a retained-source feature or seamless crossing completion. - -The focused first-use fixture now passes 688 assertions across 16 combinations -(`eye-first-use-lifetime-gpu.log`, dev Vulkan). It immediately adopts a resident -capture, switches from viewer slot 3 to either 3 or fresh slot 4, retains the -fallback image, and checks the first two frames. It covers full versus scene-only -damage, texture-only versus headless presentation, and the normal eye pipeline -versus an extra HDR readback. The normal presentation branch uses the product's -`RequestSceneCapture` path. HDR bytes match the independent source capture and -the displayed centre remains blue. Successful BMPs are removed by the fixture. - -A window-backed variant crashed inside swapchain initialization before drawing, -including with the client's window flags (`eye-first-use-window-flags-gpu.log`). -It was removed: the product crossing tests use a headless device with presentation -enabled, so a window was not needed to match that path. This is not evidence that -the product black frame is a driver defect. The isolated test does not reproduce -the product failure, and no renderer runtime fix follows from its passing result. -Next, isolate the local producer publication/adoption and nested capture ordering -from the saved product prototype. The retained observer and full crossing work -remain incomplete. - -### Render-stage snapshot probe - -`ATOMIC_RENDER_PROBE_DIR` enables a diagnostic probe in the client or render tests. -`ATOMIC_RENDER_PROBE_FIRST` and `ATOMIC_RENDER_PROBE_LAST` select an inclusive -renderer-frame range (defaults 0 through 8, maximum span 1025 frames). Renderer -frames include producer captures, so these are not client capture-sequence indices. -Each renderer creates its own run directory to separate viewer and producer devices. -For example, the checked fixture command is: - -```sh -ATOMIC_RENDER_PROBE_DIR=.cache/build/dev/tests/stage-probe-check \ -ATOMIC_RENDER_PROBE_LAST=5 SDL_VIDEODRIVER=offscreen \ -.cache/build/dev/tests/test_render '[stage-probe],[eye-first-use]' -``` - -Prefix the existing client command with the same environment settings to probe -that scene. `index.html` shows the snapshots in execution order with stage/resource -labels. Each snapshot has a metadata JSON, raw `.bin` pixels with declared row -pitch and SDL format, and a BMP preview. Preview channels clamp to [0,1]; raw HDR -values remain unchanged. The probe also copies the imported whole-eye input before -`eye-image`, so a bad imported image can be distinguished from a later bad stage. -Metadata includes pipeline, world, viewport, eye handle, camera position and whether -the node accepted and ran. Nodes without texture outputs and unsupported formats -are recorded explicitly. Texture snapshots currently cover base mip and layer zero. - -Each copy is recorded directly after its graph node in the same GPU command buffer, -before later nodes can reuse its storage. GPU-to-CPU waits and disk writes happen -only after submission. Captures are bounded to 256 snapshots and 256 MiB per render -batch. This diagnostic changes timing and must not support performance claims. -Submission failures discard the queued readbacks; missing files must not be treated -as valid snapshots. Disable the environment setting for the ordinary rendering path. - -The dev client and test_render build pass. The probe-enabled first-use checks and -same-command blue-then-red overwrite test pass 756 assertions in two cases -(`render-stage-probe-final-gpu.log`). All 1,072 recorded snapshots had raw and preview -files, with no unsupported formats in this fixture. Thirty-two imported-eye/output -pairs match exactly, excluding transfer padding. One browsable trace and a stage -comparison PNG remain under `stage-probe-check/`; duplicate traces and the overwrite -fixture's temporary images were removed. This validates the probe, not the product -black-frame fix. - -The saved retained-source prototype was rerun with stage probing and then removed -again. `ATOMIC_RENDER_PROBE_VIEW` now optionally restricts capture to one viewport; -omitting it captures all selected-frame viewports. The local-eye-only run used -view 4 and renderer frames 0-1024. It passed 16,924 assertions and failed one -(`portal-stage-probe-walk.log`): warm 60 Hz client frame 245 reduced the floor patch -from 556 to 185 pixels. Capture metadata changes from remote handle 733 to 736; -the old captured camera is roughly eight metres behind the live camera, while -the replacement remains several metres behind. All 786 stage snapshots were -saved, with no black whole-eye or final-scene output in that trace. - -The wider run captured every viewport at renderer frames 180-360. It passed 16,826 -assertions and failed ten (`portal-stage-all-walk.log`). At warm 30 Hz client frame -145, corresponding to renderer frame 215, `eye-image` receives handle zero and -writes black to `eye-hdr`; tonemap and present retain that black output. The -normal missing-image clear in `nodes/OutputNodes.cpp` explains this stage result. -The client log immediately before capture reports a camera route waiting for -`server.world` topology from `walk.destination`. A reply arrives in slot 3 while -the displayed view has slot 2 and no image. The selection/lifecycle cause still -needs isolation. This is distinct from the earlier valid-handle black frame, -which these runs did not reproduce. - -The broad probe materially changes timing: GPU waits and roughly 6.6 GiB of -stage files extended the run and coincided with image expirations. It is useful -stage evidence, not a timing-neutral reproduction or a performance result. -`portal-stage-evidence/missing-eye/` retains renderer frames 214-216, client frames -143-147, raw pixels, metadata, a browsable index and `stages.png`. The first run's -floor boundary and first local images remain under `portal-stage-evidence/30/` -and `60/`, and first-local stage copies remain under `portal-stage-trace/`. -The broad trace and both raw client capture directories were removed. All five -prototype files match their pre-run bytes; client/test_client/test_render rebuild -passes, and the restored producer-host check passes 305 assertions -(`portal-stage-probe-rollback-host.log`). No seamless-crossing fix is claimed. -Next isolate the missing-image route selection with a narrow probe, then return -to the original valid-handle failure and full current-camera acceptance. - -A focused topology recovery test reproduced an additional outage: a renewal -requested at 250 ms and processed at 1000 ms was discarded because the cached -snapshot expired at 1000 ms, although the authenticated request remains valid -until 1250 ms. The old code left the request pending after discarding that reply. -The failing test reported 13 passing assertions and one failure -(`topology-renewal-before.log`). `PortalTopologyHost::Pump` now accepts matching -renewals within the pending request deadline, including after cache expiry. -Snapshot access still returns null before the reply arrives; endpoint identity, -correlation, revision and request-deadline checks remain in force. A reply at the -1250 ms deadline cannot revive the snapshot. This closes a proven recovery gap; -it does not prove the earlier product black frame had this exact cause. - -The topology/restart suites pass 124 assertions across seven cases, and the copied -remote-camera routing test passes 144 assertions (`topology-renewal-after.log`, -`topology-renewal-route.log`). The dev client and both test binaries build. The -cold/warm product image-handoff checks pass 33,872 assertions across two cases -and four 30/60 Hz runs (`topology-renewal-product.log`), with the retained-source -prototype absent and stage probing disabled. Input-world adoption boundaries and -neighbouring images remain under `topology-renewal-evidence/`; all 4,800 raw client -capture files were removed. Formatting and diff checks pass. The full 16-combination -camera matrix was not rerun for this narrow renewal change, and the original -valid-handle black frame and current-camera parity remain open. - -Route selection now consumes already-delivered topology messages before checking -its cache. The expanded `remote-eye-route` test reproduced two failures when an -authenticated destination reply was in the universe inbox but `PortalImageHost` -had not been pumped (`topology-ready-before.log`, 178 passing / two failing -assertions). `RequestTopology` now pumps only the topology host before requesting -refresh. It does not run image producers, enter a GPU wait, or wait for network -traffic. The existing endpoint, world, correlation, deadline and revision checks -still decide whether a queued reply may update the cache. Routing now passes 288 -assertions with and without an earlier host pump, including expired topology and -withdrawn endpoints. The topology/restart/non-GPU host checks pass 172 assertions -across eleven cases (`topology-ready-route.log`, `topology-ready-host.log`). - -Direct rendering of a retained local world remains the next larger construction -step for current-camera parity. The current client view assembles its input world's -lighting, shaders, instances, particles, ribbons and interface before selecting -an eye image. Replacing that image with only the retained world's geometry would -mix worlds. The retained prototype also drops `Content` and `ContentRelay` at -adoption. A complete implementation must retain authorized content delivery and -use one engine-owned world-view preparation path for these layers, shared with -local image producers rather than another partial client collector. Snapshot -inputs crossing the world enter/leave boundary must be owned copies; renderer -pointers must remain local. Use the current eye pose on every draw, preserve body -ownership and aperture composition, and keep image-bus rendering for worlds whose -visual data is not locally admitted. The previous replica's observer lifetime -must also stop gameplay lease renewal without losing authorized presentation. -No direct retained-world renderer is implemented by these topology fixes. - -The full product camera matrix also passes 136,117 assertions -(`topology-ready-camera-matrix.log`): all 16 combinations of 30/60 Hz, first/third -person, explicit/automatic Humanoid subjects, and held/released movement. Stage -probing is disabled and the retained-source prototype is absent. The two adoption -boundaries and neighbouring image/metadata files for each run remain under -`topology-ready-camera-evidence/` with a JSON summary; 19,200 raw capture files -were removed. Build, formatting and diff checks pass. This verifies the routing -ordering change against that matrix, not complete current-camera parity or the -original valid-handle black-frame case. - - -Graph failure before a capture node now completes that batch's queued image -requests as failed. Unrelated pipeline/view requests remain pending. Recorded -copies retain their device fences but cannot publish success for a failed graph. - -Body composition must also precede world shader lenses. A spatial lens can move -pixels, so applying an unwarped depth test after it mixes different rays. Carry the -required authored lens inputs and content identities with the capture, then apply -the same ordered lens chain after local body composition. Nested apertures need -their own mapped body layer and depth domain; a child's distance cannot be compared -as if it were in its parent's world. Keep direct-render comparisons with glass, -a spatial lens and a nested scaled aperture as distinct acceptance cases. - -Keep room radiance/depth resident and invalidate them together on scene, lighting, -camera or aperture changes. Local limb/root updates should update bounded geometry -and palettes without retransmitting the room image. Bound depth payload bytes, -retained images and staging slots; count actual transfer bytes and operations. -Disocclusion, off-screen samples and stale depth need explicit coverage. Faster -transport is useful but cannot substitute for this composition contract. - - - -Reuse the existing primary draw-order stream for exclusion rather than copying -or deleting resident scene rows. Include exclusion identity and resolved rig -changes in image demand and object/composition invalidation. Preserve unrelated -environment and shadow caches. Validate opaque and blended limbs, retained -images, duplicate character names, held-subject adoption and two viewers before -claiming this complete. Compare direct and remote pixels with the same camera; -keep small before/after captures and remove temporary frame sequences. - -Invalidate view history, image demand and retained composition when the eye's -endpoint incarnation or seam mapping changes. Reuse producer scene inputs and -resident image slots across the transition, with fences controlling retirement. -Readiness must include a published drawable destination view as well as the -joined replica and resolved Humanoid. Verify every frame during preparation, -commit, first presentation and arm crossing, including reverse entry and refusal. - -`PortalImageSource::Poll` now revalidates each producer receipt against the -Universe presentation directory. Withdrawal or same-name incarnation replacement -retires its pending request and retained GPU image immediately, before the image -age timeout. This also removes copied images, which cannot depend on resident -receipt invalidation. Readiness returns only after an image from the replacement -receipt arrives; hosts must keep the Universe directory current. - -Supervised producer traffic and lifecycle cleanup run only with a closed -coordinated tick frame. Receiving a new endpoint directory inside an open frame -cannot register its endpoints, and disconnect cleanup cannot retire old ones. -Defer the entire producer pump, including process exit/retry handling, until the -frame boundary. The relay also leaves transport traffic queued during an open -frame, so directory updates and replies cannot be consumed under that refusal. - -Returning to a native replica also has an image-readiness boundary. Preparing a -native frame now warms its demanded portal images before choosing the displayed -view. If those images are absent and the same authored world's owned whole-eye -image still exists, keep requesting/displaying that eye until native portal -images arrive. Do not create an extra whole-eye fallback for a cold view that has -never owned one. Refresh caller spans after collection changes portal/surface -storage, and keep the existing image age/incarnation retirement rules. - -The authenticated successor may discover producer routes before commitment using -an empty consumer directory. The original connection retains reply ownership -until adoption. Each replacement connection owns a fresh presentation stream; -framing sequence state must not survive a reconnect. Source input submissions -continue during the retirement/adoption gap and stop after destination input -ownership takes over, allowing already-sent packets to drain. - -Before Proceed, a failed successor keeps retrying the same cancellation attempt -at half-second intervals until the source acknowledges it. Successful transport -queueing is not application completion. A dropped source acknowledgement must -not strand the held camera or prevent a later transfer offer from being adopted. -The retired source departure answers repeated cancellation without recreating -body authority. Product Client checks with authenticated source/successor -listeners now withhold the successor snapshot through the 15-second readiness -deadline, and separately disconnect before that snapshot. Both preserve the -source player, cancel the failed attempt and adopt a later transfer without a -fresh destination avatar. The Server fixture drops destination transfer replies -for 40 ticks and requires the source rig to remain held until cancellation is -acknowledged. These are separate protocol fixtures; their combined physical walk -with image fidelity remains open. - -Source replica retirement and destination adoption are separate events. Cover -both explicit entity destruction and authoritative snapshot omission during that -gap. Any retained subject representation must preserve the player/Humanoid/root -relationship without duplicating physics, scripts or GUI startup. Bound its -storage to the affected rig, resolve replacement identity from the accepted -transfer receipt, and release it on adoption or cancellation. Verify displayed -camera motion and destination-driven subject motion independently of retained -controller input. The implementation gates and known cloning limitations are in -`RENDER-REFACTOR-TASKS.md`, under "Source retirement". - -Retain submitted movement and its actual prediction duration independently of -source consumption. Reconcile the held presentation against an atomic completed -destination pose, replay only later retained inputs, and reject samples whose -input frontier predates retained coverage. Keep this history bounded and scoped -to the exact transfer claim. Carry the mapped presentation through adoption; -handover to native destination input also requires a completed pose associated -with that input clock. A global replication acknowledgement does not prove that -a budget-deferred root update arrived. Check displacement through adoption and -the first native correction, so a fix cannot merely move the jump one frame. -Keep control consumption distinct from elapsed simulation: a host may coalesce -several inputs or continue a held direction between arrivals. Verify the replay -duration against those actual intervals, including held-key and stop-at-adoption -crossings, before treating a matching input prefix as prediction parity. -The product Client preserves its input timeline across replica replacement; -world clocks and connection acknowledgements remain independent. Compare elapsed -input and simulation time across the route switch before changing host input -scheduling or applying a presentation correction. Opt-in `portal-input` traces -now expose actual control assignments on both routes. Interpret forwarded -and scheduled assignments as pre-physics, and legacy `native` trace assignments as post-physics; -retain the last assignment before each physics step. Initial traced runs showed -native takeover advancing the input frontier faster than elapsed world time. -Native controls now use a bounded queue anchored to the last forwarded physics -assignment. Its completed pose reports actual application. This aligns the -route clocks. Unconfirmed source controls now survive adoption and are resent -before newer input, including local send-budget retry. Replay uses each timed -input's recorded duration. Body and Humanoid camera now share fractional -prediction presentation, with phase continuity across adoption. This removes the -observed alternating doubled and stationary camera steps in the held movement -case. Intermediate tick input coverage and the first completed destination -sample nearly cancelling a held frame's movement before adoption remain open; -the task ledger records reproductions and trace artifacts. - -Destination worlds receive named, versioned view requests through the world bus. -Bounded jobs prepare their immutable render inputs; the destination renders its -own lighting and scene state. Return an owned image payload or serialized image -artifact through the bus, with world generation, request identity, seam/camera -revision, extent, format, capture tick and completion status. Raw ECS or GPU -pointers never cross this boundary. A same-process optimization may resolve a -local image slot on the render owner from the receipt, but must also pass the -copied-message/process-isolated path and retain the image until consumers retire. -Scope that local slot to the renderer owner, source viewport, both endpoint -incarnations and the complete request identity. A receipt is not proof that a -failed or unsubmitted capture is usable. Propagate failure explicitly and cancel -the reservation when the source deadline expires. Exercise queue saturation, -supersession and endpoint teardown in both delivery modes. - -Use bounded queues and byte/pixel budgets. Coalesce superseded view requests, -discard stale replies, and accept completed images at explicit presentation -boundaries. Delayed jobs must not change deterministic world tick outcomes. -Test moved portals/cameras/lights, resize, world unload/reload, failed captures -and out-of-order replies. Expose destination-image age and missing-frame status; -the seam cannot quietly display a cached picture of a different camera or world. - -Cross-world walking sequences must prove both sides together: the player sees -the destination before entry, both clipped character halves agree while -straddling, one body owns collision at each barrier, and its humanoid camera -continues smoothly after acknowledgement. Repeat in reverse and through a loop, -with destination failure and high-speed traversal as separate cases. - -### visible proof scene - -Build `PortalSeams` example: contrasting lit rooms, matching floor grid, an oblique -and moving portal pair, a portal loop, a mirror, a skinned/rigid object crossing, -a rolling body, a fast projectile, a long body straddling and a cross-world pair. -Show entry/exit planes, body owner, velocity vectors and source/destination -clipped bounds on demand. Provide deterministic camera/crossing scripts, pause, -single-step and direct-versus-portal split view for agent inspection. - -Gate is inspected image sequences plus numeric ownership/contact tests. A single -still image cannot prove seamless motion, physics or temporal history. - -Repair the existing non-Euclidean portal demonstration through these same engine -paths. Preserve its spatial illusion while checking corridors/rooms reached from -multiple directions, repeated loops, look-back after crossing, moving lights, -objects and humanoid-following player cameras. The example must expose a fixed -scripted all-angle route and an interactive walking route. Record per-frame -aperture/depth probes and ownership/camera continuity alongside the captures; -renaming the demo or adding a disconnected showcase does not close its defects. - -### bound portal views before shading them - -Traverse a conservative portal adjacency graph from each demanded camera; -intersect projected apertures with the parent clip region before allocating a -capture. Use existing spatial data for candidate portals. Reject only proved -invisible/empty apertures; temporal visibility is not enough after camera motion. -Recursion limits remain explicit approximation boundaries. - -Scale capture resolution from projected aperture footprint plus filter/temporal -margin, with quantized size classes and hysteresis. Allocate portal targets from -the common pool and budget total recursive pixels, not just recursion depth. -Small portals can use lower resolution only within declared image-quality limits; -test near-plane approach and rapid aperture growth to avoid a blurry threshold pop. -Measure clip-plane distances and bias in the destination's length units after -seam scaling. Include shrinking exits and continuous approaches between sampled -camera poses, where a fixed near-plane cutoff can hide a visible aperture. - -Share destination world geometry, acceleration and compatible lighting inputs -across portal views. Reuse capture pixels only for equal effective camera/clip/ -lighting/content keys; identical destination names do not make two entrance -viewpoints equivalent. Cache seam transforms by portal revisions and child-view -plans by lineage, with bounded eviction when no parent demands them. - -Intersect swept body bounds with portal spatial bounds before expensive far-side -contacts. Share original mesh/skin data between clipped draw proxies and encode -the seam transform/plane in compact per-view references. Render visibility must -never gate physical crossing checks. Moving portals require relative surface -velocity at the crossing point, including angular motion; rotating a body's -velocity alone is insufficient. Test moving entrances/exits explicitly. - -Invalidate cached portal shadows/captures from both endpoints, transported light -paths and destination revisions. Approximate low-rate far captures must show age -and quality policy; do not hide stale physics or light discontinuity behind them. -Profile recursive pixel count, unique worlds versus views, proxy draw amplification, -capture reuse and physical seam candidates separately. -Compare resident and copied image delivery with identical pixel oracles. Report -bus bytes, readback/upload operations, target creation/retirement and live/peak -payload separately. A resident path that allocates a fresh target each frame has -removed CPU transfers but has not established target reuse or lower frame time. - -## 13. editable packing, quantization and geometry detail - -### explicit policy components - -Add scene-owned quantization policy components for editable mesh and editable -texture/image data. Use one shared format vocabulary with component-specific -channels. Fields include enabled state, target attributes/channels, encoding, -range/scale/offset, rounding mode, saturation/refusal policy, quality/error limit -and revision. Format names serialize as strings and drive both VMs and Studio. - -Distinguish three operations: editing canonical authored values, rounding those -values to a declared lattice, and storing/uploading a compact representation. -An explicit destructive rounding edit changes authored values and revision; -presentation-only packing preserves authored values and updates visual residency. -Collision rebuild follows actual mesh edits, never camera-dependent quantization -or displacement. Undo/redo restores values and policy in one transaction. - -| Requested family | Representation contract | GPU path | -|---|---|---| -| float16 | IEEE binary16, declared finite/overflow/subnormal rules | Native where supported; packed uint decode otherwise | -| unsigned float16 | Explicit nonnegative range or named unsigned encoding; not an assumed IEEE type | Defined encode/decode and error test before exposure | -| float8 / unsigned float8 | Named exponent/mantissa layout, e.g. explicit E4M3/E5M2 semantics, sign/nonnegative policy, finite limits | Packed storage with shader decode on baseline; no assumed native texture format | -| int16 / uint16 | Signed two's-complement or unsigned; raw integer versus snorm/unorm is explicit | Typed integer fetch or normalized/decode path | -| int8 / uint8 | Same distinction, bounded channels/ranges | Probe storage/arithmetic/sample support separately | -| int4 / uint4 | Defined signed/unsigned nibble order, padding and stride | Pack into byte/word; decode explicitly | -| bool | Canonical zero/one value; bit-packed storage with explicit word layout | Mask/shift decode; no C++ bool ABI on wire | - -Signed/unsigned labels cannot be aliases with different undocumented ranges. -Round-to-nearest ties policy is deterministic; reject NaN/infinity in authored -finite types; define zero, negative zero and saturation. Test min/max, ties, -odd counts, endian, alignment and every code for small formats. - -Storage support does not imply shader arithmetic support, and arithmetic support -does not imply a filterable image format. Probe the actual backend surface; -FP16/int8 feature support itself is optional on relevant Vulkan versions. -[Khronos feature contract](https://docs.vulkan.org/refpages/latest/refpages/source/VK_KHR_shader_float16_int8.html). - -For bounded normalized quantization use scale/offset and a recorded max error; -the half-step error holds only within range without clipping. Positions use -mesh-relative bounds; normals/tangents use octahedral encoding with handedness; -UVs preserve authored tiling via separate bounds/scale. Degenerate extents decode -without division. CPU reference and GLSL/MSL decoders must agree. - -### mesh allocation and bake pipeline - -Keep the existing shared vertex/index buffer model, add slab suballocation only -when arrivals/growth cause measured transfer waste. Use bounded free ranges/bin -classes, coalescing, stage/commit batches, geometric growth/high-water retention, -deferred reuse and an oversized-mesh policy. O(1) claims need an actual allocator -proof; do not copy them from research notes. - -Use u16 indices when all referenced indices fit; u32 otherwise. Validate count -and overflow, including 65,535/65,536 boundaries. Quantize then weld on compatible -attributes, preserving UV/normal/material seams and tangent handedness. Reorder -triangles for post-transform cache, optimize fetch order and remap vertices. - -Editable mesh changes repack/upload dirty attribute/index spans where the format -allows. A changed quantization bounding box can invalidate a whole stream; count -that full repack honestly. Immutable bake and runtime editing share codecs, -while the cook stays off the shipped runtime path. - -### four LOD modes and tessellation - -1. Four authored mesh levels: stable references, projected size/error thresholds, - per-level bounds and residency. Missing finer content selects a resident - coarser level; it does not erase the object. -2. Automatic decimation: deterministic edge collapse with normal/UV/material - constraints and attribute weights. Share vertices/index ranges where useful, - allow separate coarse streams when needed; store measured geometric error. -3. Smart triangle reduction: select by projected geometric error and triangle - area, with silhouette/boundary preservation. Tiny triangle count alone is not - permission to remove important silhouettes or thin walls. -4. Meshlet/virtual geometry: cook 64 to 128 triangle clusters as initial test - sizes, hierarchy/DAG, sphere/cone bounds and error. GPU chooses a crack-safe - cut, culls and streams required pages. Hardware raster for larger clusters, - optional compute visibility raster for tiny triangles, then material resolve. - -All selections run in GPU per-view output beside culling, using stable instance -slots. Store policy and level references in world rows. Add hysteresis (0.85 -down-threshold ratio as an experiment), camera-specific history and separately -tuned shadow LOD. CPU selection remains a test/no-compute fallback only. - -Meshlet work is a required staged prototype under this request, not silently -discarded as long-horizon. Bound page tables/requests, provide resident coarse -coverage, stitch transitions and handle edits. Probe 64-bit atomics or use a -proved alternative before a packed atomic visibility implementation; capability -failure selects the four-level/decimated graph with a visible reason. - -Tessellation is a node with bounded factors, crack-compatible edge rules and -camera/error policy. Use native tessellation only where the backend exposes it; -compute subdivision or baked subdivisions provide supported fallback. Visual -displacement samples declared maps, expands bounds and updates normals, shadows, -velocity and traced geometry. Physics still sees authored collision geometry. - -Proof covers watertight seams, negative scales, degenerate triangles, UV repeats, -alpha edges, topology edits, LOD oscillation, cameras choosing different levels, -portal views, streaming pressure and conservative bounds. Report source/packed -bytes, triangle/vertex fetch counts and decode cost, not a guessed percentage win. - -### optimize packed bytes across the whole path - -Choose attribute layouts by consumer. Depth/shadow/culling paths need position, -indices and alpha where masked, not all normal/UV/colour streams. Compare split -position and shading streams against interleaving; preserve cache-friendly index -order. Do not force every pass to decode an expanded common vertex structure. - -Measure CPU authored bytes, packed upload bytes, resident bytes and temporary -conversion peaks separately. Keeping editable float32 source plus a packed GPU -copy reduces device cost, not CPU authoring memory. If compact canonical editable -storage is enabled, setters/readers decode or quantize through the declared -component policy and undo uses bounded page deltas, not whole-mesh snapshots. - -Quantize directly into staging for CPU-authored data when this removes a temporary -copy. For GPU-generated geometry, keep generation/packing on device and avoid -round trips. GPU-packing float32 uploads only saves resident/fetch bytes, not -host-device bandwidth; reports must distinguish these cases. Update packed words -at their real write granularity so adjacent nibble/bit edits cannot race. - -Retain local quantization pages/ranges where mesh-wide bounds changes otherwise -force complete repacks. Bounds expand conservatively; shrinking/requantizing -happens only under an explicit edit/cook operation or measured maintenance policy. -Check page-edge seams and include per-page headers in compression ratios. - -Reuse meshlet hierarchy and topology across cameras; store only each view's -selection. Compact active selected clusters before raster work, and use material -bins only where sorting cost is recovered by coherent shading. A changed camera -may recompute selection while unchanged geometry stays entirely resident. - -Cache bounded tessellation topology templates and draw-instance-independent -displacement data by source/policy key. View-dependent factors and time-varying -deformation cannot reuse an incompatible template/output. Share edges across -neighbouring patches and update displacement-derived bounds, velocity and tracing -once for compatible consumers, not once per shadow/camera pass. - -Defragment mesh slabs only when fragmentation prevents useful allocations or a -measured maintenance window justifies it. Relocate on device, patch stable -indirection at a safe boundary and retain old ranges until completion. A routine -arrival must not trigger a full-buffer compaction disguised as a delta upload. - -## 14. textures, mip streaming and atlas proof - -Keep source, cooked, compressed and device representations distinct. Evaluate -ETC1S/UASTC interchange in a bounded standard container and target transcode to -BCn/BC7, ASTC, ETC2 or RGBA fallback according to actual backend support. -Compare cook-per-target storage against runtime transcode cost; no runtime -recompression hidden in the render thread. UI/masks can request lossless formats. - -Mip chains preserve colour space, alpha coverage/premultiplication and normal -semantics. Flipbooks filter cells independently and stop when a frame reaches -one pixel; unevenly divided cells refuse an unsafe chain. Procedural/editable -producers use the same rule; dirty regions expand appropriately at each mip. - -Streaming starts with usable coarse levels, promotes by declared screen-footprint -policy, and uses hysteresis/cooldown. Apply byte budgets to resident, staging, -pending and retired allocations, not texture count. Do not evict current/in-flight -resources; demote unneeded fine mips before whole least-recently-used resources. -An oversized request fails without thrashing every other texture. - -SDL may require a new allocation for a different resident mip range. Account for -temporary overlap and retirement, update descriptors atomically, and ensure -missing upper levels are never sampled. Optional GPU feedback is asynchronous -streaming demand; LOD visibility decisions remain GPU-resident without a blocking -CPU readback. A conservative CPU footprint fallback may overrequest content. - -Staging uses bounded reusable buffer rings, aligned ranges and completion fences. -Recycle only retired ranges; cap bytes per frame and defer finer mips. Critical -base data and diagnostic markers have explicit priority; no unconditional full -buffer cycling/reupload on each arrival. Track queue age and refusal reasons. - -### atlas experiment - -Build a graph-addressable atlas/array allocator with stable logical handles and -indirection to tile/layer, UV rectangle, padding and mip availability. Test fixed -arrays before variable tiles. Group compatible formats, samplers and colour -spaces; repeat/wrap textures may require array layers rather than atlas tiles. - -Allocate gutters sufficient for filtered mip footprints; generate per-tile mips -with edge dilation. Clamp sampling within safe rectangles; alpha and normal -tiles need semantic padding. Repacking updates indirection transactionally and -retires old allocations only after references complete. Editable dirty rectangles -must not touch neighbours; rotated tiles require matching UV/normal conventions. - -### many 4K textures - -Create deterministic fixtures at 1, 8, 32, 128 and a pressure-selected higher count -of 4096x4096 textures. A base RGBA8 4K image is 64 MiB; its full chain approaches -85.33 MiB. Eight full chains already exceed the existing 512 MiB content budget, -so test streaming/refusal instead of promising all images fit. - -Compare RGBA8, semantically valid compact channels, block compression and packed -editable formats with/without atlas. Measure actual device/staging/retired bytes, -upload traffic, resident mip distribution, visible error, edit latency and frame -time. Sweep device budgets rather than allocating until driver failure. - -Tests include all tiles visible, mostly hidden, repeated materials, camera motion, -wrap/anisotropy, distant mips, alpha borders, shader sampling, one-pixel edits, -odd packed dimensions, repack, eviction and device recreation. Flat steady live -bytes plus bounded churn and correct images are the gate. - -### one device budget and bounded streaming pressure - -Coordinate texture, mesh, graph transient, history, portal, particle, tracing and -staging budgets through one render-owned budget view. Existing module counters -remain owners of their allocations; the budget view aggregates them rather than -duplicating storage. Reserve headroom for frame-critical and replacement resources; -each subsystem cannot independently assume it owns all available memory. - -Pin in-flight and required coarse data. Warm-cache eviction, deferred promotions, -history release and declared quality fallback precede refusal. Maintain demand -across all active cameras, portals, shadows and traces; main-camera texel density -alone misses reflections. Cap GPU feedback entries, deduplicate page requests -and process them asynchronously with conservative fallback after overflow. - -Avoid cache pollution from one-time captures or fast camera sweeps: keep probationary -entries separate from repeatedly used residents, with bounded retention and -promotion/demotion cooldown. Priority incorporates visual demand, request age and -bytes; starvation prevention ensures a large valid request eventually progresses. -Admission uses configured budgets and demand state, not profiler metrics. - -Partial updates follow compressed-block and mip-filter footprints. Batch texture -edits by destination and align dirty regions; uploading slightly more data can -be cheaper than many tiny copies. Do not transcode an unchanged whole 4K image -for a one-pixel edit unless that format forces it; surface that amplification -and offer an editable-friendly representation. - -SDL transfer buffers must be unmapped before encoding uploads. Reuse their -allocations with map/write/unmap batches and fence retirement; do not hold mapped -pointers across reuse or describe the SDL baseline as persistently mapped. -Cycling and changed destination storage require preserving all still-needed -contents. [SDL transfer-buffer contract](https://wiki.libsdl.org/SDL3/SDL_MapGPUTransferBuffer). - -On unified-memory systems, still measure CPU copies, coherency and allocation -churn. On discrete GPUs, track transfer payload separately from device-local -traffic. Neither memory model makes unnecessary work free, and SDL may abstract -away placement choices that a lower-level backend could expose. - -Atlas packing reduces binds only when the shader/batching path uses it; it does -not inherently compress texture bytes. Compare arrays, atlas and individual -textures at equal visible quality, including padding, fragmentation, descriptor -cost and mip residency. Prefer page-stable incremental placement to frequent -global repacks; bound the overlap cost of every relocation. - -## 15. save, replication, safety and migration - -Save authored names, parent references, sparse tagged overrides, declared feature -keys, attachment order, quantization policy and Studio-only source. Save revisions -only where reload semantics need them. Do not save resolved catalogues, GPU -handles/slots, capability decisions, cache timestamps or duplicated module bytes. - -Material/attachment deltas carry entity identity in the owning protocol, stable -slot/parameter name, base/next revision, bounded value and authority. Base mismatch -requests a bounded current snapshot; duplicate/stale deltas are idempotent. -Large textures/modules/material definitions use signed delivery, not replication. - -Server validates approved publication/schema names and values without compiling -shaders or linking render. Client-local visual overrides remain nonauthoritative; -gameplay cannot rely on local LOD, displaced vertices or visual particles. -Cross-VM setters, save readers and network readers use one canonical validation. - -Bound source/include expansion, names/errors, parameter/default/override bytes, -inheritance/fallback depth, variants, module words/instruction estimates, -descriptor ranges, local invocations, buffer/target extents, per-frame changes, -uploads and pipeline creation. Reject malformed arithmetic before allocation or -device calls. Validate SPIR-V and permitted capabilities independently. - -Signed bytes establish publisher identity, not shader correctness or a guarantee -against GPU hangs. Validate available structure, restrict resources and dispatch, -and isolate authoring workers; never claim static instruction counts bound -arbitrary loop execution. No raw device addresses, host pointers or undeclared -resources in authored contracts. - -Worker cancellation/failure cannot publish half an artifact. Escape source/path -diagnostics in UI, cap excerpts and unique-name diagnostic/cache growth. Fuzz -containers, reflection and translation under process limits; soak failed cooks, -publication swaps, resource pressure and delayed retirement. - -Migration is one-way conversion into canonical runtime structures. Freeze old -material/world/ShaderScript/graph fixtures; load cooked modules alongside the -existing source path temporarily; migrate material shader names into techniques, -package inline raster/dispatch source, then remove the source compiler path after -approved policy and package gates. Studio retains authoring source and cook jobs. - -Built-ins enter the same validation/reflection/container path. Preserve any -needed legacy readers for the declared support window, but remove duplicate -resolvers, hand-written parameter tables and old shader binding conventions. -Release target/staging checks prove no shaderc front end, source includes or -source-only runtime demands ship after the migration gate. - -### cheap stable validation and compact change delivery - -Validate immutable cooked structure once per verified content root, reader/policy -version and required device admission key. A reused cache entry must retain the -trust context; cache hits cannot bypass a changed allow-list or manifest binding. -Keep packet/override authority and revision checks on every mutable request. - -Coalesce repeated render-data writes within an authored transaction when only the -final value is observable. Script signals, undo boundaries, tick ordering and -replication base/next revisions still follow their public semantics; never merge -observable intermediate events merely to reduce uploads. One accepted transaction -can feed a compact dirty-page list to render and bounded deltas to replication. - -Intern stable names once at admission; use dense local slots thereafter. If the -existing wire protocol permits a session dictionary, transmit string definitions -before compact references and validate its generation; saves/manifests remain -string-identified and raw `Name::Id()` never becomes a protocol identifier. -Prefer existing protocol facilities to adding a second dictionary system. - -Bound serialization scratch, compression jobs and result queues. Cache immutable -serialized material/schema records and snapshot changed overrides rather than -walking all materials each tick. Track bytes encoded, verified and copied beside -CPU cost so deduplication is proved end to end, including rejected inputs. - -## 16. particles, environment and TornadoSim - -### retained particle foundations - -Preserve per-world pools and per-emitter fixed capacity blocks; live-prefix swap -retirement and free-range reuse. Separate mutable simulation, compact draw rows -and per-emitter shared state. The predecessor records 28-byte particle draws and -16-sample curves; verify current layouts before optimizing them. - -Keep stateless seeded emission from emitter identity, monotonic spawn counter and -purpose tag; never seed from a recycled slot. Curves update on authored revision, -transforms/forces on their own revision. GPU owns visual stepping when active; -CPU reference/fallback defines matched semantics without running a duplicate -live particle system. Spawn, integrate, retire and draw become explicit nodes. - -| Preserved candidate | Plan and gate | -|---|---| -| Blend/depth order | Retain blend/orientation partitions and unsorted additive particles; add bounded far-to-near depth buckets for blended groups; test overlapping smoke and bucket seams | -| Soft particles | Sample opaque linear depth, apply configurable depth-difference fade; opt-in for smoke, not mandatory for tiny sparks; measure overdraw/tile GPU cost | -| Significance/LOD | Compact emitter rows ranked by projected importance and effect class; rate/lifetime/size/pool caps, distance activation and fade; reduce fill footprint as well as count | -| Curl fields | Generic sampled/procedural vector field with strength-zero bypass; finite-difference curl of a defined vector potential, optional low-rate interpolated updates | -| Curves | Allow bounded per-emitter sample quality for sharp authored curves; do not enlarge every emitter's table | -| Trails | Preserve simulation-tick fixed ring and render-derived ribbon; authored-only save/replication restores empty history; no render-rate trail sampling | - -Field effects declare their units, clock, interpolation and bounds. Approximate -curl may have discretization divergence; test the actual field rather than -claiming perfect incompressibility. Field textures and parameters reside on GPU. - -### environment nodes - -Make existing SkyboxCompute, AtmosphereProcedural and CloudCompute paths explicit -graph producers. Add generic fog/volume resources, density generation, lighting, -integration, reprojection/upsample and composite nodes. World generation can be -shared; view integration/depth/temporal history belongs to each camera. - -Define sky cubemap face orientation, atmosphere units, density/extinction/albedo, -phase function, step count, light injection/shadow inputs and height bounds. -Test analytic empty/constant-density limits, Beer-Lambert transmittance, horizon, -camera-in-volume, depth intersection, lighting changes and temporal disocclusion. -Bound volume dimensions, ray steps, history and update rate; no unlimited compute. - -### TornadoSim obligations - -Retain the pure Luau first slice in [TORNADOSIM.md](TORNADOSIM.md). It is an arcade -analytical field, not a fluid-solver port. One `SampleField` provides softened -maximum-wind ring, radial inflow, central lift, upper flow and deterministic -turbulence; EF-style presets and lifecycle use tables and the script clock. - -`RunService.Heartbeat`, Part/Model/CFrame/Vector3/math.noise drive bounded kinematic -debris, ground bounce, tree bend and script-controlled building break groups. -ParticleEmitter disc/cylinder, tangential/radial forces, drag/noise and curves -make dust base, condensation funnel, rain shaft and cloud deck on the GPU. -Beam, PointLight, Trail and GUI supply lightning and hazard readout. - -`TornadoSim.luau` contains gameplay state, moving vortex, plain, structures, -camera, preset controls and camera-sampled hazard. First runnable slice needs no -external assets; later wind/thunder audio uses published content. No per-particle -CPU mirror, tornado-specific native component, or claim of rigid debris physics. - -Render gaps proved by the scene feed generic nodes: field-sampling force when -emitters cannot follow the field, volume rendering for dense cloud self-shadow, -visual deformation for vegetation, and lightning/environment composition. -Physics velocity/impulse or reusable break groups are separate owner-layer work -only when kinematic debris is insufficient. - -The source lab's 1M to 50M custom particles and sparse cloud density octree remain -explicit scale experiments, not requirements for the first script or promised -capacity. Profile the real scene first, then bounded pool/volume variants under -memory/fill limits. Procedural spatial audio remains an audio/content dependency. - -Proof: both VM metadata where relevant, Luau typecheck, headless script advance, -inspected funnel/rain/debris/tree/lightning motion, correct hazard at camera and -release profile stating debris, emitters, live particles and volume work. - -### reduce simulation, fill and volume work separately - -Maintain GPU lists of live emitter blocks and live particle ranges; dead capacity -does not deserve full integration work. Batch compatible emitters into dispatches, -share immutable curve/field tables and update only changed parameters. Alive -particle integration must remain defined while offscreen; visibility can skip -drawing, while paused/analytic catch-up simulation needs an explicit effect policy. - -Large smoke often needs fill-rate work more than a larger particle pool. Compare -tight quad bounds, depth rejection, half-resolution colour/transmittance targets, -depth-aware upsample and reduced screen footprint at declared quality. Opaque -depth must remain available for soft intersections. Small high-frequency sparks -can stay native resolution rather than sharing smoke's blur. - -Global transparency ordering cannot be guaranteed by sorting only within each -emitter. Test intersecting emitters, ribbons and glass; use shared depth buckets -or an explicitly approximate order-independent mode where appropriate. Keep -additive effects out of sorting. Order-independent transparency needs its own -alpha/energy/error test, not a silent substitute for correct blending. - -Separate weather density generation from lighting and view integration. Cache -static noise/shape and atmosphere lookup tables by physical parameters; sun -changes can relight without regenerating density. Compare bounded world-space -bricks/clipmaps against dense volumes, with conservative empty-space summaries -and coarse coverage before a page becomes visible. - -Volume rays skip provably empty bricks and may terminate below a declared -transmittance error threshold. World density/lighting may be shared; froxel -projection and temporal history remain view-specific. Reprojection rejects -disocclusion and lightning changes promptly; staggered updates cannot leave a -bright flash trapped in old cloud lighting. - -Evaluate the Luau storm field once per required gameplay consumer at its bounded -tick, and send compact storm parameters to GPU visual consumers. Field sampling -for many visual particles stays on device. Cache common field terms/noise tables -only where equivalent semantics or an explicit visual approximation allow it; -do not create a second authoritative wind model to make a benchmark faster. - -## 17. chunked-world render input candidates - -These requirements from the optimization notes remain owned work, with scene, -terrain, bake, world and physics plans providing the non-render systems. -They must not become private renderer terrain state. - -| Candidate | Preserved algorithm/constraints | Verification | -|---|---|---| -| Padded binary greedy meshing | Stage `(n+2)^3` voxel shell from immutable neighbour borders; bit masks per face, maximal run/row merge, optional 64-bit packed quad; reusable scratch | No hidden boundary faces or missing neighbour access; packed coordinate/extent overflow tests; fixed-width constraints explicit | -| AO-aware quads | Per vertex side1/side2/corner: both sides occupied gives zero, else `3 - sum`; 2-bit value; diagonal selected from opposite-corner sums | Document exact vertex order/diagonal rule and test asymmetric cases, rather than relying on a vague larger-sum instruction | -| Chunk scheduler | Coordinate-sorted derived readiness for generate/mesh/upload; revision/ticket validation, interior then border reconciliation | ECS owns state; no private dirty registry or structural tag churn; repeated/missed signals converge | -| Ticketed generation | Immutable request with graph/seed/coordinate/LOD/outputs; dedup full signature, bounded owned results, current ticket/revision check | Completion order alone cannot change simulation. Deterministic tick admission must wait/join or record an explicit admission decision; ticket sorting alone is insufficient | -| Streaming | Load radius inside unload radius, e.g. 3 versus 5 chunks; distance/frustum priorities; async byte/work and sync finalization budgets | Priorities affect visual arrival only; cancel pending eviction on reentry, memory bounded, physics admission deterministic | -| Region files | Candidate 32x32 columns, floor division for negatives, location/timestamp table, 4 KiB sectors, bounded independently compressed chunks and oversize sidecars | Transactional write/flush/recovery needed; synchronous open alone is not crash safety. Test torn writes, reuse and malicious offsets | -| Chunk phase DAG | Cached dependency order, per-tick readiness counters, conflict bitsets, bounded completion queue, fork/join within tick | Compare serial/parallel output; use simple phased Jobs::For below measured crossover | - -Greedy merge preserves material/alpha/AO seams. Border edits invalidate adjacent -derived meshes; LOD borders stitch or use justified skirts. No claim of a -hundredfold speedup or fixed performance factor survives without local evidence. - -### share generated artifacts, invalidate changed borders - -Deduplicate generation and mesh artifacts by content/seed/coordinate/LOD and all -relevant neighbour-border revisions. Reuse immutable interior data; copy only -required halo slabs into pooled job scratch. A neighbour's unrelated interior -edit should not remesh this chunk, while a border edit must invalidate both sides. - -Keep derived readiness event-driven through existing mutation feeds with bounded -reconciliation. Walk active ranges and changed chunks first, rather than sorting -every resident chunk on every tick. Cache phase order/conflict data by graph -version; workers produce isolated artifacts committed in deterministic order. - -Batch small meshing/generation tasks by measured grain and output size; maintain -per-worker pools with hard ceilings so parallelism cannot multiply scratch beyond -the scene budget. Track obsolete work discarded after camera/edit changes. -GPU-only visual meshing is an option only when physical consumers retain their -authoritative generation path and no readback is needed to unblock simulation. - -Incremental region-file writes reuse unchanged compressed records and group -adjacent I/O while preserving transactional recovery. Page-cache, compression and -staging budgets belong in total memory reports. Predictive visual prefetch must -not make asynchronous arrival affect collision or gameplay tick results. - -## 18. profiling and optimization gates - -Every meaningful node CPU scope uses existing ENGINE_PROFILE instrumentation, -feeding Tracy, FrameGraph and heap tags. Worker durations report after join, -preserving producer hierarchy. Waiting is Idle; dropped/unmarked work is visible. -Never add a second timing-only scope system. - -GPU timestamps bracket real node invocations and carry frame/world/view/node -generation plus query identity. Collect only completed slots, once; late/out-of- -order results attach to their producer, not a fabricated current-frame position. -Use GPU category and `gpu ` prefix under current root profiling rules, correcting -the predecessor's suggestion to categorize GPU work as ordinary Render spans. - -Existing timestamp notes specify 128 marks/four slots; verify actual backend -limits before assigning. Prioritize shadow/surface captures, geometry/lighting, -then post; show dropped marks. CPU-only nodes require no GPU marks. Vulkan-only -timing availability is not a claim of Metal timing support. - -Offer Off/CPU/Full runtime tiers and per-node `profile=false`, with rows labelled -unmeasured. Compiled-out support and runtime disable are distinct: a runtime -toggle cannot remove compiled macros. Sampling every N frames records age and -holds last valid data; disabling abandons pending queries without blocking. - -| Signal | Required detail | -|---|---| -| Frame time | CPU busy/self/idle, GPU producer duration, critical dependencies, submitted buffers and actual overlap evidence | -| Node work | Draw/dispatch/copy counts, submitted triangles, shaded/selected counts where observable, resolution/sample count | -| Culling/LOD | Candidate funnel, overflow/fallback, per-level counts, selected error, page/mesh requests | -| Lighting | Shadow tile texels used/allocated, cache ages, cascade updates, cluster count histogram and overflow | -| Traffic | Exact instance/index/material/texture/mesh/particle upload bytes and operations at transfer boundaries | -| Residency | Live/peak/cumulative allocated/released logical GPU payload, creation counts, staging and deferred bytes | -| CPU heap | Live blocks/bytes, total allocation and profiler overhead; one-second sampler, heap-report and slope/fit soak | -| Caches | Hits/writes/misses/refusals/evictions by bounded reason, absent layers excluded, zero traffic on actual hits | -| Authoring | Queue/cook/compile/reflect/translate/check/admit/upload/first-visible latency, variant demand and cache hits | - -Studio profile grid uses pass columns, resource rows, read/write/lifetime cells, -logical/physical alias IDs, declared/peak/allocated bytes and measured GPU time. -In-game overlay reads the same data; capture receipts pair images with graph, -profile, settings and measurement age. Explicit profile capture can export text -under build artifacts; this is not an unsolicited benchmark document. - -Measure shipped cost in release. Heap hooks compile out there, so use a named -diagnostic preset for heap cost and state the difference. Reports include GPU, -driver/backend, preset, scene/publication, world/view counts, material/variant -counts, resolution, quality, warm/cold cache and visible workloads. - -Experiments compare one and many cameras, 1/1,000/high material counts, small and -dense geometry, static/moving portals, transparent smoke, 4K pressure, streaming -bursts, world churn and hot reload. Bound measurement windows, warmups and seeds; -show distribution/spikes rather than only averages. Do not infer byte savings -from entity counts or physical overlap from scheduling waves. - -Preserve candidate priorities after correctness/residency foundations: stable -cascaded shadows, clustered lights with tight assignment, HZB funnel hardening, -texture compression/streaming/staging, mesh compaction/order, particle significance. -Bindless material slabs are a later measured step: descriptor arrays plus -material slab/slot in GPU data, dummy bindings, normalized samplers and limited -variants. Probe descriptor indexing/update behavior and actual limits; retain -bounded per-material binds on unsupported backends. - -### optimization acceptance and experiment protocol - -Each experiment names a bottleneck hypothesis, baseline, single changed factor, -quality/error policy and expected counter movement. Warm both variants, alternate -their run order, hold clocks/settings where practical, and report median/p95/p99 -plus worst relevant spikes. Add interaction runs after individual ablations: -two independent speedups may fight over bandwidth or residency when combined. - -Compare full-frame critical-path time and input-to-visible latency, not the sum -of overlapping GPU spans. An extra in-flight frame can raise throughput while -making controls feel slower. Bound frames in flight and record them with both -versions. Present waits and CPU/GPU idle stay visible instead of being removed -from results to make the optimized path look faster. - -| Gate | Exact or bounded condition | Evidence | -|---|---|---| -| Still scene, warmed versions | No unchanged instance/mesh/texture/material uploads or repacks; no compile or target creation for those layers | Traffic, rows/bytes visited, allocations and pipeline counters | -| Camera-only move | No unchanged shared-world uploads/extraction; view culling/history/shading may run | Fixed entity count with 1/2/8/32 active cameras | -| One entity/material edit | Work follows changed pages and declared dependents; upload amplification bounded | Dirty elements versus staged bytes/copy commands, per-view redraw reasons | -| Shared asset across worlds | One immutable device asset per compatible content key, separate world state | Resident roots/allocations and reference-retirement checks | -| Hidden UI/preview | No preview cook/render/readback; bounded warm state may remain | Owner activity counters and steady memory after close | -| Empty GPU workload | No unnecessary full-resource clear/sort/copy; only necessary count/reset/control work | Dispatch sizes, indirect counts and bytes touched | -| Small workload fallback | Optimization overhead does not force the large-scene algorithm | Serial/simple-path crossover measurements | -| Burst or pressure | Allocation + staging + in-flight replacement remain within configured ceilings | High-water/queue-age/refusal metrics and no corrupted images | -| Approximate mode | Declared error/quality and temporal lag satisfied at the reported settings | Image/temporal fixtures, raw tracer samples and quality-matched timing | -| Device portability | Selected implementation is supported and faster or uses its documented fallback | Per-backend exact-path captures and timing, not only capability metadata | - -Set numerical time/regression budgets from the P0 baseline and project frame -target during implementation. Exact zero-work gates above do not need a guessed -millisecond limit. For nonzero cost, keep acceptance thresholds and measurement -variance in the artifact; no unspecified claim that an optimization is faster. - -Tune compute with measured workgroup shape, register spills, shared-memory use, -occupancy and memory transactions where tools expose them. Higher occupancy is -not itself a speedup; avoid specialization per device model unless stable wins -justify extra variants. Keep a small validated profile set and portable fallback. -[Occupancy tradeoffs](https://gpuopen.com/learn/occupancy-explained/). - -Estimate attachment and queue bytes from actual formats/extents/counts before -testing, then distinguish estimates from measured device traffic and logical -allocation. Unified-memory and discrete devices need separate comparisons. -Sampling/profiling overhead gets an instrumented versus uninstrumented check; -never add readbacks or per-entity logging to the hot path just to count savings. - -## 19. example pipelines and review scenes - -Every example is an authored, saved PipelineDocument/PipelineSet plus a runnable -scene in `mono.engine/examples`, loaded through the same Studio/runtime path. -No demonstration may call a hidden renderer outside the graph. Each has fixed -capture inputs, expected tier behavior and a release profiling recipe. - -| Example | Graph shape and parameters | What review must see | -|---|---|---| -| Standard PBR lab | Shared residency/shadows -> per-view cull/LOD/G-buffer -> AO/GI/light/sky -> surfaces/transparency -> post/output | Seven maps alone/together, metal/roughness sweep, HDR emission, lighting channels | -| Anime | Lit scene -> palette (initial 4 bands, dither off) -> depth/normal edges (1px) -> masked ink mix -> authored ramp/output | Stable hard bands and fine outlines; optional wide threshold/blur glare, not compulsory bloom | -| Cartoony | Lit scene -> 2 to 3 bands -> 2px edges/dilate -> saturation grade -> output | Broad outlines and flat colours; AO-only lighting profile as cheap-tier experiment | -| Drawing | Depth/normal edges + lit luminance -> hatch (scale/45-degree orientation/contrast) -> desaturate -> paper multiply -> output | Crisp silhouettes, multiple hatch densities and no needless HDR intermediates after conversion | -| Anime screencap | HDR lighting -> soft bloom -> grade -> light sharpen -> letterbox/vignette -> output conversion | Retained static composition; explicit tonemap placement prevents double conversion | -| Hybrid raytrace | Raster primary -> resident acceleration -> secondary ray reflection/shadow/GI -> denoise/composite -> output | Offscreen object reflected and occluding; comparison with raster/SSR fallback | -| Progressive path trace | Acceleration -> camera rays -> path integration -> accumulate/moments -> optional denoise -> tonemap | Diffuse/specular/emissive transport, sample count, convergence and immediate reset after edit | -| PortalSeams and existing non-Euclidean demo | Linked captures, portal-light transport, split geometry, physical crossing, recursive composition, bus-delivered destination images | The full sequence in §12: all-angle seams, actual humanoid-subject player cameras, cross-world walking and ownership | -| AA comparison | Same scene/camera, selectable None/MSAA/FXAA/SMAA/TAA/upscale graph | Thin edges, foliage, moving emissive geometry, cuts and native UI | -| Multi-world camera wall | Distinct worlds and repeated cameras per world, asset preview and portal views | All active cameras update in one frame; shared rows uploaded once | -| Editable packing lab | Quantization policy -> pack/upload -> atlas/mips -> draw/inspect | Error heatmaps, real byte counts, one-pixel edits and pressure fallback | -| Geometry detail lab | Four meshes/decimation/triangle-error/meshlet modes plus tessellation/displacement | Different view LODs, watertight transitions and unchanged physics mesh | -| Attached effects lab | Same cooked module on mesh/decal/particle/ribbon/UI/environment/surface view | Correct masks/order, shared shader residency and hidden no-work behavior | -| TornadoSim | Generic weather/particle/field/volume nodes driven by the Luau scene | Moving funnel, rain, tree bend, debris, lightning and meaningful hazard readout | - -Do not label unsupported Tier B/C tests passed because a default pipeline rendered -something. Assert the selected fallback graph and reason. New `palette`, `edges` -and `hatch` kinds require actual shaders; paper, ink and letterbox operations use -ordinary typed composite nodes rather than abusing diagnostic overlay state. - -### matched workload controls for the examples - -Each demo exposes a fixed reference configuration and separately named optimized -configurations, with the exact changed setting recorded. Keep content, camera -path, seed and quality equal for exact optimizations. Approximate modes report -their resolution/sample/error differences alongside speed and bytes. - -Add scripted phases to the camera wall and packing lab: warm still, camera move, -single entity edit, content arrival, many simultaneous edits, hide/show, world -unload and pressure recovery. PortalSeams adds tiny-to-full-screen aperture growth; -tracers add static accumulation and scene changes; TornadoSim adds low/high -particle fill and lightning invalidation. The same scene drives correctness and -cost checks, with readbacks disabled in timed windows. - -Prewarm only resources the active demonstration demands. Loading the demo browser -must not allocate every example's 4K images, BVHs and histories. Shared fixtures -reuse immutable assets; each scene's resident state retires when it closes. -The demo selector shows active tier and approximation mode so a fallback cannot -masquerade as the optimized feature being reviewed. - -## 20. implementation order and deletion gates - -Phase names are proposed work units, not version promises. Implement all requested -features through these phases; measured candidates retain explicit acceptance -criteria. A failed prerequisite does not justify marking the rest complete. - -| Phase | Dependencies | Concrete changes | Completion gate | -|---|---|---|---| -| P0: baseline/contracts | Plan review | Read affected module policies; verify old done claims; inventory hidden rendering and shader consumers; settle reviewed compiler policy; freeze graph/material/portal/image fixtures; reconcile policy references | Current behavior classified by evidence, ownership/format/clip contracts written, baseline failures named | -| P1: image harness | P0 | Extend real-device fixtures, per-pass capture, analytic probes, comparison policy, failure bundles and `just render-check` | Deliberate projection/depth/colour/resource faults fail for the right reason; missing device cannot pass | -| P2: graph-owned frame/residency | P0, P1 | Move preparation/uploads/simulation/capture/UI into real node execution; explicit side effects/resources; retain stable world/view slots; parallel collector and batched submission | Serial/parallel same output; all active views update; static worlds have zero duplicate uploads; delete old frame orchestrator | -| P3: shader cook and interfaces | P0, P1, graph contracts | Separate runtime schemas from compiler targets; cook bundles/variants, reflect contracts, validate/translate, signed delivery and complete keys | Packaged authored shader works through cooked loading; supported backends pass bindings/images; policy prerequisites satisfied | -| P4: materials and attachment data | P2, P3 | Typed material definitions/instances, samplers, capability policy, per-item attachments, VM/save/replication integration and resident rows | Legacy content uses one resolver; per-item changes update data only; every visual family has tested attachment semantics | -| P5: compositor and Studio authoring | P3, P4 | Typed palette/groups/material graph lowering, inspectors, async cook previews, undo/redo and hidden-work gates | Save/load/cook/run round trip; stale/failed cook cannot replace valid preview; no UI-thread compile hitch | -| P6: lighting/colour/post/AA | P1 to P4 | PBR contracts, HDR order, dynamic AO/GI baseline, stable shadows/clusters, post shaders, velocity/history and AA subgraphs | Numeric energy/colour and motion fixtures pass; every mode has actual backend or explicit tier fallback | -| P7: packing/streaming/geometry | P2 to P4 | Quantization components/codecs, editable dirty updates, mip/texture pressure/atlas, four LOD modes, decimation, meshlets, tessellation/displacement | Bounded memory and error; no culling holes; per-camera GPU LOD; physical mesh unaffected by visual state | -| P8: portal completion | P1, P2, P4, P6; physics/world work | Shared seam math, all-angle clipping/proxies, light transport, HDR captures, bus/job image exchange, physical overlap, world transfer and humanoid-subject camera continuity | Numeric ownership/contact, direct-view image comparisons and inspected player/object crossing sequences; existing non-Euclidean demo fixed; no missing geometry, stale other-side image or doubled lighting/body | -| P9: tracing | P3, P4, P6, geometry contract; P8 for portal rays | Port/build acceleration and hybrid/path nodes, accumulation/reset, denoise and capability fallback | Offscreen intersection and statistical convergence; no fake tracer label; portal-ray behavior consistent | -| P10: weather/effects and scene producers | P2, P4, P6 | Explicit particle/environment nodes, generic field/volume work proven by TornadoSim; retained chunk render-input candidates | Script and visual gates pass; bounded particle/volume cost; no duplicate CPU simulation | -| P11: examples and portability | Relevant feature phases | All §19 documents/scenes, native handler command adapter, all backend/tier image runs, active-camera and pressure profiling | Actual SPIR-V/MSL images, documented limits, no implicit unsupported features | -| P12: remove migration paths | All functional gates | Remove shipped source compilation/translation after approval, duplicate layouts/resolvers/old pass lists; finish checks, fuzz/soak and documentation | One supported path per responsibility, packaged cooked-only content, bounded retirement and complete evidence | - -P6/P7/P8/P9 contain substantial work and can be split into smaller reviewed -changes while preserving their gates. Shader cook work must not delay fixing -existing image defects that P1 can reproduce safely; temporary compatibility -adapters have named removal in P12, not permanent second owners. - -### optimization work travels with each phase - -| Phase | Optimization deliverable added to its functional gate | -|---|---| -| P0 | Measure bytes visited, update causes, camera amplification and total memory; classify exact versus approximate modes | -| P1 | Reusable fixtures and bounded async captures; differential cached/uncached and aliased/unaliased image checks | -| P2 | Revision/page-driven preparation, dense execution plans, world sharing, safe acknowledgements and small-input serial fallback | -| P3 | Content-keyed single-flight cooking, narrow invalidation and bounded pipeline prewarm; cold/warm evidence | -| P4 | Split uniform/descriptor/module keys, shared packed values, GPU policy masks and active effect worklists | -| P5 | Layout-only edits free of runtime rebuilds; hidden previews idle; legal expression/kernel fusion with debug materialization | -| P6 | Demand-driven attachments, clustered lists, conservative shadow/AO/GI cache invalidation and quality-matched post/AA ablations | -| P7 | Consumer-specific mesh streams, honest CPU/upload/device packing costs, all-consumer streaming demand and bounded relocation | -| P8 | Aperture-first traversal, pixel budgets, shared destination inputs and correct moving-seam physics | -| P9 | Shared mesh acceleration, bounded GPU ray queues, equal-sample kernel comparisons and radiance-history policy | -| P10 | Active-block dispatch, particle fill controls, density/lighting split and border-aware producer invalidation | -| P11 | Integrated multi-feature contention tests across supported devices; latency and memory alongside throughput | -| P12 | Remove losing experimental implementations or retain only justified capability/scale fallbacks; no abandoned alternate owner | - -Build the common change/residency contracts before tuning each feature's kernel. -Prototype kernel fusion, bindless, wavefront queues, sparse volume layouts and -async overlap behind the same node interfaces; use the measured winner for each -supported class. Rejecting a losing optimization does not cancel its feature: -retain the correct simpler implementation and its full functional gate. - -### deletion ledger - -| Existing path | Replacement | Delete when | -|---|---|---| -| Product round-robin/one-view rendering orchestration | Active requests plus batch executor | Same-frame all-view output and lifecycle tests pass | -| `Begin` doing hidden CPU node work then reporting spans | Scheduled preparation nodes | Disabling/reordering nodes changes actual work with valid contracts | -| Upload outside resource declarations | World residency and delta nodes | Dirty-range, in-flight acknowledgement and zero-traffic tests pass | -| Hidden shadow/portal/particle/environment/post calls | Registered families with explicit resources/side effects | Image and failure-lifecycle parity exists for each family | -| Hardcoded material parameter/binding switches | Canonical declarations/reflection and one resolver | Legacy fixtures plus both VMs and all techniques pass | -| Inline/source-only packaged nodes and runtime ShaderScript compile | Cooked module references; Studio worker authoring | Reviewed policy updated, packaging/link/staging checks prove source-free client | -| Runtime authored SPIR-V-to-MSL translation | Published checked MSL payload | Supported MSL backend runs packaged content | -| CPU mirror of selected LOD/visibility/visual particles | GPU world inputs plus view outputs | Device/reference parity and explicit no-compute fallback exist | -| Temporary conversion shims | Supported-version canonical reader | Declared support window ends; migration fixtures retained for supported input | - -## 21. final implementation acceptance - -Completion requires evidence for every R01 to R17 item and each phase gate. -Documentation, catalogue entries, green unrelated tests and screenshots of one -frame cannot substitute for behavior across the named scope. - -- One graph controls all render work and explains why each resource exists. -- Active world/camera collection is complete; preparation is safely parallel and - vectorizable; record/submit remains owner-thread; cameras share residency. -- Per-instance capabilities, visual deformation, culling and LOD use GPU state - with no per-frame decision readback; physics/authored state remains canonical. -- Every visual family supports declared attached shader/effect stages with masks, - active residency, bounded resources and correct camera/world policy. -- Material/shader authoring, save, VM bindings, cooking, publication, load, - fallback, hot reload and retirement all use the canonical contracts. -- PBR, colour/alpha, lighting, AO/GI, shadows, environment, post and AA have real - image and numeric proof on the supported tier/backend matrix. -- Hybrid and progressive tracing intersect real geometry and demonstrate their - transport, convergence and invalidation rather than falling back invisibly. -- Portals pass projection, clipping, light transport, geometry overlap, physics - ownership and cross-world transfer tests plus an inspected moving demo. -- Editable quantization covers every requested format family; storage bytes and - error are measured; 4K streaming/atlas pressure is bounded and visually correct. -- Authored four-level LOD, automatic decimation, projected-error/meshlet work, - tessellation and visual-only displacement have explicit supported paths. -- Every example in §19 loads through normal authoring/cook/runtime and has a - fixture/profile entry. TornadoSim retains honest first-slice limits. -- Release/dev/server builds, appropriate full test gates, `[gpu]` backend tests, - shader/architecture/source/binding/component/type checks and relevant fuzz/soak - runs pass. Report unexecuted hardware checks as missing evidence. -- Release profiling names workload and settings, shows real traffic/bytes and - regression comparisons; caches and retirement remain bounded after churn ends. -- Replaced paths are deleted under the ledger; docs/policy and generated metadata - match the final code. No unrelated roadmap items get marked done. - -### optimization completion proof - -Every implemented cache has tested reuse and invalidation, an owner/lifetime, -bounded storage and a failure retry. Every GPU migration accounts for host copies, -staging, resident output and per-view scratch. Every batching/fusion change keeps -authored order, projection, colour and resource hazards correct. - -P0/P11 evidence must show both small and large workloads, cold/warm behavior, -steady-state and edit bursts, device pressure and supported fallback paths. -Report regressions explicitly; do not exchange longer latency, stale pixels or -lower quality for a faster counter without a named accepted mode. - -The §18 gate table and §20 optimization phase table are required alongside the -original functional proof. A source-level argument, a zero-upload counter or a -single faster kernel is insufficient evidence for a complete optimized renderer. -This refinement remains a plan; no optimization measurements are claimed yet. - -This planning deliverable is complete when the source migration map below covers -every old section, all attached checklist items have implementation and proof -requirements, source documents are removed only after porting, and references -lead here. Engine gates above remain uncompleted until implementation review. - -## 22. source migration map - -The following map records coverage, not inherited implementation status. Numeric -research starting points are experiments; claimed speedups, old fixed row sizes -and backend assumptions are not promises. Technical corrections in this plan -override stale research prose while retaining the problem and proposed approach. - -### former render pipeline document - -| Former sections | Destination | -|---|---| -| Status; 1.1 layers; 1.2 authoring chain | §0, §2, §3 | -| 1.3 resources; 1.4 catalogue/editor | §3, §8 | -| 1.5 diagnostics/profile; 1.6 backend | §3, §8, §18 | -| 1.7 exact default order; 1.8 residency/transfer | §2, §4, §10 | -| 2 invariants | §3, §4, §5, §12, §15 | -| 3.1 registration; 3.2 custom nodes | §3, §8 | -| 3.3 DeviceCaps/ShaderCapabilities | §6, §7 | -| 3.4 stages/optimization/caches | §3, §7, §18 | -| 3.5 data movement/quantization | §3, §4, §13, §14 | -| 3.6 optimized Tier A/B/C default | §6, §10, §19, §20 | -| 4 shader authoring | §0 policy conflict, §7, §8, §15 | -| 5.1 Anime; 5.2 Cartoony; 5.3 Drawing; 5.4 Anime screencap | §19 | -| 6.1 existing signals; 6.2 GPU time; 6.3 introspection; 6.4 switches; 6.5 heap | §18 | -| 7 completed and remaining modularity stages | §2 verification requirement, §3, §7, §20 | - -### former optimization document - -| Former sections/candidates | Destination | -|---|---| -| Cascaded exponential shadows; stable frusta | §9 shadow table | -| Filter menu; depth/normal bias; point shadow cubes | §9 shadow table | -| Shadow update scheduling; atlas/tile reuse | §9 shadow table | -| Forward+ clusters; tight light assignment | §9 clustered lighting | -| Two-phase Hi-Z hardening; CPU software occluders; indirect batch sets | §9 visibility | -| Bindless material slabs/pipeline counts | §18, §7 | -| Buffer slab allocation; instance/vertex quantization | §4, §13 | -| Smallest indices; triangle order/shared-vertex LOD; meshlets; LOD refinements | §13 | -| Universal compressed interchange; flipbook mips; mip residency/eviction; staging rings | §14 | -| Particle blocks; split arrays/curve tables; seeded emission; GPU step/CPU reference | §16 | -| Blend partition/depth buckets; soft particles; significance; curl fields; trail recording | §16 | -| Padded greedy meshing; baked AO/triangulation; derived chunk scheduler | §17 | -| Ticketed generation; hysteresis streaming; region files; chunk phase DAG | §17 | -| Transient aliasing/barriers; async compute overlap; post-chain cost | §3, §10, §18 | -| Profiling contract and six-item priority ranking | §18 | - -### former materials and shaders document - -| Former sections | Destination | -|---|---| -| Status/product goal/current foundation | §0, §2, §7 | -| Non-negotiable rules/ownership/layer cuts | §3, §7, §15 | -| Stable identities/definitions/instances/types/device packing | §7 | -| Texture declarations/samplers/editable textures | §7, §13, §14 | -| Source model/cooked bundles/interface matching/variants | §7 | -| Device/shader caps and selection order | §6, §7 | -| Dependency graph/cook stages/incremental keys/containers | §7 | -| Material/shader editors/hot reload/shipping boundary | §7, §8, §15 | -| CPU caches/material residency/shader pipeline keys/budgets | §7, §14, §18 | -| Graph material techniques/authored shaders/preview visibility | §6, §7, §8 | -| Runtime API/authoring API/binding generation | §7, §15 | -| Save/replication/hostile content limits | §15 | -| Migration and six work phases | §20 | -| Headless/integration/image/fuzz/soak tests | §5, §7, §15, §21 | -| Profiling/budgets | §18 | -| Non-goals/completion | §0 reconciles newly requested visual graphs/tracing/packing; §15 preserves trust and bounded interfaces; §21 | - -### TornadoSim and attachment - -All TornadoSim source-scope rows, existing engine doors, first demo slice, -first-pass exclusions, proof gates and evidence-triggered engine doors are in -§16. Its gameplay plan remains linked rather than deleted. R01 to R14 correspond -in order to the fourteen attached checklist lines; R15/R16 cover consolidation. - -### section-by-section optimization traceability - -The additional optimization review is R17. Its coverage stays local to each -section so future implementation does not need a competing optimization backlog. -Use this index when reviewing completeness; update the owning section and gate -together when an experiment changes the chosen implementation. - -| Sections reviewed | Optimization refinement | -|---|---| -| §0, §1 | Optimization order, exact/approximate classification and cost/proof mapping | -| §2 | Current full-span signature work and targeted baseline measurements | -| §3 | Incremental semantic compilation, dense execution, liveness, safe concurrent aliasing and measured async schedules | -| §4 | Mutation pages, shared snapshots, hot/cold GPU fields, bounded view storage and granular acknowledgements | -| §5 | Reused fixtures, bounded capture work and independent differential oracles | -| §6 | GPU policy composition, masked tile work, dispatch batching and conservative demand | -| §7 | Split material caches, shared values, single-flight cook/load and pipeline prewarm | -| §8 | Incremental canvas, selective previews, legal shader/kernel fusion and intermediate materialization | -| §9 | Lighting attachment demand, shadow footprints, compact clusters, transport-aware caches and culling crossovers | -| §10 | Full-image bandwidth, MSAA stores/resolves, correct temporal reuse and bounded partial damage | -| §11 | Shared acceleration, coherent bounded ray queues, sampling-distribution reuse and honest convergence | -| §12 | Aperture/pixel budgets, destination sharing, exact capture keys and moving-seam constraints | -| §13 | Consumer-specific streams, end-to-end packing cost, local quantization and bounded defragmentation | -| §14 | Device-wide pressure arbitration, staging contract, request deduplication and atlas tradeoffs | -| §15 | Cached immutable validation, semantic-preserving delta coalescing and serialization work | -| §16 | Active simulation work, particle fill/ordering, volume caching and one storm authority | -| §17 | Shared artifacts, precise border invalidation, bounded scratch and incremental I/O | -| §18 | Ablations, full-frame/latency gates, occupancy tuning and exact zero-work requirements | -| §19 | Matched demo workloads, edit/pressure phases and demand-driven loading | -| §20, §21 | Phase ownership, removal of losing paths and end-to-end acceptance | -| §22 | This traceability index, keeping refinements attached to the source requirements | diff --git a/docs/future-work/REVISIT_IDEAS.md b/docs/future-work/REVISIT_IDEAS.md index 96df840a3..f50db7185 100644 --- a/docs/future-work/REVISIT_IDEAS.md +++ b/docs/future-work/REVISIT_IDEAS.md @@ -1,6905 +1,56 @@ - -# gpt 5.6 sol in browser with ROADMAP.md file - -### Core Engine / ECS - -* [ ] **Entity lifecycle system**: spawn/despawn/deferred destruction, pooling, orphan handling -* [ ] **Archetype/query optimizer**: cached ECS queries, change filters, parallel query execution -* [ ] **Component change tracking**: dirty bits/version counters so systems only process changed data -* [ ] **Entity references/handles**: generation-safe references instead of raw entity IDs -* [ ] **World snapshots**: serialize/restore an entire world state -* [ ] **World cloning**: instant-ish duplicate world for testing, previews, server simulation -* [ ] **Rollback/snapshot system**: useful for networking and deterministic simulation -* [ ] **Fixed-timestep simulation**: independent simulation/render frequencies -* [ ] **System dependency graph**: explicitly declare `before/after`, parallelize independent systems -* [ ] **Frame scheduler**: CPU jobs, GPU jobs, async jobs and synchronization points represented together -* [ ] **Engine tick phases**: Input → Simulation → Physics → Animation → Replication → Render preparation → Render -* [ ] **Determinism mode**: detect nondeterministic simulation and optionally enforce deterministic ordering -* [ ] **Hot-reloadable components/systems** - -This would complement your existing batched-compute/job-system work particularly well. - ---- - -## Performance / Profiling - -You have profiling mentioned, but I'd make **performance tooling itself a first-class engine feature**. - -* [ ] **Built-in profiler** - - * CPU timeline - * GPU timeline - * ECS systems - * render passes - * jobs - * network - * memory -* [ ] **Live ECS statistics** - - * entity count - * component counts - * archetype sizes - * query timings -* [ ] **GPU residency inspector** - - * resident bytes - * upload/download traffic - * dirty regions - * update frequency -* [ ] **PCIe traffic monitor** -* [ ] **CPU ↔ GPU synchronization visualizer** -* [ ] **Frame debugger** - - * inspect every render pass - * resources - * barriers - * shaders - * draw/dispatch calls -* [ ] **Memory visualizer** - - * CPU allocations - * GPU allocations - * fragmentation - * per-component memory -* [ ] **Asset memory profiler** -* [ ] **Network bandwidth profiler** -* [ ] **Performance budgets** - - * e.g. physics < 2 ms - * scripts < 3 ms - * render submission < 1 ms -* [ ] **Automatic performance regression tests** - -The GPU-resident work in your roadmap makes this especially valuable. - ---- - -# World / Scene System - -I'd significantly expand this. - -* [ ] **Scene streaming** -* [ ] **World partitioning** -* [ ] **Spatial database** - - * BVH - * octree - * grid - * loose octree -* [ ] **Scene hierarchy** -* [ ] **Subscenes** -* [ ] **Scene references** -* [ ] **Additive scene loading** -* [ ] **Scene instancing** -* [ ] **World layers** -* [ ] **World regions** -* [ ] **Streaming priorities** -* [ ] **Distance-based activation/deactivation** -* [ ] **Server-side interest management** -* [ ] **Persistent world chunks** -* [ ] **World origin rebasing** -* [ ] **Floating-origin support** -* [ ] **Large-world coordinates** - -That last group becomes important if you're serious about the Space Engineers-style gigantic-world demos already mentioned in the roadmap. - ---- - -# Networking - -You have WebSockets and platform connection keys, but there's a **big networking layer** missing. - -I'd add: - -* [ ] UDP transport -* [ ] Reliable/unreliable channels -* [ ] Packet fragmentation/reassembly -* [ ] Packet compression -* [ ] Delta compression -* [ ] Entity replication -* [ ] Component replication -* [ ] Replication priorities -* [ ] Replication frequency -* [ ] Network ownership -* [ ] Client prediction -* [ ] Server reconciliation -* [ ] Lag compensation -* [ ] Interpolation -* [ ] Extrapolation -* [ ] Network rollback -* [ ] Interest management -* [ ] Spatial replication -* [ ] Network object IDs -* [ ] Remote events/RPC -* [ ] Remote functions -* [ ] Network profiler -* [ ] Packet-loss simulation -* [ ] Latency simulation -* [ ] Bandwidth throttling -* [ ] Connection migration -* [ ] Server browser -* [ ] Matchmaking abstraction - -I'd probably make this its own major milestone rather than burying it under miscellaneous infrastructure. - ---- - -# Asset System - -You have CDN/world export/import, but a proper **asset database** would be extremely useful. - -* [ ] Asset dependency graph -* [ ] Asset GUIDs -* [ ] Asset versioning -* [ ] Asset hashing -* [ ] Asset deduplication -* [ ] Asset caching -* [ ] Import pipeline -* [ ] Import processors -* [ ] Import presets -* [ ] Asset reimport detection -* [ ] Asset dependency invalidation -* [ ] Asset bundles/packages -* [ ] Asset streaming -* [ ] Asset hot reload -* [ ] Asset thumbnails -* [ ] Asset metadata -* [ ] Asset validation -* [ ] Missing-reference detector -* [ ] Broken-asset detector -* [ ] Duplicate-asset detector -* [ ] Dependency viewer -* [ ] Asset migration system - -And particularly: - -**Asset cooking/build pipeline** - -```text -Source Asset - ↓ -Importer - ↓ -Processor - ↓ -Optimizer - ↓ -Compressor - ↓ -GPU-ready representation - ↓ -Package / CDN -``` - -That would make your Blender/Roblox/Unity/RPG Maker import ambitions much cleaner. - ---- - -# Input - -You already have `UserInputService` and `ContextActionService`, but I'd go beyond Roblox compatibility. - -* [ ] Input abstraction layer -* [ ] Keyboard/mouse -* [ ] Controller -* [ ] Touch -* [ ] Pen/tablet -* [ ] Gamepad remapping -* [ ] Input contexts -* [ ] Input chords -* [ ] Input buffering -* [ ] Input recording/replay -* [ ] Input visualization -* [ ] Input action assets -* [ ] Per-player input maps -* [ ] Device detection -* [ ] Deadzone configuration -* [ ] Haptics -* [ ] Controller vibration - -**Input recording/replay** is particularly useful for automated gameplay tests. - ---- - -# AI Framework - -You have pathfinding, but I think the engine could have a **general AI framework**. - -* [ ] Navmesh generation -* [ ] Dynamic navmesh -* [ ] Navmesh streaming -* [ ] Hierarchical pathfinding -* [ ] Flow fields -* [ ] Crowd simulation -* [ ] Steering behaviors -* [ ] Behavior trees -* [ ] Utility AI -* [ ] State machines -* [ ] GOAP -* [ ] Blackboard system -* [ ] Perception system -* [ ] Vision cones -* [ ] Hearing -* [ ] Threat detection -* [ ] Squad AI -* [ ] Formation AI -* [ ] Cover selection -* [ ] Tactical positioning -* [ ] AI LOD -* [ ] AI sleeping/deactivation -* [ ] Multi-agent job scheduling - -Your advanced climbing/pathfinding idea would fit nicely as a capability-based navigation system: - -```text -AgentCapabilities - ├─ Walk - ├─ Jump - ├─ Climb - ├─ Swim - ├─ Fly - ├─ Crawl - └─ OpenDoors -``` - -Then navigation isn't just "find path"; it's **find path satisfying capabilities**. - ---- - -# Physics - -Your collider/constraint work could eventually become a much more complete physics layer. - -* [ ] Broadphase -* [ ] Narrowphase -* [ ] Continuous collision detection -* [ ] Sleeping -* [ ] Physics islands -* [ ] Trigger volumes -* [ ] Collision layers/masks -* [ ] Material system -* [ ] Friction/restitution -* [ ] Character controller physics -* [ ] Ragdolls -* [ ] Vehicle physics -* [ ] Rope/chain physics -* [ ] Soft bodies -* [ ] Cloth -* [ ] Destruction -* [ ] Fracturing -* [ ] Buoyancy -* [ ] Wind forces -* [ ] Physics constraints editor -* [ ] Physics debug renderer - -And eventually: - -**GPU physics / batched physics** - -for huge numbers of particles, debris, projectiles, crowds, etc. - ---- - -# Audio - -You have the future DAW idea, but the actual runtime audio system deserves its own section. - -* [ ] 3D positional audio -* [ ] Distance attenuation -* [ ] Doppler -* [ ] Occlusion -* [ ] Reverb zones -* [ ] Audio buses -* [ ] Audio mixers -* [ ] DSP effects -* [ ] Low-pass/high-pass -* [ ] Compressor -* [ ] EQ -* [ ] Spatial audio -* [ ] Ambisonics -* [ ] Environmental audio -* [ ] Audio streaming -* [ ] Audio streaming cache -* [ ] Audio asset compression -* [ ] Music system -* [ ] Adaptive music -* [ ] Audio snapshots -* [ ] Footstep material system -* [ ] Voice chat abstraction - ---- - -# Testing - -This is one of the biggest things I'd add. - -You have security/fuzz testing and rendering tests, but I'd create a full **Engine Test Framework**. - -* [ ] Unit test runner -* [ ] ECS tests -* [ ] Physics tests -* [ ] Rendering tests -* [ ] Network tests -* [ ] Serialization tests -* [ ] Script tests -* [ ] Asset tests -* [ ] Determinism tests -* [ ] Multiplayer simulation tests -* [ ] Golden-image rendering tests -* [ ] Performance tests -* [ ] Memory tests -* [ ] Fuzz testing -* [ ] Stress testing -* [ ] Soak testing -* [ ] Automated gameplay tests -* [ ] Headless engine mode -* [ ] CI test runner -* [ ] Test recordings/replays - -A really powerful feature would be: - -### "Record → Replay → Compare" - -```text -Gameplay - ↓ -Record inputs + world events - ↓ -Replay deterministically - ↓ -Compare: - WorldState - ECS state - Render output - Network state -``` - -That would make debugging enormously easier. - ---- - -# Debugging - -Beyond the debugger itself: - -* [ ] Time-travel debugger -* [ ] Frame rewind -* [ ] World-state snapshots -* [ ] Entity history -* [ ] Component history -* [ ] Network packet inspection -* [ ] RPC inspector -* [ ] Remote debugger -* [ ] Live variable editing -* [ ] Live component editing -* [ ] Entity watch -* [ ] Conditional breakpoints -* [ ] Data breakpoints -* [ ] Event breakpoints -* [ ] Exception breakpoints -* [ ] Script execution profiler -* [ ] Lua/JS VM profiler -* [ ] "Why is this entity here?" inspector - -The last one could be surprisingly useful: - -```text -Entity 1837 - -Created by: - SpawnSystem - -Prefab: - Enemy.Orc - -Components: - Transform - CharacterController - Health - AIController - -Currently modified by: - PhysicsSystem - AISystem - AnimationSystem -``` - ---- - -# Editor - -Your Studio replacement is already extensive, but I'd add some more **power-user editor functionality**: - -* [ ] Command palette -* [ ] Global search -* [ ] Search objects by property -* [ ] Search components -* [ ] Multi-property editing -* [ ] Multi-object inspector -* [ ] Favorites -* [ ] Bookmarks -* [ ] Recent objects -* [ ] Recent assets -* [ ] Scene bookmarks -* [ ] Camera bookmarks -* [ ] Editor layouts/profiles -* [ ] Workspace presets -* [ ] Multi-monitor layouts -* [ ] Tabs that can become windows -* [ ] Floating dock widgets -* [ ] Editor scripting -* [ ] Editor macros -* [ ] Action history -* [ ] Undo/redo transactions -* [ ] Transaction inspector -* [ ] Dependency visualization -* [ ] Reference finder -* [ ] "Find all usages" -* [ ] Asset dependency graph - -### Particularly: Command Palette - -Something like: - -```text -> Add Component -> Create Script -> Find Asset -> Focus Selection -> Toggle Wireframe -> Open Render Graph -> Profile Frame -> Spawn Entity -> Run World -> Export World -``` - -This is a massive productivity multiplier. - ---- - -# Prefab / Template System - -I don't see a proper prefab system in the roadmap. - -I'd definitely add: - -* [ ] Prefabs -* [ ] Nested prefabs -* [ ] Prefab overrides -* [ ] Prefab variants -* [ ] Prefab inheritance -* [ ] Prefab diff -* [ ] Prefab apply/revert -* [ ] Prefab dependency graph -* [ ] Prefab editing mode -* [ ] Runtime prefab instantiation -* [ ] Prefab version migration - -This would pair extremely well with your ECS/Roblox Instance shim. - ---- - -# Serialization / Migration - -Your world format is getting substantial. Add: - -* [ ] Schema versioning -* [ ] Automatic migrations -* [ ] Component versioning -* [ ] Backwards compatibility -* [ ] Forward compatibility where possible -* [ ] Binary serialization -* [ ] Streaming serialization -* [ ] Incremental saves -* [ ] Autosave -* [ ] Crash recovery -* [ ] Save corruption detection -* [ ] Save diff -* [ ] Save merge -* [ ] World patch files - -Especially useful: - -```text -world.aworld -world.aworld.patch -world.aworld.patch2 -``` - -rather than rewriting huge worlds for every tiny change. - ---- - -# Reflection / Metadata - -You're already effectively building reflection through components, tags and Roblox properties. - -I'd formalize it. - -* [ ] Runtime reflection API -* [ ] Property metadata -* [ ] Component metadata -* [ ] Enum metadata -* [ ] Serialization metadata -* [ ] Editor metadata -* [ ] Replication metadata -* [ ] Security metadata -* [ ] Quantization metadata -* [ ] Network metadata -* [ ] Inspector metadata -* [ ] Deprecation metadata -* [ ] Experimental metadata - -Then something like: - -```lua -property("Health", { - type = "float32", - replicated = true, - quantize = "uint16", - editor = { - min = 0, - max = 1000 - } -}) -``` - -becomes possible. - -This could unify several seemingly separate roadmap items. - ---- - -# Security / Sandboxing - -Your script capabilities item is important enough to expand: - -* [ ] Capability-based permissions -* [ ] VM resource limits -* [ ] CPU execution budgets -* [ ] Memory budgets -* [ ] File-system sandbox -* [ ] Network sandbox -* [ ] Plugin sandbox -* [ ] Server/client separation -* [ ] Trusted/untrusted asset distinction -* [ ] Script signing -* [ ] Plugin signing -* [ ] Permission prompts -* [ ] Capability audit log -* [ ] Restricted API profiles -* [ ] Crash isolation - ---- - -# Procedural Generation - -Beyond terrain: - -* [ ] Procedural meshes -* [ ] Procedural materials -* [ ] Procedural textures -* [ ] Procedural foliage -* [ ] Procedural buildings -* [ ] Procedural roads -* [ ] Procedural caves -* [ ] Procedural planets -* [ ] Procedural weather -* [ ] Procedural biome system -* [ ] Seeded generation -* [ ] Generation graphs -* [ ] Deterministic generation -* [ ] Generation caching -* [ ] Background generation workers - -This would fit your node-based philosophy extremely well. - ---- - -# Environment System - -I'd make environment its own subsystem: - -* [ ] Day/night cycle -* [ ] Sun/moon -* [ ] Stars -* [ ] Atmosphere -* [ ] Clouds -* [ ] Weather -* [ ] Rain -* [ ] Snow -* [ ] Fog -* [ ] Wind -* [ ] Lightning -* [ ] Volumetrics -* [ ] Water -* [ ] Ocean simulation -* [ ] Waves -* [ ] Underwater rendering -* [ ] Weather zones -* [ ] Dynamic sky - -Some of this overlaps with your render roadmap, but the **simulation/environment layer** should be separate from the renderer. - ---- - -# Build / Release System - -A proper engine needs a first-class build pipeline. - -* [ ] Project build system -* [ ] Development build -* [ ] Shipping build -* [ ] Dedicated server build -* [ ] Headless build -* [ ] Client-only build -* [ ] Asset cooking -* [ ] Shader cooking -* [ ] Script compilation -* [ ] Dependency stripping -* [ ] Feature stripping -* [ ] Platform-specific builds -* [ ] Build cache -* [ ] Incremental builds -* [ ] Build profiles -* [ ] Release channels -* [ ] Versioning -* [ ] Crash reporting -* [ ] Symbol management - ---- - -# Platform Layer - -You already have `MOBILE.md`, so I'd expand platform abstraction: - -* [ ] Windows -* [ ] Linux -* [ ] macOS -* [ ] Android -* [ ] iOS -* [ ] Web -* [ ] Steam Deck -* [ ] Console abstraction -* [ ] GPU capability detection -* [ ] CPU capability detection -* [ ] Dynamic quality scaling -* [ ] Device profiles -* [ ] Resolution scaling -* [ ] Battery/thermal awareness -* [ ] Mobile memory budgets - ---- - -# One particularly interesting thing: an Engine Graph - -Given how much of your roadmap is already becoming node-oriented, I'd seriously consider making **the engine itself graph-driven**. - -Not just rendering. - -You could have: - -```text - ┌──────────────┐ - │ Input Graph │ - └──────┬───────┘ - ↓ -┌───────────┐ ┌──────────────┐ -│ AI Graph │──────→│ World Graph │ -└───────────┘ └──────┬───────┘ - ↓ - ┌──────────────┐ - │ Physics Graph│ - └──────┬───────┘ - ↓ - ┌──────────────┐ - │Animation Graph│ - └──────┬───────┘ - ↓ - ┌──────────────┐ - │Render Graph │ - └──────────────┘ -``` - -And underneath: - -```text -Engine Graph - │ - ├── dependencies - ├── scheduling - ├── CPU jobs - ├── GPU jobs - ├── synchronization - ├── resource lifetime - └── profiling -``` - -That could become one of the **defining architectural features of Atomic Engine**, rather than it simply being "a Roblox-compatible engine with a good renderer." - ---- ---- ---- - -Yes. **This is a much better distinction**. You mean things that belong in the *engine/runtime/renderer itself*, rather than "add a grappling hook API." - -And I think the game you're remembering may be **Where Winds Meet** or **Crimson Desert**. Both are examples of the current generation of very large open-world games pushing massive environments, dense scenes, streaming, vegetation, atmospheric effects, etc. If you give me anything else you remember about the game, I can identify it. - -For Atomic Engine, I'd think about the feature set in terms of **"what does a modern AAA engine do automatically so the game developer doesn't have to?"** - -## The big AAA-engine mechanics you're missing - -Your existing LOD item is actually just one part of a much larger family: - -![Image](https://images.openai.com/static-rsc-4/4LjPJSiZ3m3s1r6wUsLlQZCYTnD5kR87qULOTJrDLRGjcVGD5TWsEEZNoztHn9jwWJB_cJz_DtqJN_CGoCKxlrVFV1DxO-4lPdhehPRpVriW3aObwOldAP8If8GjRbmq76UbsUwWLUlw66-rvI0MzQLUEhF85FsAVZ0mGUoLXzBVXXAaFe2CKafea1ka8XzY?purpose=fullsize) - -![Image](https://images.openai.com/static-rsc-4/WU2CTiO-kcY-g1NtbahuqtNucnXP2cU-fQNB8dj-IEr05f8p5WPNLPikPvL1XaeSTkzMsD_zao66-vmLkCtjZuY-KSEEUlGk1lrYyBBE-ya6yM0pvJ7v8Zv1fdhE7L8m6nZG32gNkwk15TK1alx6--3NcKcyZ7fjXZq_54D1JAOKikd6Pkoq--9C7g9w_077?purpose=fullsize) - -![Image](https://images.openai.com/static-rsc-4/HVpZEZ_KT7wJPA2UhAbrrbaihjzwxwBJTRn60GhcfkyBKuTEE4Uy9BNRnorlCljpQRJr1uRfjvsdQgul3-vYaBIHYWO6rlymXKp_xVxM5HPMin9YqwgOhut6djn2Lsv224iZBInKLjWOM9tYOcoOCpaetVATTUhv_t0Mh3edeOg2Ut0RmIpeG5Pmt6u53CtB?purpose=fullsize) - -![Image](https://images.openai.com/static-rsc-4/cNINqBM2cyqEIYsht__rmaI3j-Op24cldsbZ3nx4t57Nd8sVau_etYVxQyLUBO3AhQUDig3cPjU9CyAWPj2jIG1qWjGxDzpQCPVHCVNJVgrYhNNWjhuvgyRr4H8urViLNBWeAlSzW0JsYv4oxnqqjn18HrkcNHyHt6jMpISTrJeHNFBU-gTlVrmdy7Qr0XMY?purpose=fullsize) - -### 1. Virtualized Geometry / Nanite-like system - -You already have: - -> LOD: 4 different meshes, auto-decimate, smart triangle reduction - -I'd go considerably further. - -* [ ] **Virtualized geometry system** -* [ ] Meshlet generation -* [ ] Cluster hierarchy -* [ ] Hierarchical meshlet culling -* [ ] Screen-space geometric error -* [ ] Per-cluster LOD -* [ ] GPU-driven geometry selection -* [ ] GPU-driven indirect rendering -* [ ] Triangle-level/cluster-level occlusion -* [ ] Frustum culling -* [ ] Backface culling -* [ ] Small-object culling -* [ ] Distance-based culling -* [ ] Software rasterizer for occlusion -* [ ] Hardware occlusion queries where useful -* [ ] Runtime mesh streaming -* [ ] Virtualized geometry cache - -Instead of: - -```text -Mesh - ├── LOD0 - ├── LOD1 - ├── LOD2 - └── LOD3 -``` - -you effectively get: - -```text - Mesh - │ - Cluster tree - / | \ - Cluster Cluster Cluster - / | \ ... - meshlets - / | | \ - triangles... -``` - -Then the GPU decides **what geometry actually deserves to exist this frame**. - -That's the sort of technology that lets something look absurdly detailed while rendering huge environments. - ---- - -# 2. World streaming / World Partition - -This is arguably *more important than LOD* for a huge open world. - -* [ ] World partitioning -* [ ] Spatial cells -* [ ] Hierarchical streaming -* [ ] Async asset streaming -* [ ] Async mesh streaming -* [ ] Async texture streaming -* [ ] Async animation streaming -* [ ] Async audio streaming -* [ ] Priority-based streaming -* [ ] Camera-based streaming -* [ ] Gameplay-interest streaming -* [ ] Memory-budget-driven streaming -* [ ] Background streaming workers -* [ ] Streaming prefetch -* [ ] Streaming hysteresis -* [ ] Cell-level LOD -* [ ] Persistent world layer -* [ ] Runtime world generation -* [ ] World origin shifting - -Something like: - -```text - WORLD - │ - ┌──────────┼──────────┐ - │ │ │ - Cell Cell Cell - │ │ │ - ┌───┴───┐ ┌───┴───┐ ┌───┴───┐ - │ │ │ │ │ │ - LOD0 LOD1 ... -``` - -And cells automatically transition between: - -**unloaded → metadata → low-res → resident → high-detail** - -without the game having to manually manage it. - ---- - -# 3. Virtual Texturing - -This is a HUGE one for AAA rendering. - -* [ ] Virtual textures -* [ ] Texture page streaming -* [ ] GPU texture feedback -* [ ] Virtual texture cache -* [ ] Mip/page residency -* [ ] Runtime virtual texture -* [ ] Virtual texture blending -* [ ] Large landscape textures -* [ ] Streaming texture prioritization -* [ ] Texture memory budgets - -Instead of loading a 16K texture completely: - -```text -16K texture -████████████████████ -████████████████████ -████████████████████ -████████████████████ -``` - -you load only the pages actually visible: - -```text -████░░░░░░░░████░░ -████░░░░████████░░ -░░░░░░████░░░░░░░░ -``` - -This is especially useful for your eventual terrain system. - ---- - -# 4. Virtual Shadow Maps - -Another major AAA feature. - -* [ ] Virtual shadow maps -* [ ] Shadow page cache -* [ ] Per-page shadow resolution -* [ ] Dynamic shadow invalidation -* [ ] Cached static shadows -* [ ] Cascaded shadow fallback -* [ ] Contact shadows -* [ ] Per-object shadow settings -* [ ] Shadow LOD - -Instead of making one enormous shadow map, the engine allocates high-resolution shadow pages where they're actually needed. - ---- - -# 5. GPU-driven rendering - -This is probably **one of the most important additions I'd make to Atomic Engine.** - -* [ ] GPU-driven frustum culling -* [ ] GPU-driven occlusion culling -* [ ] GPU-driven LOD selection -* [ ] GPU-driven draw generation -* [ ] Indirect draw buffers -* [ ] Multi-draw indirect -* [ ] GPU scene -* [ ] GPU instance database -* [ ] GPU visibility buffers -* [ ] GPU-driven particle rendering -* [ ] GPU-driven foliage -* [ ] GPU-driven decals -* [ ] GPU-driven lights - -You are already moving toward GPU-resident instance state, so this is a very natural extension of your architecture. - -The goal is basically: - -```text -CPU - │ - │ "Here is the world" - ▼ -GPU Scene - │ - ├── cull - ├── LOD - ├── occlusion - ├── visibility - ├── sorting - └── draw generation - │ - ▼ - Render -``` - -The CPU doesn't need to tell the GPU: - -> "Render these 73,421 objects." - -It tells the GPU: - -> "Here's the world." - -The GPU figures out what matters. - ---- - -# 6. HLOD - -This is different from ordinary mesh LOD. - -**Hierarchical LOD** lets entire groups of objects become one representation. - -For example: - -```text -City - ├── Building - ├── Building - ├── Tree - ├── Lamp - ├── Car - ├── Fence - └── 4,000 props -``` - -At distance: - -```text -City HLOD - └── one optimized representation -``` - -I'd add: - -* [ ] HLOD generation -* [ ] HLOD clusters -* [ ] HLOD proxy meshes -* [ ] HLOD material baking -* [ ] HLOD impostors -* [ ] Runtime HLOD selection -* [ ] HLOD streaming -* [ ] HLOD hierarchy visualization - -This is **extremely useful for giant open worlds**. - ---- - -# 7. Impostors - -Another deceptively important AAA trick. - -* [ ] Billboard impostors -* [ ] 8-direction impostors -* [ ] 16-direction impostors -* [ ] Octahedral impostors -* [ ] 3D impostors -* [ ] Impostor baking -* [ ] Dynamic impostor generation -* [ ] Impostor transition dithering - -A distant tree doesn't need to remain a 20,000-triangle tree. - -It can become: - -```text -3D tree - ↓ -LOD - ↓ -impostor - ↓ -billboard - ↓ -culled -``` - ---- - -# 8. Foliage system - -AAA open worlds have a **specialized foliage renderer**, not 400,000 ordinary MeshParts. - -* [ ] Foliage instancing -* [ ] GPU foliage -* [ ] Procedural foliage placement -* [ ] Density maps -* [ ] Biome rules -* [ ] Foliage LOD -* [ ] Foliage HLOD -* [ ] Foliage impostors -* [ ] Wind simulation -* [ ] Interaction deformation -* [ ] Distance fading -* [ ] Cluster culling -* [ ] Foliage streaming -* [ ] Foliage collision LOD -* [ ] Grass cards -* [ ] Grass patch generation - ---- - -# 9. Decal system - -Not just `Decal` as a texture. - -A serious renderer needs: - -* [ ] Deferred decals -* [ ] Mesh decals -* [ ] Decal atlases -* [ ] Decal projection -* [ ] Decal blending -* [ ] Normal decals -* [ ] Roughness decals -* [ ] Emissive decals -* [ ] Runtime decal spawning -* [ ] Decal culling -* [ ] Decal LOD - -Bullet holes, dirt, blood, scorch marks, graffiti, damage, etc. can all use the same infrastructure. - ---- - -# 10. Advanced particle/VFX framework - -Your particle system roadmap is currently mostly feature parity. - -I'd add the **AAA architecture**: - -* [ ] GPU particle simulation -* [ ] GPU particle sorting -* [ ] Particle collision -* [ ] Particle depth collision -* [ ] Particle scene collision -* [ ] Particle lights -* [ ] Particle trails -* [ ] Particle ribbons -* [ ] Particle mesh rendering -* [ ] Particle flipbooks -* [ ] Particle sub-emitters -* [ ] Particle events -* [ ] Particle forces -* [ ] Vector fields -* [ ] Curl noise -* [ ] Fluid-like particle simulation -* [ ] GPU particle culling -* [ ] Particle LOD -* [ ] Particle simulation budgets - -Basically a Niagara-like architecture. - ---- - -# 11. Volumetric effects - -This is probably relevant to the **black mist ability** you remember. - -* [ ] Volumetric fog -* [ ] Volumetric clouds -* [ ] Local volumetric fog -* [ ] Volumetric particles -* [ ] Fog volumes -* [ ] Density volumes -* [ ] Light scattering -* [ ] God rays -* [ ] Volumetric shadows -* [ ] Height fog -* [ ] Fog injection -* [ ] 3D density textures -* [ ] Animated volume textures -* [ ] Ray-marched volumes - -Then a game can make something like: - -```text -Character - ↓ -black mist volume - ↓ -density field - ↓ -raymarch - ↓ -lighting/scattering - ↓ -temporal accumulation -``` - -without the game developer having to invent the renderer. - ---- - -# 12. Temporal rendering - -I'd absolutely add this. - -* [ ] TAA -* [ ] TSR-like temporal upscaling -* [ ] Temporal supersampling -* [ ] Motion-vector reconstruction -* [ ] Temporal denoising -* [ ] History buffers -* [ ] Reactive masks -* [ ] Disocclusion handling -* [ ] Temporal particle rendering -* [ ] Temporal volumetrics - -And eventually: - -* [ ] DLSS integration -* [ ] FSR integration -* [ ] XeSS integration - -These are **engine-level rendering systems**, not game features. - ---- - -# 13. Dynamic resolution - -Very useful for the sort of massive scenes you're aiming for. - -* [ ] Dynamic resolution scaling -* [ ] GPU-time target -* [ ] Per-pass resolution -* [ ] Temporal upscaling -* [ ] Resolution history -* [ ] Resolution budget -* [ ] Resolution scaling for reflections -* [ ] Resolution scaling for shadows -* [ ] Resolution scaling for volumetrics - -For example: - -```text -Target: 16.6 ms - -GPU = 12 ms -→ increase resolution - -GPU = 18 ms -→ decrease resolution - -GPU = 16 ms -→ hold -``` - ---- - -# 14. Lighting infrastructure - -You've got GI/path tracing planned, but I'd add the machinery around lighting. - -* [ ] Clustered lighting -* [ ] Forward+ -* [ ] GPU light culling -* [ ] Light grids -* [ ] Light clustering -* [ ] Shadow atlases -* [ ] Light importance ranking -* [ ] Light LOD -* [ ] Reflection probes -* [ ] Reflection probe blending -* [ ] Irradiance volumes -* [ ] Light probes -* [ ] Probe streaming -* [ ] Probe baking -* [ ] Runtime probe updates -* [ ] Screen-space reflections -* [ ] Hardware ray-traced reflections -* [ ] Distance field shadows - ---- - -# 15. Distance fields - -This is a really cool engine-level technology. - -Generate signed distance fields for meshes and use them for: - -* [ ] Distance-field ambient occlusion -* [ ] Distance-field shadows -* [ ] Soft shadows -* [ ] Global illumination -* [ ] Collision queries -* [ ] Volumetric effects -* [ ] Object interaction -* [ ] VFX collision -* [ ] Procedural effects - -One representation can support a surprising number of systems. - ---- - -# 16. Occlusion hierarchy - -I'd make this its own roadmap item rather than hiding it inside rendering. - -* [ ] Frustum culling -* [ ] Distance culling -* [ ] Occlusion culling -* [ ] Hierarchical Z-buffer -* [ ] Software occlusion rasterizer -* [ ] Portal culling -* [ ] Cell culling -* [ ] HLOD culling -* [ ] Shadow culling -* [ ] Reflection culling -* [ ] Particle culling -* [ ] Light culling - -And importantly: - -**GPU occlusion feedback.** - ---- - -# 17. Animation LOD - -Not just mesh LOD. - -AAA engines reduce animation cost too. - -* [ ] Animation LOD -* [ ] Bone LOD -* [ ] Skeleton LOD -* [ ] Update-rate LOD -* [ ] Pose interpolation -* [ ] Animation culling -* [ ] Animation budget allocator -* [ ] Crowd animation instancing -* [ ] Crowd animation GPU evaluation -* [ ] Animation pose caching -* [ ] Motion matching -* [ ] Pose search -* [ ] Animation compression - -For 10,000 NPCs, you don't want 10,000 full animation evaluations every frame. - ---- - -# 18. Crowd rendering - -If you want the **"massive medieval battle"** demo from your roadmap to actually work, this becomes important. - -* [ ] Crowd instance renderer -* [ ] Crowd LOD -* [ ] Crowd animation LOD -* [ ] GPU animation -* [ ] GPU skinning -* [ ] Instance animation -* [ ] Crowd culling -* [ ] Crowd impostors -* [ ] Crowd simulation batching -* [ ] Crowd spatial partitioning - ---- - -# 19. Destruction - -Not game-specific destruction scripts. This is **engine destruction infrastructure**. - -* [ ] Runtime mesh fracture -* [ ] Pre-fractured assets -* [ ] Destruction clusters -* [ ] Destruction LOD -* [ ] Debris pooling -* [ ] Debris GPU rendering -* [ ] Destruction physics -* [ ] Fracture hierarchy -* [ ] Destruction streaming -* [ ] Procedural fracture - ---- - -# 20. Water renderer - -A proper engine water system is surprisingly complicated. - -* [ ] Ocean renderer -* [ ] FFT waves -* [ ] Gerstner waves -* [ ] Shoreline waves -* [ ] Foam -* [ ] Underwater scattering -* [ ] Refraction -* [ ] Reflection -* [ ] Caustics -* [ ] Water volumes -* [ ] Screen-space water effects -* [ ] Water LOD -* [ ] Infinite ocean -* [ ] River/stream representation - ---- - -# 21. Sky / atmosphere - -I'd make this more substantial than "skybox." - -* [ ] Physically based atmosphere -* [ ] Atmospheric scattering -* [ ] Sun scattering -* [ ] Moon -* [ ] Stars -* [ ] Dynamic sky -* [ ] Sky LUTs -* [ ] Cloud shadows -* [ ] Volumetric clouds -* [ ] Weather-driven atmosphere -* [ ] Horizon rendering -* [ ] Aerial perspective - ---- - -# 22. Post-processing stack - -A proper compositing architecture: - -* [ ] Bloom -* [ ] Exposure -* [ ] Auto exposure -* [ ] Tone mapping -* [ ] Color grading -* [ ] LUTs -* [ ] Motion blur -* [ ] Depth of field -* [ ] Vignette -* [ ] Chromatic aberration -* [ ] Film grain -* [ ] Sharpening -* [ ] Lens effects -* [ ] Distortion -* [ ] Screen-space effects -* [ ] Custom compute post-process -* [ ] Temporal post-processing - -You already have the node-based direction for this. - ---- - -# 23. Automatic quality system - -This is something people don't think about when they say "engine feature." - -Have Atomic automatically determine: - -```text -GPU capability -CPU capability -VRAM -RAM -resolution -frame time -scene complexity -``` - -and dynamically adjust: - -* [ ] Shadow quality -* [ ] LOD distance -* [ ] foliage density -* [ ] particle counts -* [ ] volumetric resolution -* [ ] GI quality -* [ ] reflection quality -* [ ] texture resolution -* [ ] animation update rates -* [ ] simulation rates - -Essentially an **engine-wide scalability manager**. - ---- - -# 24. Shader permutation management - -AAA engines can have ridiculous numbers of shader variants. - -I'd add: - -* [ ] Shader permutation system -* [ ] Feature flags -* [ ] Automatic permutation stripping -* [ ] Shader cache -* [ ] Pipeline state cache -* [ ] Async shader compilation -* [ ] Shader compilation database -* [ ] Shader dependency graph -* [ ] Runtime shader hot reload -* [ ] Shader warmup -* [ ] PSO cache -* [ ] Shader compile visualization - -This pairs directly with the shader compilation work already on your roadmap. - ---- - -# 25. Engine-wide budgets - -**This is a very AAA concept that I'd absolutely steal.** - -Every expensive subsystem gets a budget. - -```text -Frame Budget -──────────────────────── -Rendering 7.0 ms -Animation 2.0 ms -Physics 2.0 ms -AI 1.5 ms -Particles 1.0 ms -Streaming 0.5 ms -Scripts 2.0 ms -──────────────────────── -Total 16.0 ms -``` - -Then subsystems dynamically degrade quality when their budget is exceeded. - -For example: - -```text -Particle budget exceeded - ↓ -reduce particle simulation - ↓ -reduce particle LOD - ↓ -reduce distant particle updates - ↓ -cull lowest-priority effects -``` - -This could become a **core Atomic Engine philosophy**. - ---- - -# The really big missing category: "Virtualization" - -Looking at your roadmap, I'd seriously consider adding a dedicated: - -## `VIRTUALIZATION.md` - -Modern AAA rendering increasingly boils down to **don't actually process things that don't matter**. - -You could have: - -### Geometry virtualization - -Nanite-style meshlets. - -### Texture virtualization - -Virtual texturing. - -### Shadow virtualization - -Virtual shadow maps. - -### World virtualization - -World partition/streaming. - -### Animation virtualization - -Animation LOD/update budgets. - -### Particle virtualization - -GPU particles + LOD. - -### Audio virtualization - -Don't actually mix inaudible sounds. - -### Entity virtualization - -Sleep/deactivate/reduce distant simulation. - -### Lighting virtualization - -Only evaluate relevant lights. - -### Material virtualization - -Only evaluate necessary shader features. - -Then the general principle becomes: - -> **The engine maintains the illusion that the entire world is active and fully detailed, while only materializing the subset currently required.** - -That is *very* close to what makes modern AAA open-world engines impressive. - ---- ---- ---- - -Absolutely. If the goal is **"AAA visual quality without AAA computational cost"**, I'd split Atomic's rendering/physics roadmap around a single principle: - -> **Don't make everything high quality. Make the engine intelligently spend quality where it is perceptually useful.** - -Your roadmap already has the foundations for this with GPU residency, render nodes, LOD, occlusion, PBR, ray tracing, etc. - -Here are the engine-level systems I'd add. - -# 🎨 Rendering: high quality / low cost - -## 1. GPU-driven everything - -This should probably be the foundation. - -* [ ] GPU scene -* [ ] GPU frustum culling -* [ ] GPU occlusion culling -* [ ] GPU LOD selection -* [ ] GPU material sorting -* [ ] GPU draw generation -* [ ] indirect rendering -* [ ] multi-draw indirect -* [ ] GPU instance compaction -* [ ] GPU visibility buffers -* [ ] GPU light culling -* [ ] GPU shadow culling -* [ ] GPU particle culling -* [ ] GPU foliage culling - -The CPU should increasingly say: - -```text -"Here is the world." -``` - -rather than: - -```text -"Draw object 183." -"Draw object 184." -"Draw object 185." -... -``` - ---- - -# 2. Meshlet / virtual geometry renderer - -I'd make this a major Atomic feature. - -Traditional: - -```text -Object → Mesh → Draw -``` - -Atomic: - -```text -Object - ↓ -Mesh - ↓ -Cluster hierarchy - ↓ -Meshlets - ↓ -GPU culling - ↓ -Visible triangles -``` - -Add: - -* [ ] Meshlet generation -* [ ] Meshlet bounds -* [ ] Meshlet cone culling -* [ ] Meshlet hierarchy -* [ ] Meshlet LOD -* [ ] Screen-space error metric -* [ ] Meshlet occlusion -* [ ] GPU meshlet selection -* [ ] GPU indirect dispatch -* [ ] Meshlet streaming -* [ ] Meshlet compression - -This gets you toward the **Nanite class of rendering architecture** without simply copying Nanite. - ---- - -# 3. HLOD + impostor hierarchy - -Instead of simply: - -`LOD0 → LOD1 → LOD2 → LOD3` - -make the engine capable of: - -```text - World - │ - Region - │ - HLOD - │ - ┌────┴────┐ - Objects Objects - │ - LOD - │ - Impostor - │ - Cull -``` - -Add: - -* [ ] Automatic HLOD generation -* [ ] HLOD material baking -* [ ] HLOD proxy generation -* [ ] Impostor baking -* [ ] Runtime impostor selection -* [ ] Cross-fade/dither transitions -* [ ] HLOD streaming -* [ ] HLOD visibility testing - -This is incredibly important for large environments. - ---- - -# 4. Temporal rendering infrastructure - -Temporal techniques are one of the biggest "free quality" mechanisms modern renderers use. - -Add: - -* [ ] Motion-vector infrastructure -* [ ] Temporal history buffers -* [ ] Temporal accumulation -* [ ] Temporal reprojection -* [ ] Disocclusion detection -* [ ] History rejection -* [ ] Reactive masks -* [ ] Temporal denoising -* [ ] Temporal particle accumulation -* [ ] Temporal volumetric accumulation -* [ ] Temporal GI accumulation - -Then: - -* [ ] TAA -* [ ] TSR-style upscaling -* [ ] Temporal super-resolution - -The renderer can internally render something at, say, 70% resolution while reconstructing a much cleaner output. - ---- - -# 5. Dynamic resolution - -Make this automatic. - -```text -Target = 16.67 ms - -12 ms → resolution ↑ -15 ms → resolution ↑ -16 ms → hold -18 ms → resolution ↓ -22 ms → resolution ↓↓ -``` - -Add: - -* [ ] GPU frame-time controller -* [ ] Dynamic resolution -* [ ] Per-pass resolution scaling -* [ ] Resolution history -* [ ] Temporal upscaling integration -* [ ] Minimum/maximum resolution -* [ ] Resolution budgets - -This should integrate with your render graph. - ---- - -# 6. Variable-rate shading - -This is a really good one for "quality where it matters." - -* [ ] Variable Rate Shading -* [ ] Per-tile shading rates -* [ ] Motion-based shading rate -* [ ] Foveated shading -* [ ] Peripheral shading reduction -* [ ] Material-based shading rates -* [ ] VRS debug visualization - -Example: - -```text - Camera - - HIGH QUALITY - ███████████████ - ███████████████ - ███████████████ - ░░░░░░░░░ - LOW -``` - -Moving objects or peripheral regions can receive less shading work. - ---- - -# 7. Adaptive shadow system - -Instead of "shadow resolution = 4096." - -Have the engine decide. - -* [ ] Shadow importance scoring -* [ ] Shadow resolution LOD -* [ ] Shadow distance LOD -* [ ] Cascaded shadows -* [ ] Virtual shadow maps -* [ ] Shadow atlases -* [ ] Cached static shadows -* [ ] Contact shadows -* [ ] Screen-space contact shadows -* [ ] Per-light shadow budgets -* [ ] Shadow update frequency LOD - -A light 2 km away shouldn't receive the same shadow treatment as a character standing 2 metres away. - ---- - -# 8. Clustered lighting - -For scenes with enormous numbers of lights: - -* [ ] Clustered Forward+ -* [ ] GPU light binning -* [ ] Light grids -* [ ] Tile/cluster light lists -* [ ] Light importance culling -* [ ] Light LOD -* [ ] Shadow-casting-light budgets - -Instead of: - -```text -every object × every light -``` - -do: - -```text -screen/volume cluster - ↓ -only relevant lights - ↓ -shade -``` - ---- - -# 9. Reflection hierarchy - -Don't make every reflection ray-traced. - -Use a hierarchy: - -```text -Closest: -Ray traced reflection - ↓ -SSR - ↓ -Reflection probe - ↓ -Sky reflection - ↓ -Fallback -``` - -Add: - -* [ ] Reflection probes -* [ ] Reflection probe blending -* [ ] SSR -* [ ] Ray-traced reflections -* [ ] Hardware RT -* [ ] Probe streaming -* [ ] Probe importance -* [ ] Reflection LOD -* [ ] Reflection resolution scaling - -The engine chooses the cheapest technique that looks acceptable. - ---- - -# 10. GI hierarchy - -Same principle. - -```text -Near: -RT GI - ↓ -Screen-space GI - ↓ -Probe GI - ↓ -Irradiance volume - ↓ -Baked fallback -``` - -Add: - -* [ ] Light probes -* [ ] Irradiance volumes -* [ ] DDGI-like probes -* [ ] Screen-space GI -* [ ] RT GI -* [ ] Probe caching -* [ ] GI temporal accumulation -* [ ] GI resolution LOD -* [ ] GI update-rate LOD - ---- - -# 11. Distance fields - -This is one of my favourite additions for Atomic. - -Generate SDFs for meshes and reuse them. - -```text -Mesh - ↓ -SDF - ├── AO - ├── shadows - ├── GI - ├── collision - ├── particles - ├── volumetrics - └── effects -``` - -Add: - -* [ ] Mesh SDF generation -* [ ] Global SDF -* [ ] Hierarchical SDF -* [ ] SDF streaming -* [ ] SDF compression -* [ ] SDF collision queries -* [ ] SDF ray marching -* [ ] Distance-field AO -* [ ] Distance-field shadows - ---- - -# 12. Material LOD - -This is often overlooked. - -A material can have: - -```text -Near: -Normal + roughness + metallic + detail normal + clearcoat - -Medium: -Normal + roughness + metallic - -Far: -BaseColor + roughness - -Very far: -HLOD baked material - -Extremely far: -Impostor -``` - -Add: - -* [ ] Material LOD -* [ ] Texture channel LOD -* [ ] Shader feature LOD -* [ ] Material complexity budgeting -* [ ] Automatic shader simplification -* [ ] Distance-based material features - -That's potentially a **huge** performance win. - ---- - -# 13. Texture streaming - -You already have texture packing planned. I'd add a proper streaming architecture. - -* [ ] Mip streaming -* [ ] Texture residency -* [ ] GPU feedback -* [ ] Texture priority -* [ ] Texture memory budget -* [ ] Virtual texturing -* [ ] Virtual texture page cache -* [ ] Async texture decompression -* [ ] Texture prefetching -* [ ] Texture LOD bias - ---- - -# 14. Animation quality scaling - -Same concept outside rendering. - -```text -2m away: -Full animation - -20m: -Reduced bone updates - -50m: -Reduced animation rate - -100m: -Simplified skeleton - -300m: -Impostor animation - -500m: -Static -``` - -Add: - -* [ ] Bone LOD -* [ ] Animation LOD -* [ ] Animation update-rate LOD -* [ ] Skeleton LOD -* [ ] Pose caching -* [ ] Crowd animation batching -* [ ] GPU skinning -* [ ] GPU animation evaluation -* [ ] Animation budget allocator - ---- - -# ⚙️ Physics / Collision - -This is where I'd make a **very substantial architecture**, rather than simply adding collider types. - -## 15. Multi-stage collision detection - -Classic architecture: - -```text - Physics objects - │ - Broadphase - │ - Potential pairs - │ - Narrowphase - │ - Contact points - │ - Solver - │ - Integration -``` - -Add: - -* [ ] Broadphase -* [ ] Dynamic AABB tree -* [ ] Sweep-and-prune -* [ ] Spatial hash -* [ ] BVH -* [ ] Narrowphase -* [ ] Contact manifold generation -* [ ] Sequential impulse solver -* [ ] Constraint solver -* [ ] Position correction -* [ ] Velocity integration -* [ ] Sleeping - ---- - -# 16. Multiple collision representations - -**This is extremely important for performance.** - -Don't make one mesh serve every purpose. - -```text - Render Mesh - │ - ┌────────────┼────────────┐ - ↓ ↓ ↓ - Collision LOD Physics SDF - Mesh -``` - -Support: - -* [ ] Sphere -* [ ] Capsule -* [ ] Box -* [ ] Cylinder -* [ ] Convex hull -* [ ] Compound collider -* [ ] Triangle mesh -* [ ] Heightfield -* [ ] Voxel collider -* [ ] SDF collider - -And automatically generate them: - -```text -High-poly mesh - ↓ -Collider cooking - ↓ -convex decomposition - ↓ -optimized physics representation -``` - ---- - -# 17. Collision LOD - -This should absolutely be an engine feature. - -A rock might have: - -```text -0–20m: -Detailed convex decomposition - -20–100m: -Simple convex hull - -100m+: -Bounding volume - ->500m: -No physics -``` - -Same for NPCs: - -```text -Near: -Capsule + hitboxes - -Medium: -Capsule - -Far: -No collision -``` - ---- - -# 18. Physics sleeping - -Huge performance win. - -If something hasn't moved: - -```text -Dynamic - ↓ -Velocity ≈ 0 - ↓ -No contacts changing - ↓ -SLEEP -``` - -Don't solve it every frame. - -Add: - -* [ ] Automatic sleeping -* [ ] Island sleeping -* [ ] Wake propagation -* [ ] Sleep thresholds -* [ ] Sleep statistics - ---- - -# 19. Physics islands - -Group connected objects. - -```text -Island A - ├── crate - ├── crate - └── floor - -Island B - ├── vehicle - ├── wheels - └── suspension -``` - -Then solve islands independently: - -* [ ] Island generation -* [ ] Island sleeping -* [ ] Parallel island solving -* [ ] Island scheduling -* [ ] Island profiling - -This fits your multi-threading architecture beautifully. - ---- - -# 20. Continuous collision detection - -Essential for fast objects. - -Without CCD: - -```text -Frame 1: ● -Frame 2: ● - WALL - │ - │ - │ -``` - -Object can tunnel through. - -With CCD: - -```text -●───────────────X│ - collision -``` - -Add: - -* [ ] Swept collision -* [ ] Time of impact -* [ ] Conservative advancement -* [ ] CCD modes -* [ ] Fast-body detection - ---- - -# 21. Physics substepping - -Don't tie physics directly to rendering. - -```text -Render: 60 Hz - -Physics: -120 Hz - -High-speed objects: -240 Hz -``` - -Add: - -* [ ] Fixed timestep -* [ ] Variable render timestep -* [ ] Physics substeps -* [ ] Adaptive substeps -* [ ] Per-object simulation frequency -* [ ] Physics interpolation -* [ ] Physics extrapolation - ---- - -# 22. Collision layers - -Make collision filtering extremely cheap. - -```text -Player -Enemy -World -Projectile -Vehicle -Trigger -Water -Debris -``` - -Then bitmasks: - -```text -Player → World + Enemy -Projectile → World + Enemy -Trigger → Player + Enemy -``` - -Ideally the broadphase eliminates most impossible pairs **before narrowphase**. - ---- - -# 23. Trigger/query system - -Separate physical collision from spatial queries. - -* [ ] Raycast -* [ ] Spherecast -* [ ] Capsulecast -* [ ] Boxcast -* [ ] Overlap sphere -* [ ] Overlap capsule -* [ ] Overlap box -* [ ] Frustum query -* [ ] Shape sweep -* [ ] Closest-point query -* [ ] Distance query -* [ ] Batch queries -* [ ] Async queries -* [ ] GPU queries where useful - -**Batch queries** are especially important. - -Instead of: - -```text -raycast() -raycast() -raycast() -raycast() -... -``` - -allow: - -```text -batch_raycast(10,000 rays) -``` - -and process them together. - ---- - -# 24. GPU physics - -Eventually: - -* [ ] GPU broadphase -* [ ] GPU particle collision -* [ ] GPU cloth -* [ ] GPU destruction -* [ ] GPU fluids -* [ ] GPU crowd collision -* [ ] GPU spatial queries - -But I would **not** try to make all rigid-body physics GPU-only. - -A hybrid architecture is much more useful: - -```text -CPU - ├── gameplay physics - ├── vehicles - ├── characters - └── constraints - -GPU - ├── particles - ├── debris - ├── cloth - ├── fluids - └── massive crowds -``` - ---- - -# 25. Physics material system - -* [ ] Friction -* [ ] Restitution -* [ ] Density -* [ ] Surface velocity -* [ ] Rolling friction -* [ ] Combine modes -* [ ] Physical material lookup -* [ ] Material-based particles -* [ ] Material-based footsteps -* [ ] Material-based VFX - -Then the renderer, physics and audio system can all ask: - -```text -"What surface am I interacting with?" -``` - -and receive the same physical material. - ---- - -# 26. Collision cooking/cache - -Don't generate expensive collision representations at runtime repeatedly. - -Asset pipeline: - -```text -Mesh - ↓ -Physics cooker - ├── convex hull - ├── decomposition - ├── BVH - ├── SDF - └── heightfield - ↓ -.physicsasset -``` - -Then runtime simply loads the cooked representation. - ---- - -# 27. Physics-aware LOD - -This is the **really interesting part**. - -Your engine could have one generalized concept: - -## Simulation LOD - -Not just graphics. - -```text - SIMULATION LOD - │ - ┌────────────┼────────────┐ - ↓ ↓ ↓ - Render Physics Animation - │ │ │ - LOD LOD LOD -``` - -For an object: - -```text -Distance - │ - ├── 0–20m - │ Full render - │ Full collision - │ Full animation - │ - ├── 20–100m - │ Render LOD - │ simplified collision - │ reduced animation - │ - ├── 100–500m - │ HLOD - │ coarse collision - │ low-rate simulation - │ - └── 500m+ - HLOD/impostor - no physics - sleeping -``` - -That is **much more powerful** than ordinary LOD. - ---- - -# 28. Automatic quality allocation - -I think this could become one of Atomic Engine's signature features. - -Every object gets an engine-generated **importance score** based on: - -```text -distance -screen size -velocity -player visibility -camera visibility -gameplay relevance -shadow contribution -audio relevance -physics relevance -``` - -Then: - -```text -Importance = 0.94 -→ maximum quality - -Importance = 0.52 -→ medium - -Importance = 0.08 -→ cheap representation -``` - -So instead of developers manually saying: - -> "This NPC gets animation LOD 2 at 80 metres." - -the engine can determine it dynamically. - ---- - -# 🚀 And one more: asynchronous everything - -For the huge open worlds you're imagining, I'd add a general: - -## Async Resource/Simulation Pipeline - -```text - Main Frame - │ - ┌──────────┼──────────┐ - ↓ ↓ ↓ - Streaming Physics AI - │ │ │ - ↓ ↓ ↓ - Worker Workers Workers - │ │ │ - └──────────┼──────────┘ - ↓ - Results - ↓ - Frame -``` - -With: - -* [ ] Async asset loading -* [ ] Async texture decompression -* [ ] Async mesh decompression -* [ ] Async shader compilation -* [ ] Async physics -* [ ] Async pathfinding -* [ ] Async terrain generation -* [ ] Async GPU readback -* [ ] Async scene loading -* [ ] Async world streaming -* [ ] Async animation evaluation - ---- - -## If I were designing Atomic's "high-performance AAA" stack - -I'd actually organize it like this: - -```text - ATOMIC ENGINE - │ - ┌───────────┴───────────┐ - │ IMPORTANCE SYSTEM │ - │ distance / visibility │ - │ screen size / budget │ - └───────────┬───────────┘ - │ - ┌───────────┴───────────┐ - │ SIMULATION LOD │ - └───────────┬───────────┘ - │ - ┌─────────────────┼─────────────────┐ - ↓ ↓ ↓ - RENDER LOD PHYSICS LOD ANIMATION LOD - │ │ │ - ↓ ↓ ↓ - Meshlets Collider LOD Bone LOD - HLOD Sleeping Update rate - Impostors Islands GPU skinning - │ │ │ - └─────────────────┼─────────────────┘ - ↓ - GPU / CPU BUDGET - │ - ↓ - SCHEDULER / JOBS - │ - ┌──────────┴──────────┐ - ↓ ↓ - CPU GPU - simulation visibility - physics culling - gameplay LOD - streaming lighting - rendering -``` - -**That is the direction I'd push the engine toward.** - -The really interesting part isn't individually implementing LOD, HLOD, occlusion, physics sleeping, animation LOD, dynamic resolution, etc. It's making them all participate in a **unified importance/budget system**. Then Atomic can automatically spend computational resources on *what the player can actually perceive*, which is probably the single biggest architectural lever for getting "huge AAA world + extremely high visual quality + sane hardware requirements." - ---- ---- ---- - -Yes. Looking specifically across the roadmap **and** `CODE_ARCH.md`, there are quite a few deeper engine mechanisms I would add. Some of these are more interesting than simply adding another renderer feature because they can become reusable infrastructure across rendering, physics, animation, terrain, networking, etc. - -One important constraint from your architecture: you explicitly decided **against virtualized geometry for now**, with LOD selection targeting quad utilization instead. So I wouldn't blindly add "Nanite" to the roadmap; I'd build the mechanisms that let you revisit that decision based on actual Atomic benchmarks. - -# 1. A generalized Spatial Acceleration System - -You have `collision` and `spatial` as separate architectural modules already. - -I'd turn this into a major engine capability: - -* [ ] Dynamic AABB tree -* [ ] BVH -* [ ] Spatial hash -* [ ] Uniform grids -* [ ] Loose octree -* [ ] Quadtree -* [ ] Frustum trees -* [ ] Hierarchical spatial queries -* [ ] Dynamic insertion/removal -* [ ] Incremental tree refitting -* [ ] Batched spatial queries -* [ ] Async spatial queries -* [ ] Query filters -* [ ] Spatial query cache - -And importantly, **one spatial system shared by multiple subsystems**: - -```text - Spatial Database - │ - ┌─────────┬───────┼────────┬─────────┐ - ↓ ↓ ↓ ↓ ↓ - Physics Render Audio AI Streaming - │ │ │ │ │ - collision cull sounds vision cells -``` - -Instead of every subsystem inventing its own spatial structure. - ---- - -# 2. Broadphase as a first-class engine feature - -I'd make collision detection much more sophisticated than just "support capsule / hull / mesh." - -The pipeline should be: - -```text - WORLD - │ - Spatial Broadphase - │ - Potential pairs - │ - Pair filtering - │ - Narrowphase - │ - Contact manifolds - │ - Solver -``` - -Add: - -* [ ] Dynamic AABB tree broadphase -* [ ] Sweep-and-prune broadphase -* [ ] Multi-level broadphase -* [ ] Static/dynamic separation -* [ ] Sleeping-object exclusion -* [ ] Collision-layer bitmasks -* [ ] Pair caching -* [ ] Persistent contact manifolds -* [ ] Speculative contacts -* [ ] Broadphase profiling - -The really nice part is that the same broadphase can potentially service: - -**physics + raycasts + AI vision + audio occlusion + VFX collision + streaming.** - ---- - -# 3. Collision Representation Cooking - -Your roadmap currently says to add capsule, square, mesh, hull, etc. - -I'd add a proper **Physics Cooker**. - -Given: - -```text - Render Mesh - │ - Physics Cooker - │ - ┌────────────┼────────────┐ - ↓ ↓ ↓ - Convex Hull Decomposition SDF - │ │ │ - └────────────┼────────────┘ - ↓ - Physics Asset -``` - -Generate automatically: - -* [ ] Convex hull -* [ ] Convex decomposition -* [ ] Simplified triangle mesh -* [ ] BVH -* [ ] Heightfield -* [ ] SDF -* [ ] Compound collider -* [ ] Collision LODs -* [ ] Physics asset cache - -Then your high-poly visual mesh doesn't dictate your physics cost. - ---- - -# 4. Collision LOD - -This deserves its own item. - -For example: - -```text -0–10 m - detailed collider - -10–50 m - simplified convex - -50–200 m - primitive collider - -200m+ - no simulation -``` - -But I'd actually make this part of a broader: - -## Simulation LOD - -Your engine could apply the concept to **everything**. - -```text - Simulation LOD - │ - ┌───────────────┼───────────────┐ - ↓ ↓ ↓ - Rendering Physics Animation - │ │ │ - LOD LOD LOD -``` - -This would fit beautifully with your existing GPU-resident architecture. - ---- - -# 5. Physics Islands - -This is a major one. - -If 100 crates are connected by constraints, don't solve the entire world as one giant problem. - -```text -World - -Island A - ├── vehicle - ├── wheel - ├── wheel - └── suspension - -Island B - ├── crate - └── floor - -Island C - └── debris -``` - -Add: - -* [ ] Island generation -* [ ] Island sleeping -* [ ] Island wake propagation -* [ ] Parallel island solving -* [ ] Island prioritization -* [ ] Island splitting/merging - -This fits your architectural rule that work **inside a tick can be parallel**. - ---- - -# 6. Persistent Contact Manifolds - -This is a smaller but very worthwhile physics feature. - -Instead of rebuilding all contacts every frame: - -```text -Frame N - ↓ -contacts - -Frame N+1 - ↓ -reuse + update contacts -``` - -Add: - -* [ ] Persistent manifolds -* [ ] Contact warm starting -* [ ] Contact caching -* [ ] Manifold pruning -* [ ] Temporal contact coherence - -This makes resting stacks and complex scenes considerably cheaper. - ---- - -# 7. Continuous Collision Detection - -Definitely. - -* [ ] Swept collision -* [ ] Time-of-impact solver -* [ ] Conservative advancement -* [ ] CCD body modes -* [ ] Fast-object detection -* [ ] CCD collision budget - -Then projectiles and fast-moving objects don't tunnel through thin geometry. - ---- - -# 8. Physics Substepping - -Also combine this with your fixed-timestep architecture: - -```text -Render 60 Hz -Simulation 120 Hz -Critical 240 Hz -``` - -* [ ] Fixed simulation timestep -* [ ] Physics substeps -* [ ] Adaptive substeps -* [ ] Per-body simulation rates -* [ ] Physics interpolation -* [ ] Physics extrapolation - ---- - -# 9. GPU / CPU Hybrid Simulation - -You already want extensive batched computation and multiprocessing per world. - -I'd formalize the split. - -### CPU - -* characters -* vehicles -* important rigid bodies -* constraints -* gameplay-relevant collision - -### GPU - -* particles -* debris -* fluids -* cloth -* vegetation interaction -* massive crowds -* thousands of simple bodies - -So you get: - -```text - Physics World - │ - ┌───────┴───────┐ - ↓ ↓ - CPU GPU - authoritative massively - simulation parallel -``` - ---- - -# 10. Render/Physics Shared Geometry - -This could be really cool. - -Your mesh processing pipeline could produce multiple representations simultaneously: - -```text - Asset - │ - Geometry Processor - │ - ┌──────────────┼──────────────┐ - ↓ ↓ ↓ - Render Physics SDF - Mesh Collision Distance - │ │ │ - ↓ ↓ ↓ - Renderer Physics VFX/GI -``` - -One asset import generates everything the engine needs. - -That means **SDF isn't just a rendering feature**; it becomes shared engine infrastructure. - ---- - -# 11. SDF Everywhere - -Your roadmap already has displacement, GI, AO, etc. - -I'd add a generalized: - -## Signed Distance Field System - -* [ ] Mesh SDF generation -* [ ] Hierarchical SDF -* [ ] SDF compression -* [ ] SDF streaming -* [ ] Global scene SDF -* [ ] Local object SDF -* [ ] SDF collision queries -* [ ] SDF ray marching -* [ ] SDF AO -* [ ] SDF shadows -* [ ] SDF GI -* [ ] SDF VFX collision -* [ ] SDF volumetric effects - -One data structure serving multiple systems is exactly the kind of thing I'd want in this engine. - ---- - -# 12. Visibility System - -Your roadmap already has occlusion culling, but I'd elevate it into an actual subsystem. - -```text - Visibility System - │ - ┌───────────────┼────────────────┐ - ↓ ↓ ↓ - Frustum Occlusion Distance - │ │ │ - └───────────────┼────────────────┘ - ↓ - Visible Set - │ - ┌──────────┼──────────┐ - ↓ ↓ ↓ - Render VFX Shadows -``` - -Add: - -* [ ] Frustum culling -* [ ] Hierarchical Z occlusion -* [ ] Bounding-box culling -* [ ] Sphere culling -* [ ] Portal culling -* [ ] Cell culling -* [ ] Shadow visibility -* [ ] Reflection visibility -* [ ] Particle visibility -* [ ] Visibility history -* [ ] Temporal occlusion -* [ ] GPU visibility buffer - -Your portal work makes this particularly interesting because portals already require special projection/clipping/visibility handling. - ---- - -# 13. Automatic Render Budgeting - -This is something I think **Atomic should do unusually well**. - -Every frame: - -```text -GPU budget = 16.67ms - -Geometry 3.1ms -Shadows 2.2ms -Lighting 2.0ms -GI 2.8ms -Particles 0.8ms -Post 1.7ms -──────────────────── -Total 12.6ms -``` - -Then the engine can dynamically allocate quality. - -If GPU time rises: - -```text -GI ↓ -Shadow resolution ↓ -Particle count ↓ -LOD distances ↓ -Volumetric resolution ↓ -``` - -instead of simply dropping the entire frame rate. - -Add: - -* [ ] GPU budget manager -* [ ] CPU budget manager -* [ ] Memory budget manager -* [ ] Streaming budget -* [ ] Shadow budget -* [ ] Particle budget -* [ ] Animation budget -* [ ] Physics budget -* [ ] Automatic quality allocator - ---- - -# 14. Perceptual Importance System - -This is the mechanism I'd put **above** all those budgets. - -Calculate something like: - -```text -importance = - screen_area - × visibility - × distance_weight - × motion_weight - × gameplay_weight - × audio_weight -``` - -Then every subsystem can consume it. - -```text -Object importance: 0.92 - -→ Render LOD 0 -→ full animation -→ full collision -→ high-res shadow -→ detailed VFX - -Object importance: 0.03 - -→ impostor -→ no animation -→ sleeping physics -→ no shadow -→ minimal VFX -``` - -This could become a defining Atomic feature. - ---- - -# 15. Temporal Coherence System - -This is another big one for speed. - -A lot of expensive calculations don't actually need to happen from scratch every frame. - -Create reusable infrastructure for: - -* [ ] Temporal history -* [ ] Previous-frame transforms -* [ ] Previous visibility -* [ ] Previous depth -* [ ] Previous motion vectors -* [ ] Previous lighting -* [ ] Previous GI -* [ ] Previous shadow state -* [ ] Previous physics contacts -* [ ] Previous animation poses - -Then systems can say: - -> "Nothing changed enough; reuse last frame." - ---- - -# 16. Asynchronous Read/Write Pipelines - -Your roadmap specifically notes that expensive noise terrain generation currently freezes the main thread. - -I'd solve this more generally. - -```text -CPU World State - │ - ↓ - Job Submission - │ - ┌────┼────┬────┐ - ↓ ↓ ↓ ↓ -CPU CPU GPU IO - │ │ │ │ - └────┴────┴────┘ - ↓ - Fence/Event - ↓ - Apply Results -``` - -Add: - -* [ ] Async compute scheduler -* [ ] GPU fences -* [ ] CPU futures -* [ ] Job dependencies -* [ ] Resource dependencies -* [ ] Async readback -* [ ] Async world generation -* [ ] Async physics queries -* [ ] Async pathfinding -* [ ] Async asset cooking -* [ ] Async streaming - -This would turn your current job system into a much more complete execution framework. - ---- - -# 17. Resource Lifetime / Aliasing - -You already specifically mention **resource aliasing** in shader compilation. - -I'd expand it to the whole renderer: - -* [ ] Transient GPU resources -* [ ] Resource lifetime analysis -* [ ] Automatic aliasing -* [ ] Render-target pooling -* [ ] Buffer pooling -* [ ] Texture pooling -* [ ] Memory defragmentation -* [ ] Residency tracking -* [ ] Automatic eviction -* [ ] Resource dependency graph - -This can massively reduce VRAM usage. - ---- - -# 18. Compression/Quantization Everywhere - -You're already considering FP16/FP8/INT16/INT8/INT4 for components and editable meshes/textures. - -I'd generalize this into an **Engine Data Representation System**. - -For each piece of data: - -```text -Position -→ FP32 / FP16 - -Normal -→ packed 10:10:10 - -Color -→ RGBA8 - -Quaternion -→ 3-component compressed - -Animation -→ quantized tracks - -Network -→ quantized state - -Physics -→ compact state - -GPU instance -→ tightly packed struct -``` - -Then the engine can choose representation based on where the data lives. - -This is particularly powerful because your architecture already emphasizes minimizing PCIe traffic and only uploading changed GPU-resident state. - ---- - -# 19. Automatic Data Residency - -I'd push your GPU-resident idea much further. - -Every engine resource could have: - -```text -CPU resident -GPU resident -CPU + GPU resident -streaming -transient -persistent -``` - -And the engine manages movement automatically. - -```text -CPU - │ - │ dirty - ↓ -Upload Queue - │ - ↓ -GPU - │ - │ unused - ↓ -Eviction -``` - -Add: - -* [ ] Residency manager -* [ ] Dirty-range tracking -* [ ] Partial buffer uploads -* [ ] Sparse resources -* [ ] GPU memory budgets -* [ ] Residency priorities -* [ ] Automatic eviction -* [ ] Upload batching -* [ ] Upload compression - -This directly builds on what you're already doing. - ---- - -# 20. Renderer "Quality Modes" - -Rather than developers manually assembling every optimization: - -```text -Atomic Renderer - ├── Cinematic - ├── Ultra - ├── High - ├── Medium - ├── Low - └── Mobile -``` - -But these shouldn't just be arbitrary presets. - -They should be **constraint profiles**: - -```text -Ultra: -16ms target -12GB VRAM - -High: -16ms target -8GB VRAM - -Mobile: -33ms target -4GB RAM -``` - -The engine automatically determines: - -* LOD -* resolution -* shadows -* GI -* texture residency -* animation rates -* particles -* physics detail -* volumetric resolution - ---- - -# 21. Automatic Asset Analysis - -This would be a fantastic Studio feature. - -When importing a model: - -```text -Castle.fbx - -Triangles: 4.2M -Materials: 38 -Textures: 71 -VRAM: 1.4 GB -Physics: 3.2 MB -SDF: 12 MB - -Generated: -✓ LOD0 -✓ LOD1 -✓ LOD2 -✓ HLOD -✓ Collision -✓ SDF -✓ Impostor - -Warnings: -⚠ 7 unnecessary material slots -⚠ 2K texture on 12px object -⚠ excessive triangle density -``` - -Your existing ShaderCapabilities/resource estimation direction is already moving toward this kind of tooling. - ---- - -# 22. Render Cost Visualization - -I'd absolutely add this. - -Studio viewport modes: - -```text -Normal -Wireframe -Overdraw -Triangles -LOD -Materials -Light complexity -Shadow complexity -GPU time -Memory -Visibility -``` - -And especially: - -### **"Why is this expensive?"** - -Select an object: - -```text -Tree_38291 - -GPU cost: - Geometry 0.031 ms - Shadow 0.014 ms - Material 0.009 ms - VFX 0.000 ms - -Memory: - Mesh 1.2 MB - Textures 4.8 MB - -Current LOD: - LOD1 - -Visible: - Yes - -Occluded: - No -``` - -That would make optimization dramatically easier. - ---- - -# 23. Frame Capture / Render Replay - -Your roadmap already wants extensive rendering tests. - -Go one step further: - -```text -Capture Frame - ↓ -Save: - ECS state - GPU buffers - render graph - camera - resources - shaders - visibility - ↓ -Replay offline -``` - -Then you can compare: - -```text -Frame 10382 - -Before optimization -16.8 ms - -After optimization -11.4 ms -``` - -This is **huge** for engine development. - ---- - -# 24. Deterministic Replay - -Your architecture explicitly commits to strict IEEE floating-point determinism. - -Exploit that. - -Add: - -* [ ] Simulation recording -* [ ] Input recording -* [ ] World snapshots -* [ ] Deterministic replay -* [ ] State hashing -* [ ] Divergence detection -* [ ] Tick-by-tick comparison -* [ ] Physics replay -* [ ] Network replay - -Then: - -```text -Replay #1827 - -Tick 918: -Client A = hash 83FA... -Server = hash 83FA... - -Tick 919: -Client A = hash 19BB... -Server = hash 73CD... - -→ DIVERGENCE -``` - -That would be an incredible debugging system. - ---- - -# 25. One especially interesting feature: "Engine LOD" - -I'd actually give this its own major roadmap item. - -Instead of thinking: - -> LOD = lower polygon count. - -Atomic's definition could be: - -> **LOD = lower computational representation while preserving perceptual/physical behavior.** - -So: - -```text - ENTITY - │ - Importance Score - │ - ↓ - Engine LOD - │ - ┌─────────────┼─────────────┐ - ↓ ↓ ↓ - Rendering Physics Animation - │ │ │ - Mesh LOD Collider LOD Bone LOD - HLOD Sleeping Rate LOD - Impostor Island Pose cache - Culling Simplify GPU skin - │ │ │ - └─────────────┼─────────────┘ - ↓ - Budget Manager -``` - -Then even **streaming** can participate: - -```text -far away -→ metadata only - -nearby -→ low-res representation - -visible -→ high-res - -close -→ maximum detail -``` - ---- - -## And there are some particularly good "AAA engine" mechanics I'd put on your roadmap - -### Rendering - -* [ ] GPU-driven visibility -* [ ] HLOD -* [ ] Impostors -* [ ] Meshlet renderer **as an experiment** -* [ ] Hierarchical Z occlusion -* [ ] Temporal rendering -* [ ] Dynamic resolution -* [ ] VRS -* [ ] Virtual texturing -* [ ] Virtual shadow maps -* [ ] Clustered lighting -* [ ] Reflection hierarchy -* [ ] GI hierarchy -* [ ] SDF system -* [ ] GPU particles -* [ ] GPU foliage -* [ ] Animation LOD -* [ ] Material LOD -* [ ] Texture streaming -* [ ] Automatic render budgets - -### Physics - -* [ ] Spatial acceleration structures -* [ ] Broadphase -* [ ] Narrowphase -* [ ] Persistent manifolds -* [ ] Warm-started solver -* [ ] Physics islands -* [ ] Sleeping -* [ ] CCD -* [ ] Substepping -* [ ] Collision layers -* [ ] Collision LOD -* [ ] Physics cooking -* [ ] Convex decomposition -* [ ] SDF collision -* [ ] Batch raycasts/overlaps -* [ ] Async physics queries -* [ ] GPU physics for massively parallel workloads - -### Cross-system - -* [ ] **Unified importance system** -* [ ] **Unified simulation LOD** -* [ ] **Unified budget manager** -* [ ] **Unified spatial database** -* [ ] **Unified resource residency manager** -* [ ] **Unified temporal history system** -* [ ] **Unified data quantization/packing** -* [ ] **Unified async execution system** -* [ ] **Frame capture/replay** -* [ ] **Deterministic simulation replay** -* [ ] **Automatic asset analysis** -* [ ] **Cost/complexity visualization** - -And honestly, **the cross-system group is where I think the really novel Atomic Engine architecture could emerge**. Your documents already have several of the ingredients: GPU-resident state, delta uploads, quantization, parallel world processing, render graphs, strict determinism, and a clean ECS/shim separation. - -Rather than accumulating 500 independent features, you can make a handful of systems cause *all* those features to become cheaper automatically: **Spatial, Visibility, Importance, LOD, Residency, Budgeting, Temporal History, and Scheduling**. That's the kind of architecture I'd aim for if the goal is **"Atomic can render/simulate an absurd amount of stuff without requiring absurd hardware."** - ---- ---- ---- - -Yes. **This is the more interesting direction**. Looking at the architecture documents together, I think there is a much deeper philosophy you can push Atomic toward than "implement the usual AAA features." - -Your existing design already has several unusual pieces: ECS-first separation, GPU-resident visual state, delta-only synchronization, strict determinism, parallel work within ticks, batched world processing, node-based rendering, and portals that are intended to cross the physics/rendering/projection boundary seamlessly. - -I'd build on those with something like: - -# The overarching idea: optimize for **end-to-end wall clock** - -Most engines implicitly optimize: - -> "Make each operation as cheap as possible." - -I'd instead make Atomic optimize: - -> **"Minimize time from input/state change → final observable result."** - -That changes some architectural decisions dramatically. - -For example, this can be faster: - -```text -CPU computes extra data - ↓ -GPU receives extra data - ↓ -GPU has enough information to finish independently -``` - -than: - -```text -CPU computes minimal data - ↓ -GPU stalls - ↓ -CPU computes another thing - ↓ -synchronization - ↓ -GPU continues -``` - -So I'd explicitly introduce an **end-to-end latency optimization philosophy**. - ---- - -# 1. Predicted / Speculative Compute - -This is probably the most interesting thing you mentioned. - -Instead of always waiting for the exact answer: - -```text -A → compute → B → compute → C → render -``` - -the engine can predict likely outcomes: - -```text -A -│ -├── predicted B₁ ──→ predicted C₁ -├── predicted B₂ ──→ predicted C₂ -└── predicted B₃ ──→ predicted C₃ - │ - ↓ - actual B - │ - accept / discard -``` - -The key is that **extra computation can be worthwhile if it removes a synchronization point**. - -## Where this could work - -### Rendering - -Predict: - -* camera transform -* object visibility -* LOD -* shadow visibility -* portal views -* animation pose -* temporal history - -Then correct when the authoritative state arrives. - -### Physics - -Predict: - -* broadphase pairs -* likely contacts -* sleeping/waking -* next transforms - -Then the actual solver validates/corrects. - -### ECS - -Predict which queries/components will become dirty next tick. - -### Streaming - -Predict what assets the camera will need **before** it reaches them. - -### Networking - -Client predicts future state while authoritative state arrives asynchronously. - ---- - -# 2. Speculative Visibility - -This could be extremely useful with your GPU-resident architecture. - -Suppose frame N sees: - -```text -A B C D -``` - -Frame N+1 will *probably* see: - -```text -A B C E -``` - -Instead of waiting for a full visibility calculation: - -```text -Previous visible set - ↓ -predict next visible set - ↓ -start work - ↓ -actual camera arrives - ↓ -correct -``` - -You could maintain: - -* previous visible set -* predicted visible set -* confirmed visible set - -Then rendering can begin work before the final camera state is completely resolved. - ---- - -# 3. Speculative Portal Rendering - -This becomes **really interesting** for your non-Euclidean system. - -Your roadmap wants portals to make lighting, physics, projection, clipping and geometry crossing the seam seamless. - -Imagine: - -```text -Camera - ↓ -Portal A - ↓ -Portal B - ↓ -Portal C -``` - -Instead of synchronously rendering: - -```text -Camera - → A - → B - → C -``` - -you could maintain cached predicted portal views. - -```text -Frame N: - Portal A view - ↓ - Portal B view - ↓ - Portal C view - -Frame N+1: - predict all three - ↓ - render concurrently - ↓ - validate camera transforms -``` - -And because portals transform coordinates, you can potentially identify **equivalent views**. - ---- - -# 4. Portal View Deduplication - -This is a big one I haven't mentioned before. - -Suppose you have: - -```text -Camera - ├── Portal A → Room X - ├── Portal B → Room X - └── Portal C → Room X -``` - -The naive renderer may render three separate views. - -But if their resulting view states overlap sufficiently, Atomic could detect: - -> "These are effectively the same view." - -Then share: - -* visibility -* depth -* shadows -* lighting -* geometry -* temporal history -* GPU work - -You could have a: - -## View Cache - -```text -ViewKey = - camera transform - projection - world - portal transform chain - clip region - render settings -``` - -Hash that. - -Then: - -```text -Request View X - ↓ -View cache? - ↙ ↘ - YES NO - ↓ ↓ -reuse render -``` - -This is particularly suited to non-Euclidean rendering. - ---- - -# 5. Portal Transform Chains as First-Class Objects - -Instead of thinking: - -> camera → portal → camera - -think: - -```text -TransformChain - -World A - ↓ -Portal A - ↓ -World B - ↓ -Portal B - ↓ -World C -``` - -Represent the entire transformation as a composable object: - -```text -T = Tportal3 × Tportal2 × Tportal1 -``` - -Then the same chain can drive: - -* rendering -* physics -* raycasts -* audio -* AI perception -* spatial queries -* camera placement -* shadows -* GI - -That prevents each subsystem from implementing its own version of "what happens when you cross a portal." - ---- - -# 6. Recursive Portal Budgeting - -Rather than: - -> render portals up to depth 4 - -use a **cost-based recursion budget**. - -Example: - -```text -Portal A -importance = 0.92 -→ recurse - -Portal B -importance = 0.63 -→ recurse - -Portal C -importance = 0.11 -→ stop -``` - -Factors: - -* screen area -* distance -* portal depth -* motion -* visibility -* expected contribution -* previous-frame stability - -So a tiny portal doesn't consume the same recursion budget as a giant doorway occupying half the screen. - ---- - -# 7. Temporal Portal Reprojection - -You currently use last-frame information for cameras-in-cameras. - -I'd push this much further. - -A portal view can have its own temporal history: - -```text -Portal A - ├── previous color - ├── previous depth - ├── previous motion - ├── previous visibility - └── previous transform -``` - -Then when the portal view moves slightly: - -```text -Previous portal frame - ↓ -reproject - ↓ -only calculate changed regions -``` - -This could make recursive portals **far cheaper** than brute-force rerendering every recursion every frame. - ---- - -# 8. Multi-Camera as a General Rendering Primitive - -Your architecture already wants to batch all cameras across active scenes. - -I'd make "camera" almost equivalent to a **View Request**. - -A view request contains: - -```text -World -Camera transform -Projection -Viewport -Clip planes -Portal chain -Render features -Quality budget -Temporal history -``` - -Then the renderer doesn't fundamentally care whether the view came from: - -* player camera -* reflection -* portal -* security camera -* minimap -* shadow camera -* probe -* editor viewport -* VR eye -* spectator -* cinematic camera - -They're all **views**. - -That gives you enormous opportunities for deduplication and batching. - ---- - -# 9. View Graph - -Take that one step further. - -Instead of: - -```text -Camera → Render -``` - -construct: - -```text - View Graph - - Main Camera - / | \ - / | \ - Portal Reflection Shadow - | | - Portal Probe - | - Portal -``` - -Each node is a view. - -The renderer can: - -* deduplicate views -* schedule independent views concurrently -* share resources -* determine dependencies -* prioritize important views -* reuse previous results - -This fits naturally into your render-node philosophy. - ---- - -# 10. Cross-View Work Sharing - -This could be **massive**. - -Suppose: - -```text -Main camera -Reflection camera -Portal camera -Shadow camera -``` - -all see the same castle. - -Don't independently perform: - -```text -cull castle -cull castle -cull castle -cull castle -``` - -Instead: - -```text - Scene - ↓ - Shared visibility - / | \ - ↓ ↓ ↓ - Camera Portal Reflection -``` - -Similarly: - -* mesh residency -* material residency -* animation -* skinning -* geometry processing -* texture residency - -can be shared. - ---- - -# 11. Incremental Everything - -This is another principle I'd explicitly add. - -Instead of: - -> recompute X every frame - -ask: - -> **what changed since last frame?** - -You already apply this philosophy to GPU state, where only changed data should be updated to minimize PCIe traffic. - -Generalize it: - -### Incremental ECS - -Only process changed components. - -### Incremental rendering - -Only recompute changed visibility/material state. - -### Incremental physics - -Reuse contact/manifold state. - -### Incremental GI - -Update only changed regions. - -### Incremental shadows - -Invalidate only affected pages. - -### Incremental streaming - -Only change residency where needed. - -### Incremental networking - -Send only changed state. - -### Incremental editor - -Only rebuild affected subtrees. - ---- - -# 12. Dependency-Aware Dirty Propagation - -Rather than every system scanning for changes: - -```text -Transform changed - ↓ -dependency graph - ├── render transform dirty - ├── spatial bounds dirty - ├── shadow dirty - ├── physics dirty - └── portal visibility dirty -``` - -One change propagates through a dependency graph. - -This could drastically reduce ECS iteration. - ---- - -# 13. Change Masks Per Component - -You already have the idea of packed component data and quantization. - -Go further: - -```text -Transform - ├── position dirty - ├── rotation clean - └── scale clean -``` - -Then downstream systems can avoid touching unchanged fields. - -At a lower level: - -```text -dirty_mask = 00100101 -``` - -could identify changed fields. - -This becomes useful for: - -* ECS -* GPU upload -* replication -* persistence -* undo/redo -* networking -* editor inspection - -**One dirty-bit system could serve all of them.** - ---- - -# 14. ECS Query Compilation - -Rather than interpreting ECS queries every frame: - -```text -query: -Position + Velocity + Health -``` - -compile them into an optimized execution plan. - -For example: - -```text -Query - ↓ -matching archetypes - ↓ -chunk list - ↓ -SIMD loop - ↓ -parallel partitions -``` - -Cache the result. - -If archetypes don't change, the query doesn't need to rediscover them. - ---- - -# 15. Query Result Caching - -Even more aggressive: - -```text -Query A: -Position + Velocity - -Frame N: -chunks [4,7,9,13] - -Frame N+1: -same chunks -``` - -Reuse the chunk list. - -Only invalidate when structural ECS changes occur. - -This is particularly attractive for an ECS-first engine. - ---- - -# 16. ECS Prefetching - -Since you're specifically thinking about cache hits: - -```text -Process chunk N - ↓ -hardware/software prefetch -chunk N+1 - ↓ -process N - ↓ -N+1 already in cache -``` - -But make it adaptive. - -If the access pattern is predictable: - -```text -prefetch aggressively -``` - -If random: - -```text -don't pollute cache -``` - -The ECS scheduler could learn access patterns from profiling data. - ---- - -# 17. Structure-of-Arrays **and** Array-of-Structures Hybridization - -Don't dogmatically make everything SoA. - -Different systems want different layouts. - -For example: - -```text -Rendering: -SoA - -Physics: -AoSoA - -Animation: -SoA - -Tiny frequently-used components: -packed AoS - -GPU: -structure optimized for coalescing -``` - -Atomic could automatically select component storage based on observed access patterns. - ---- - -# 18. Runtime Data Layout Specialization - -This is a more ambitious idea. - -Suppose profiling says: - -```text -Transform.Position -Transform.Rotation -Velocity -``` - -are almost always accessed together. - -Atomic could create a specialized packed view: - -```text -HotTransformView -[Position][Rotation][Velocity] -``` - -without changing the logical ECS component model. - -So: - -> **logical ECS layout ≠ physical execution layout** - -That could be extremely powerful. - ---- - -# 19. Predictive Streaming - -This is almost certainly worth doing. - -Instead of: - -```text -player reaches cell - ↓ -load cell -``` - -predict: - -```text -velocity -direction -camera -terrain topology -road/path -historical movement - ↓ -predict next cells - ↓ -stream them before needed -``` - -Even better: - -### Multiple predictions - -```text -80% → road ahead -15% → side path -5% → turn around -``` - -Load the cheap/common data for all three. - -Then fully load the most likely path. - ---- - -# 20. Streaming as a speculative computation - -Streaming doesn't have to be binary. - -```text -Unknown - ↓ -metadata - ↓ -compressed asset - ↓ -CPU decoded - ↓ -GPU resident - ↓ -high-res resident -``` - -Predictive streaming can advance an asset through these states before it's actually visible. - -This is a beautiful match for your asset system, which already separates GUIDs, content addressing, chunking, manifests and the virtual filesystem. - ---- - -# 21. GPU-Resident State with GPU Authority - -Your current architecture deliberately keeps visual state GPU-resident while CPU controllers produce it. - -I'd introduce a stronger distinction: - -### CPU-authoritative - -Gameplay state. - -### GPU-authoritative - -Purely visual derived state. - -For example: - -```text -CPU: -Transform -Animation state -Material parameters - -GPU derives: -world matrix -skinning -visibility -LOD -fade -instance flags -shadow state -``` - -Then **don't copy derived values back to CPU**. - -This sounds obvious, but making it a hard architectural rule can eliminate enormous amounts of synchronization. - ---- - -# 22. GPU-Side Dependency Graph - -If GPU state is resident, let GPU computations feed each other directly: - -```text -Transform - ↓ -Bounds - ↓ -Visibility - ↓ -LOD - ↓ -Material - ↓ -Shadow - ↓ -Draw -``` - -No CPU round trips. - -You already explicitly want per-instance render capabilities in the GPU-resident row so compute passes can branch without CPU readback. - -I'd make that philosophy universal. - ---- - -# 23. Synchronization Elision - -This could become an Atomic-specific optimization category. - -For every synchronization: - -> **Prove whether it is actually required.** - -Instead of: - -```text -CPU → sync → GPU → sync → CPU → sync → GPU -``` - -aim for: - -```text -CPU ───────────────→ GPU - async work - async work - async work - ↓ - fence only -``` - -Potential tools: - -* [ ] dependency-based fences -* [ ] timeline semaphores -* [ ] asynchronous compute -* [ ] deferred readback -* [ ] batched readback -* [ ] double/triple buffering -* [ ] persistent mapped buffers -* [ ] lock-free queues -* [ ] frame-lagged feedback -* [ ] speculative execution - ---- - -# 24. Delayed Feedback as a Feature - -This is subtle. - -Sometimes **a one-frame-old answer is better than blocking for a current answer**. - -You already do this with camera-in-camera rendering. - -Generalize it: - -```text -Current frame: -use previous result - -Meanwhile: -calculate current result - -Next frame: -use new result -``` - -Potentially for: - -* occlusion -* reflections -* GI -* shadows -* portal views -* expensive physics queries -* AI perception -* streaming decisions - -The engine needs to know **which information can safely be stale**. - ---- - -# 25. Quality-Staleness Tradeoffs - -This could be formalized. - -Every subsystem declares: - -```text -maximum acceptable staleness -``` - -Examples: - -```text -Physics: -0 frames - -Gameplay: -0 frames - -Main visibility: -0–1 - -Reflection: -1–2 - -GI: -2–8 - -Distant shadow: -several - -Far-away AI: -many -``` - -Then the scheduler can spend computation where freshness matters. - -That's much more sophisticated than simply having "quality = high/medium/low." - ---- - -# 26. Work Stealing + Critical Path Scheduling - -Your docs currently say work inside a tick may be parallel but cannot cross tick boundaries. - -I'd go beyond simple parallelism. - -Build the tick as a DAG: - -```text -Input - │ - ├── Physics ──┐ - ├── Animation ─┤ - ├── Streaming ─┤ - └── ECS ───────┤ - ↓ - Derived state - ↓ - Render -``` - -Then schedule based on **critical path**, not just workload. - -A 1 ms job blocking a 5 ms chain should potentially execute before a 4 ms independent job. - ---- - -# 27. Critical-Path-Aware ECS Scheduling - -Imagine: - -```text -System A: 3ms -System B: 1ms -System C: 1ms -System D: 4ms -``` - -If: - -```text -A → D -B → C -``` - -then: - -```text -A → D = 7ms critical path -B → C = 2ms -``` - -The scheduler should prioritize A/D. - -Not merely: - -> "give every worker roughly equal work." - -This is a genuine **end-to-end wall-clock optimization**. - ---- - -# 28. Memory-for-Time Algorithms - -I think you should explicitly embrace this. - -Your docs already pursue quantization and memory packing, but you're not forced to minimize memory at every cost. - -Allow: - -```text -+200 MB memory -→ -4 ms/frame -``` - -if the target platform has the RAM/VRAM. - -Examples: - -* cached query results -* duplicated hot ECS data -* precomputed transforms -* visibility caches -* portal view caches -* physics broadphase caches -* decoded asset caches -* precomputed SDFs -* shadow caches -* GI caches -* animation pose caches -* network delta baselines - -Basically: - -> **Memory is another form of computation budget.** - ---- - -# 29. Multi-Version Data - -This is particularly interesting. - -Instead of synchronizing one state: - -```text -State N -``` - -maintain: - -```text -State N -State N+1 prediction -State N-1 history -``` - -This helps: - -* temporal rendering -* rollback -* networking -* prediction -* physics -* portals -* interpolation - -It turns time itself into a cached dimension. - ---- - -# 30. History Buffers as a General Engine Primitive - -You already use previous-frame camera information. - -I'd create a generic: - -## Temporal Data Store - -```text -Current -Previous -Previous² -Predicted -Authoritative -``` - -Systems can request whichever version they need. - -That means temporal algorithms don't each invent their own buffering mechanism. - ---- - -# 31. Deterministic Rollback / Re-simulation - -Your strict IEEE determinism decision makes this particularly valuable. - -If the engine can deterministically replay ticks: - -```text -Tick 100 -Tick 101 -Tick 102 -Tick 103 -``` - -then speculative systems become much safer. - -You can: - -```text -predict - ↓ -continue simulation - ↓ -receive correction - ↓ -rollback - ↓ -replay -``` - -This has applications far beyond multiplayer. - ---- - -# 32. Eventual-Consistency Engine State - -Not every subsystem needs instantaneous synchronization. - -For example: - -```text -Gameplay state - ↓ authoritative - -Rendering - ↓ eventually consistent - -Audio - ↓ eventually consistent - -Streaming - ↓ eventually consistent - -Analytics - ↓ very eventually consistent -``` - -The engine could explicitly classify state as: - -* authoritative -* derived -* speculative -* cached -* eventually consistent - -That gives the scheduler permission to avoid unnecessary synchronization. - ---- - -# 33. Delta Everything - -You've already explicitly identified delta-state uploads and minimizing PCIe traffic. - -I'd make deltas a universal primitive: - -```text -ECS - delta - -GPU - delta - -Network - delta - -Persistence - delta - -Undo/redo - delta - -Streaming - delta - -Replication - delta -``` - -And ideally one common change representation: - -```text -Entity -Component -Field -Old value -New value -Version -``` - -Then different consumers encode it differently. - ---- - -# 34. Versioned State Instead of Full Synchronization - -Rather than: - -```text -"GPU is synchronized with ECS." -``` - -have: - -```text -ECS version = 91822 -GPU version = 91818 -``` - -GPU requests: - -```text -91818 → 91822 -``` - -and receives exactly those deltas. - -This makes synchronization measurable and explicit. - ---- - -# 35. Partial Synchronization - -You don't necessarily need: - -> "GPU is synchronized." - -You can have: - -```text -Transform: -GPU v91 - -Material: -GPU v104 - -Animation: -GPU v73 - -Visibility: -GPU v120 -``` - -Each subsystem progresses independently. - -That could be **very powerful** for your resident-state architecture. - ---- - -# 36. GPU Feedback Without Immediate Readback - -GPU-generated data often doesn't need to reach the CPU immediately. - -Instead: - -```text -GPU frame N - ↓ -feedback buffer - ↓ -GPU frame N+1 -``` - -and only occasionally: - -```text -GPU → CPU -``` - -for things like: - -* visibility statistics -* streaming requests -* occlusion results -* LOD statistics -* GPU counters - -This minimizes synchronization. - ---- - -# 37. Adaptive Algorithms - -Rather than choosing one algorithm forever: - -```text -BVH -vs -grid -vs -SAP -``` - -the engine could choose based on observed scene characteristics. - -For example: - -```text -Mostly static scene -→ BVH - -Huge uniform crowd -→ spatial grid - -Sparse moving objects -→ dynamic tree - -Terrain -→ hierarchical grid -``` - -Even better, choose **per spatial region**. - ---- - -# 38. Runtime Algorithm Selection - -This could be generalized: - -```text -Small N -→ O(N²), highly vectorized - -Medium N -→ spatial partition - -Huge N -→ GPU parallel algorithm -``` - -The asymptotically "better" algorithm isn't always faster at small N. - -Atomic could select based on: - -```text -N -distribution -hardware -cache -GPU occupancy -historical timing -``` - -This is exactly aligned with your "slightly more memory for less wall-clock" idea. - ---- - -# 39. Algorithm Portfolio - -You could actually maintain multiple implementations: - -```text -Collision: - ├── scalar - ├── SIMD - ├── multithreaded - └── GPU - -Visibility: - ├── CPU BVH - ├── SIMD BVH - └── GPU - -Particles: - ├── CPU - └── GPU -``` - -Then a runtime cost model selects one. - -Not every feature has to have one canonical implementation. - ---- - -# 40. Auto-Tuning - -This is where it gets really wild. - -Atomic could benchmark itself during development / first-run / controlled intervals: - -```text -Scene characteristics: - 250k entities - 30k visible - 8k dynamic - 400 lights - -Algorithm A: 2.1ms -Algorithm B: 1.6ms -Algorithm C: 2.7ms - -→ choose B -``` - -Store the result by hardware/content profile. - -This is essentially **JIT-style optimization for engine algorithms**. - ---- - -# 41. Predictive Compute Budgeting - -Combine prediction + budgets. - -Instead of: - -> "We have 2ms for particles." - -predict: - -```text -Next frame estimated: -GPU = 14.2ms - -Portal recursion = +1.4ms -Particles = +0.7ms -Shadow update = +0.8ms - -Predicted = 17.1ms -``` - -So the engine can reduce work **before** exceeding the frame budget. - -That's much better than reacting after the frame is already slow. - ---- - -# 42. Frame-Time Prediction - -You could have: - -```text -Frame N - ↓ -measure - -Frame N+1 - ↓ -predict cost - -Frame N+2 - ↓ -schedule based on prediction -``` - -Inputs: - -* number of visible objects -* camera velocity -* portal count -* particle count -* physics bodies -* GPU timing history -* streaming -* resolution - -This could drive dynamic quality proactively. - ---- - -# 43. "Do Nothing" as an Explicit Optimization - -This sounds silly, but it's incredibly important. - -Every system should have a cheap answer: - -> **Nothing changed.** - -For example: - -```text -Physics: -sleep - -Animation: -reuse pose - -Shadow: -reuse cache - -GI: -reuse probes - -Portal: -reuse view - -GPU: -no upload - -ECS: -no structural change - -Streaming: -already resident -``` - -A lot of engine performance comes from making the common case: - -```text -if unchanged: - return -``` - -extremely cheap. - ---- - -# 44. Zero-Copy Data Paths - -You should aggressively look for: - -```text -CPU data - ↓ copy -temporary - ↓ copy -GPU buffer -``` - -and replace with: - -```text -shared/persistent resource -``` - -where hardware permits. - -Especially: - -* ECS → renderer -* animation → skinning -* terrain → renderer -* physics → transforms -* network → replication -* asset decompression → GPU upload - ---- - -# 45. Cross-System GPU Pipelines - -Here's a potentially very Atomic-specific architecture: - -```text -ECS state - ↓ -GPU resident state - ↓ -Compute - ├── bounds - ├── visibility - ├── LOD - ├── animation - ├── skinning - ├── particles - ├── lighting lists - └── draw generation - ↓ -Graphics -``` - -Rather than CPU orchestrating every little stage. - ---- - -# 46. ECS → GPU "Derived State" - -I'd distinguish: - -```text -Authoritative ECS components -``` - -from: - -```text -Derived GPU components -``` - -For example: - -```text -ECS: -Transform -Mesh -Material -VisibilitySettings - -GPU derives: -WorldMatrix -BoundingSphere -LOD -Fade -DrawArguments -SkinningPalette -``` - -Those derived values **should not exist as duplicated CPU state**. - ---- - -# 47. One More Big Idea: Computational Coherence - -You have cache coherence at the hardware level. - -I'd design for **semantic coherence**. - -If several systems need the same result: - -```text -"Is this object visible?" -``` - -don't have: - -```text -renderer calculates visibility -physics calculates visibility -shadow calculates visibility -portal calculates visibility -``` - -Instead: - -```text -Visibility result - ↓ -shared by: - renderer - shadows - reflections - portals - VFX - audio -``` - -Likewise: - -```text -spatial query -distance -importance -material -surface type -``` - -should become reusable derived data. - ---- - -# 48. "Compute Once, Consume Many" - -I'd make this a hard design principle. - -For every expensive calculation ask: - -> **Can its result become an engine-wide primitive?** - -Examples: - -### Distance - -Used by: - -* LOD -* physics -* audio -* animation -* streaming -* particles - -### Visibility - -Used by: - -* renderer -* shadows -* reflections -* audio -* animation -* AI - -### Surface material - -Used by: - -* physics -* particles -* audio -* footsteps -* rendering - -### SDF - -Used by: - -* collision -* GI -* AO -* shadows -* VFX - -This is how you get disproportionate performance gains. - ---- - -# The architecture I'd actually aim for - -Your current documents already point toward: - -**ECS → GPU-resident state → delta synchronization → batched parallel worlds → node-based renderer.** - -I'd evolve that into: - -```text - ATOMIC - │ - ┌─────────┴─────────┐ - │ AUTHORITATIVE │ - │ WORLD STATE │ - └─────────┬─────────┘ - │ - Change / Version - │ - ┌─────────┴─────────┐ - │ DERIVED STATE │ - │ CPU + GPU caches │ - └─────────┬─────────┘ - │ - ┌──────────────────┼──────────────────┐ - ↓ ↓ ↓ - Visibility Spatial Importance - │ │ │ - └──────────────────┼──────────────────┘ - ↓ - SIMULATION LOD - │ - ┌─────────────┼─────────────┐ - ↓ ↓ ↓ - Render Physics Animation - │ │ │ - └─────────────┼─────────────┘ - ↓ - COMPUTE SCHEDULER - │ - ┌──────────┴──────────┐ - ↓ ↓ - CPU DAG GPU DAG - │ │ - └──────────┬──────────┘ - ↓ - OBSERVABLE FRAME -``` - -And surrounding that: - -```text -Prediction -Temporal history -Caching -Speculation -Delta state -Versioning -Budget prediction -Algorithm selection -``` - ---- ---- ---- - -Absolutely. I think **DX + AI + customization** could become one of Atomic's strongest differentiators. The engine shouldn't just be powerful internally; it should make the *power accessible* without forcing developers to understand the entire engine architecture. - -I'd think about it as: - -> **Anything the engine can do internally should eventually be inspectable, controllable, automatable, and replaceable by the developer.** - -## 1. Studio as an "engine operating system" - -Don't make Studio just a scene editor. - -Make it the unified interface to essentially everything Atomic can do. - -```text - ATOMIC STUDIO - │ - ┌──────────┬───────────┼───────────┬──────────┐ - ↓ ↓ ↓ ↓ ↓ - Scene Assets Code Runtime Data - ↓ ↓ ↓ ↓ ↓ - Physics Materials ECS Profiler Network - Render Shaders Jobs GPU Replay - Portals Animation AI Memory Tests -``` - -Every engine subsystem gets a Studio-facing interface. - -For example, select an entity and see: - -```text -ENTITY: Castle_Gate - -ECS - ├─ Transform - ├─ Renderable - ├─ PhysicsBody - ├─ PortalSurface - └─ AudioEmitter - -RUNTIME - ├─ GPU resident ✓ - ├─ Physics island #128 - ├─ LOD 1 - ├─ Visible ✓ - └─ Streaming state: Resident - -COST - CPU: 0.04ms - GPU: 0.17ms - VRAM: 18.2MB -``` - ---- - -# 2. "Everything is inspectable" - -This is probably one of the most important DX principles. - -If Atomic has: - -* ECS -* render graph -* GPU buffers -* physics -* jobs -* portals -* streaming -* resource residency -* synchronization -* temporal caches - -then Studio should expose them. - -Not just: - -> "FPS: 83" - -but: - -```text -WHY IS THIS FRAME 12.1ms? -``` - -and drill down: - -```text -Frame - ├─ Simulation 2.1ms - │ ├─ Physics 0.8 - │ ├─ ECS 0.6 - │ └─ Animation 0.7 - │ - ├─ Rendering 8.4ms - │ ├─ Shadows 1.8 - │ ├─ Geometry 2.0 - │ ├─ GI 1.6 - │ ├─ Portals 1.2 - │ └─ Post 1.8 - │ - └─ Streaming 1.6ms -``` - -Then click **Portals**: - -```text -Portal rendering: 1.2ms - -Portal A - ├─ recursion: 3 - ├─ views: 7 - ├─ cache hit: 82% - └─ 0.41ms - -Portal B - ├─ recursion: 2 - ├─ views: 4 - ├─ cache hit: 91% - └─ 0.17ms -``` - -That's developer experience worth building. - ---- - -# 3. Universal "Why?" inspector - -I'd actually make this a formal feature. - -Select anything and ask: - -> **Why is this here?** - -Examples: - -**Why is this mesh LOD2?** - -```text -Distance: 84m -Screen coverage: 2.3% -Importance: 0.18 -Triangle budget: exceeded -Selected LOD: 2 -``` - -**Why is this texture resident?** - -```text -Referenced by: - 18 visible objects - 2 portal views - 1 reflection - -Predicted usage: HIGH -``` - -**Why did this object get simulated?** - -```text -Physics: - awake - connected to Island #382 - player proximity: 14m - collision importance: 0.71 -``` - -This turns optimization from archaeology into debugging. - ---- - -# 4. Visual debugging everywhere - -Studio should have debug visualizations for basically every subsystem. - -### ECS - -* archetypes -* chunks -* query ranges -* entity ownership -* structural changes -* cache behavior - -### Physics - -* broadphase -* BVH -* contact manifolds -* islands -* sleeping -* CCD -* collision layers - -### Rendering - -* LOD -* visibility -* overdraw -* meshlets -* shadows -* light clusters -* GPU timings - -### Portals - -* portal frustums -* recursion -* transform chains -* clip planes -* view dependencies -* cached views - -### Streaming - -* loaded cells -* loading predictions -* residency -* memory pressure - -And importantly, **these should be available at runtime**, not only in editor mode. - ---- - -# 5. Time Travel Debugging - -This pairs extremely well with your deterministic architecture. - -Have: - -**Record → rewind → inspect → replay** - -```text - Timeline -──────────────────────────────── - 100 101 102 103 104 105 106 - ↑ - breakpoint -``` - -Click tick 103 and inspect: - -* ECS state -* physics -* transforms -* portal state -* GPU-visible state -* network state -* events - -Then: - -> Step one tick. - -This could be an incredible tool for engine development. - ---- - -# 6. "Freeze this subsystem" - -Imagine debugging a rendering problem. - -You can tell Studio: - -```text -Freeze: - ✓ Physics - ✓ ECS - ✓ Streaming - -Run: - ✓ Renderer -``` - -Or: - -```text -Freeze: - ✓ Renderer - -Run: - ✓ Physics -``` - -Or freeze **one entity**. - -```text -Entity 1842: -[Freeze Transform] -[Freeze Physics] -[Freeze Animation] -[Freeze GPU State] -``` - -This is much more useful than traditional debugger breakpoints for complex real-time systems. - ---- - -# 7. Live engine modification - -I'd make as much of Atomic as possible **hot-editable**. - -Change: - -* shader -* material -* render graph -* physics parameters -* LOD thresholds -* streaming rules -* ECS component -* pipeline configuration -* portal recursion -* lighting -* asset processing - -without restarting. - -Especially: - -### Live Render Graph - -```text -GBuffer - ↓ -Lighting - ↓ -GI - ↓ -Post -``` - -Drag a node. - -Connect something else. - -Compile. - -See it immediately. - ---- - -# 8. Pipeline Graph Editor - -Since you specifically mentioned customizable full pipelines: - -**Absolutely.** - -Don't make rendering the only graph. - -Atomic could expose multiple graph types: - -```text -Render Graph -Physics Graph -Asset Graph -Compute Graph -ECS System Graph -Streaming Graph -Audio Graph -Animation Graph -Build Graph -``` - -And potentially: - -```text - Atomic Graph Runtime - │ - ┌───────────────┼────────────────┐ - ↓ ↓ ↓ - CPU nodes GPU nodes IO nodes -``` - -The important distinction: - -> **Graph describes execution; code implements nodes.** - -Developers can replace either. - ---- - -# 9. Pipeline Overrides - -Every major subsystem should have an escape hatch. - -For example: - -```python -engine.renderer = MyRenderer() -engine.physics = MyPhysics() -engine.scheduler = MyScheduler() -engine.asset_cooker = MyCooker() -``` - -But preferably without requiring a fork. - -Something like: - -```text -Atomic - ├─ DefaultRenderer - ├─ CustomRenderer - ├─ DefaultPhysics - ├─ CustomPhysics - └─ CustomScheduler -``` - -This is where your modular architecture becomes extremely valuable. - ---- - -# 10. "Replace one algorithm" - -Even better than replacing entire systems. - -Expose interfaces such as: - -```text -VisibilityAlgorithm -LODAlgorithm -BroadphaseAlgorithm -StreamingPolicy -SchedulerPolicy -PortalRecursionPolicy -MemoryAllocator -ECSStoragePolicy -``` - -Then someone could write: - -```text -Atomic default: -Dynamic BVH - -Developer: -GPU spatial hash -``` - -without rewriting the physics engine. - ---- - -# 11. Custom scheduling policies - -This is especially relevant given your wall-clock philosophy. - -Allow developers to define: - -```text -CriticalPathScheduler -ThroughputScheduler -LowLatencyScheduler -DeterministicScheduler -``` - -or even custom policies. - -For example: - -```text -VR game: -prioritize camera latency - -RTS: -prioritize simulation throughput - -Cinematic: -prioritize renderer - -MMO: -prioritize networking + simulation -``` - ---- - -# 12. AI-native Studio - -Since you already have MCP, I'd make AI a **first-class Studio operator**, not merely a chatbot. - -The AI should be able to interact with the same APIs as the developer. - -For example: - -> "Why does this scene run at 48 FPS?" - -AI gets: - -```text -frame captures -GPU timings -ECS statistics -memory -draw calls -LOD -streaming -physics -``` - -and responds: - -> "The largest issue is Portal A. It creates 11 recursive views and consumes 2.4ms. Reducing its recursion budget to 2 would save approximately 1.1ms." - -Then: - -> "Apply that." - -AI changes the actual engine configuration. - ---- - -# 13. AI should operate on structured engine state - -Don't give the MCP agent only: - -```text -screenshots + text -``` - -Give it structured concepts: - -```text -Scene -Entity -Component -Resource -RenderPass -GPUBuffer -Texture -Portal -PhysicsBody -ECSQuery -Job -Frame -MemoryAllocation -``` - -So the AI can reason: - -```text -Entity 1842 - ├─ Mesh: castle_wall - ├─ Material: stone_02 - ├─ LOD: 1 - ├─ GPU resident: yes - └─ Physics: static -``` - -This is vastly more powerful. - ---- - -# 14. AI-generated engine tooling - -Your MCP shouldn't just be: - -> "create an entity." - -It could expose **capability discovery**. - -AI asks: - -```text -What can Atomic do? -``` - -and gets machine-readable descriptions of: - -```text -available systems -available components -available graph nodes -available asset processors -available debug tools -available render features -``` - -Then the AI can construct workflows dynamically. - ---- - -# 15. AI as an engine operator - -Give AI commands like: - -```text -profile_frame() -inspect_entity() -inspect_gpu_memory() -capture_frame() -trace_system() -trace_entity() -find_expensive_assets() -find_stale_gpu_state() -find_sync_points() -find_cache_misses() -compare_frames() -modify_render_graph() -modify_material() -run_benchmark() -``` - -Then AI becomes essentially: - -> **a senior engine programmer sitting inside Studio.** - ---- - -# 16. AI-generated profiling experiments - -This would be particularly good for your architecture. - -Developer: - -> "Find out if increasing portal cache memory by 256MB improves frame time." - -AI: - -```text -Baseline: -GPU: 14.7ms -VRAM: 6.2GB - -Experiment: -Portal cache +256MB - -Result: -GPU: 13.1ms -VRAM: 6.46GB - -Improvement: --1.6ms / -10.9% -``` - -Then: - -> "Keep it." - -This is exactly your **memory-for-wall-clock** philosophy becoming an automated workflow. - ---- - -# 17. AI-generated optimization patches - -AI could identify: - -```text -Physics: -87% of broadphase queries are static-static -``` - -and propose: - -> "Enable static-static pair elimination." - -Then generate a change and benchmark it. - -The important part: - -**AI shouldn't be trusted to declare an optimization successful.** - -Atomic should benchmark it. - -```text -AI hypothesis - ↓ -automated experiment - ↓ -benchmark - ↓ -statistical comparison - ↓ -accept/reject -``` - -That's much safer and more useful. - ---- - -# 18. AI-powered Asset Pipeline - -Developer drops in: - -```text -castle.fbx -``` - -Atomic AI could inspect: - -```text -4.8M triangles -73 materials -214 textures -``` - -and recommend: - -```text -Generate: -✓ 4 LODs -✓ collision hull -✓ SDF -✓ HLOD -✓ impostor -✓ compressed textures - -Warnings: -⚠ 11 redundant materials -⚠ 8 textures unnecessarily 4K -``` - -Then one click: - -> **Optimize Asset** - ---- - -# 19. AI semantic search across the entire project - -Instead of: - -```text -Find "CastleGate" -``` - -ask: - -> "Where do we create physics bodies for destructible structures?" - -or: - -> "What causes this portal to recurse?" - -or: - -> "Show me every system that modifies Transform.Position." - -This requires Atomic's internal metadata/reflection system to be excellent. - -Which leads to: - ---- - -# 20. Deep Reflection / Introspection - -I'd make this a major engine feature. - -Everything has metadata: - -```text -Component -System -Resource -Shader -Graph -Node -Pipeline -Asset -Entity -Property -``` - -Metadata includes: - -```text -type -dependencies -owners -readers -writers -memory -GPU residency -version -serialization -editor UI -AI description -``` - -Then **Studio, MCP, debugging, serialization, documentation and tooling can all use the same reflection layer.** - -That's an enormous architectural win. - ---- - -# 21. Automatic Editor UI from Reflection - -If a component says: - -```text -float mass -range 0–10000 -category Physics -``` - -Studio automatically gets: - -```text -Mass ───────────── 50 kg -``` - -If a resource exposes: - -```text -PortalRecursionDepth -PortalCacheSize -PortalImportance -``` - -Studio generates its inspector. - -This means engine developers don't have to manually build editor panels for everything. - ---- - -# 22. Custom Editor Extensions - -Then developers can add: - -```text -CustomInspector -CustomViewportTool -CustomGraphNode -CustomAssetImporter -CustomGizmo -CustomProfilerView -CustomDebugger -``` - -without modifying Studio itself. - -Think: - -> **Studio is a platform, not a closed application.** - ---- - -# 23. "Everything can become a Studio tool" - -For example, your MCP could create a tool: - -```text -AnalyzePortalPerformance -``` - -and Studio automatically exposes: - -```text -Tools - └─ Analyze Portal Performance -``` - -Likewise an engine plugin can provide: - -```text -Tools - ├─ Bake SDF - ├─ Analyze Physics - └─ Optimize Mesh -``` - -The AI and human developer use the **same underlying tool registry**. - -That's a very nice convergence. - ---- - -# 24. Universal Command Palette - -Have one: - -**Ctrl+K** - -and search literally everything: - -```text -> Render Graph -> Entity 19283 -> Physics Profiler -> Portal A -> Material Stone -> Capture Frame -> Bake SDF -> Generate LOD -> AI: Explain this frame -> AI: Optimize selected asset -> Open ECS Query Inspector -``` - -This makes a giant engine feel much smaller. - ---- - -# 25. Command-driven Studio - -And make Studio deeply commandable. - -Almost everything should be expressible as: - -```text -atomic entity create -atomic asset import -atomic render capture -atomic benchmark -atomic build -atomic profile -atomic test -``` - -Then the same commands work through: - -* GUI -* terminal -* MCP -* scripts -* CI -* AI - -That's extremely valuable. - ---- - -# 26. Reproducible Engine Workspaces - -A project should be able to say: - -```text -AtomicProject - ├── engine configuration - ├── pipeline configuration - ├── plugins - ├── renderer configuration - ├── physics configuration - ├── asset pipeline - ├── editor configuration - └── AI tools -``` - -Then: - -> clone repo → open project → everything reproduces. - -No mysterious machine-local editor state. - ---- - -# 27. Project Profiles - -For example: - -```text -Project - ├── Desktop - ├── SteamDeck - ├── Mobile - ├── VR - └── Console -``` - -Each profile can alter: - -* renderer -* budgets -* shader permutations -* streaming -* physics -* texture quality -* LOD -* CPU/GPU scheduling - -And Studio can preview: - -> **What would this scene look like on Steam Deck?** - ---- - -# 28. Pipeline Versioning - -This one is easy to overlook. - -If your render pipeline is customizable: - -```text -Pipeline v1 -Pipeline v2 -Pipeline v3 -``` - -should be versioned like code. - -Then: - -```text -git diff - -Render Graph: -+ TemporalGI -- SSR -changed ShadowAtlas -``` - -You could even diff **graphs visually**. - ---- - -# 29. Engine-level Undo/Redo - -Not just scene transforms. - -Undo: - -* render graph changes -* ECS schema -* materials -* shaders -* physics configuration -* pipeline configuration -* asset processing -* Studio layout -* project settings - -Your universal delta-state architecture could potentially make this much easier. - ---- - -# 30. "Explain this system" - -This is where AI + reflection + docs becomes really cool. - -Select: - -```text -PhysicsBroadphase -``` - -Click: - -**Explain** - -AI can inspect: - -* source -* metadata -* profiling -* current state -* dependencies - -and explain: - -```text -This broadphase is currently using a dynamic AABB tree. - -Current: -184,392 nodes -7,293 updates/frame -1.2ms - -The largest cost is reinsertion caused by high-velocity objects. -``` - -Not generic documentation. This is **contextual explanation of the actual running engine**. - ---- - -# 31. AI-generated documentation from the running engine - -Because Atomic knows its own reflection metadata: - -```text -Generate documentation -``` - -could produce: - -```text -PhysicsBody - ├── properties - ├── lifecycle - ├── threading guarantees - ├── determinism guarantees - ├── GPU interaction - └── performance characteristics -``` - -And keep it synchronized with the actual API. - ---- - -# 32. Automated Performance Contracts - -This would be very Atomic. - -Developers could specify: - -```text -Portal recursion ≤ 1ms -Physics ≤ 2ms -Renderer ≤ 10ms -Frame ≤ 16.67ms -VRAM ≤ 8GB -``` - -Then CI runs benchmark scenes. - -```text -Performance Contract - -Frame time: -Target 16.67ms -Actual 15.92ms ✓ - -VRAM: -Target 8GB -Actual 7.42GB ✓ - -Portal: -Target 1ms -Actual 1.08ms ✗ -``` - -This prevents performance regression. - ---- - -# 33. Performance as a first-class test - -Instead of only: - -```text -assert result == expected -``` - -allow: - -```text -assert frame_time < 16.67ms -assert gpu_memory < 8GB -assert synchronization_count < N -assert draw_count < N -assert cache_miss_rate < X -``` - -This fits your existing emphasis on benchmark-driven development extremely well. - ---- - -# 34. Automatic "Optimization Suggestions" - -Studio could continuously surface: - -```text -⚡ Optimization Opportunities - -Portal A: -cache hit rate 43% -Potential saving: ~0.8ms - -Texture X: -resident but unused -Potential saving: 212MB - -ECS Query #42: -random memory access -Potential saving: ~0.3ms - -Physics: -12,400 sleeping bodies being queried -Potential saving: ~0.2ms -``` - -And AI can investigate them. - ---- - -# 35. Customization should extend all the way down - -I'd make Atomic's customization hierarchy something like: - -```text -Project - ↓ -Engine configuration - ↓ -Subsystem implementation - ↓ -Algorithm - ↓ -Data representation - ↓ -Scheduling policy - ↓ -Pipeline - ↓ -Shader - ↓ -GPU implementation -``` - -A developer should be able to say: - -> "I want Atomic's ECS, but my own renderer." - -or: - -> "Atomic renderer, custom physics." - -or: - -> "Atomic physics, but replace broadphase." - -or: - -> "Default renderer, but replace shadow pipeline." - -or: - -> "Default everything except how GPU residency is managed." - -**No fork required.** - ---- - -# 36. But don't expose complexity by default - -This is the counterbalance. - -You don't want a new developer opening Atomic and seeing: - -```text -847 configuration options -``` - -So have levels: - -### Beginner - -```text -Graphics Quality: High -Physics Quality: High -Streaming: Automatic -``` - -### Advanced - -```text -LOD distances -shadow budgets -GI -physics iterations -``` - -### Engine - -```text -render graph -schedulers -residency -allocators -pipeline nodes -``` - -### Expert - -```text -custom implementations -GPU synchronization -memory layouts -execution policies -``` - -**Progressive disclosure** is probably essential. - ---- - -# 37. One API for Human + AI + Automation - -This is the part I'd be most deliberate about. - -Don't build: - -```text -Studio API -MCP API -CLI API -Plugin API -``` - -as separate systems. - -Build: - -```text - Atomic Tool/Reflection API - │ - ┌───────────────┼───────────────┐ - ↓ ↓ ↓ - Studio CLI MCP - │ │ │ - └───────────────┼───────────────┘ - ↓ - Engine Runtime -``` - -Then anything you expose to one can potentially be exposed to all three. - -That would make your existing MCP dramatically more valuable. - ---- - -# 38. The really ambitious version: AI can build Studio itself - -Because everything is reflected and graph-based: - -> "Create me a profiler that shows ECS cache misses by archetype." - -AI creates: - -```text -Tool - ├── data source - ├── query - ├── visualization - └── interaction -``` - -and installs it into Studio. - -Or: - -> "Make a portal debugging panel showing recursive view cost." - -AI generates the panel. - -This becomes **AI-extensible tooling**, rather than AI merely generating game scripts. - ---- - -# 39. Atomic as an engine you can interrogate - -I'd ultimately want this experience: - -Developer: - -> **Why is my frame slow?** - -Atomic: - -> Portal recursion accounts for 18.4% of GPU time. - -Developer: - -> **Why?** - -Atomic: - -> Portal A generates 9 views. Four overlap substantially with cached View 1832. Increasing the cache by 128MB is predicted to reduce GPU time by 0.7ms. - -Developer: - -> **Test it.** - -Atomic: - -> Benchmark complete. 1,000 frames. -> Baseline: 14.83ms ±0.11 -> New: 14.09ms ±0.09 -> Improvement: 5.0% -> VRAM: +126MB. - -Developer: - -> **Keep it.** - -That is the sort of workflow I'd aim for. - ---- - -# The big DX/AI roadmap I'd add - -### 🧠 Engine Intelligence - -* [ ] Runtime reflection -* [ ] Universal metadata system -* [ ] Dependency graph introspection -* [ ] Engine state query API -* [ ] Performance reasoning API -* [ ] Temporal state inspection -* [ ] GPU residency inspection - -### 🛠 Studio - -* [ ] Universal inspector -* [ ] Universal command palette -* [ ] Runtime debugging -* [ ] Visual system graphs -* [ ] Render graph editor -* [ ] Physics debugger -* [ ] ECS debugger -* [ ] GPU memory inspector -* [ ] Frame debugger -* [ ] Time-travel debugger -* [ ] Replay system -* [ ] Live editing -* [ ] Hot reload -* [ ] Visual profiler -* [ ] "Why?" inspector -* [ ] Performance opportunity detector - -### 🧩 Extensibility - -* [ ] Plugin API -* [ ] Custom components -* [ ] Custom systems -* [ ] Custom render nodes -* [ ] Custom physics algorithms -* [ ] Custom schedulers -* [ ] Custom allocators -* [ ] Custom asset processors -* [ ] Custom inspectors -* [ ] Custom Studio tools -* [ ] Custom graph nodes -* [ ] Custom pipeline implementations - -### 🤖 AI - -* [ ] MCP engine introspection -* [ ] MCP Studio control -* [ ] Structured engine-state API -* [ ] Tool discovery -* [ ] AI profiler -* [ ] AI debugger -* [ ] AI asset optimizer -* [ ] AI performance experiments -* [ ] AI-generated Studio tools -* [ ] AI-generated pipeline modifications -* [ ] AI documentation -* [ ] AI benchmark analysis -* [ ] AI-assisted render graph design - -### ⚡ Performance DX - -* [ ] Performance contracts -* [ ] Automated benchmark scenes -* [ ] Performance regression CI -* [ ] Frame capture/replay -* [ ] Deterministic replay -* [ ] Optimization experiments -* [ ] CPU/GPU critical-path visualization -* [ ] Synchronization visualization -* [ ] Cache behavior visualization -* [ ] Memory-for-time experiments -* [ ] Automatic algorithm benchmarking - -### 🎛 Custom Pipeline - -* [ ] Renderer replacement -* [ ] Physics replacement -* [ ] ECS storage policies -* [ ] Scheduler policies -* [ ] Visibility policies -* [ ] LOD policies -* [ ] Streaming policies -* [ ] Memory allocator policies -* [ ] GPU residency policies -* [ ] Temporal policies -* [ ] Portal recursion policies -* [ ] Per-platform pipeline profiles - ---- - -## One architectural principle I'd add to the documents - -I think this is the missing piece tying together **ECS-first + GPU residency + delta synchronization + portals + parallelism + AI + Studio**: - -> **Atomic exposes the same underlying engine state and capabilities to runtime systems, Studio, plugins, automation, CLI tooling, and AI agents through a common reflection, command, and introspection layer.** - -Then: - -```text - ATOMIC ENGINE - │ - ┌─────────┴─────────┐ - │ Reflection/API │ - │ Command System │ - │ State Introspection - └─────────┬─────────┘ - │ - ┌──────────────┬───────┼────────┬──────────────┐ - ↓ ↓ ↓ ↓ ↓ - Runtime Studio Plugin CLI MCP - │ │ │ │ │ - └──────────────┴───────┼────────┴──────────────┘ - ↓ - SAME ENGINE STATE -``` - -That means **AI doesn't get a special fake interface to the engine**. It gets the same capabilities a human developer gets, subject to permissions. - -And I think that pairs exceptionally well with your ECS-first philosophy: the ECS remains the authoritative semantic state, while GPU-resident state, caches, derived state, render views, physics structures, temporal histories, etc. are inspectable derived representations rather than opaque magic. Your existing architecture is already explicitly trying to keep the engine layers separated this way. - -The end goal is basically **"the engine is self-describing and self-debugging."** That's much more ambitious, and IMO much more interesting, than simply building another Studio with an MCP bolted onto it. +# Revisit ideas + +## Status + +This used to be a 6,905-line brainstorm. Its system proposals duplicated the +canonical plans in this directory, while many of its claims predated work that +has since landed. Do not use it as a design or implementation plan. + +## Canonical plans + +Use the system plan that owns the work: + +- [`audio-system.md`](audio-system.md) +- [`camera-and-cinematics.md`](camera-and-cinematics.md) +- [`character-system.md`](character-system.md) +- [`input-system.md`](input-system.md) +- [`navigation-ai-system.md`](navigation-ai-system.md) +- [`physics-expansion.md`](physics-expansion.md) +- [`prefab-package-system.md`](prefab-package-system.md) +- [`procedural-generation.md`](procedural-generation.md) +- [`session-and-social.md`](session-and-social.md) +- [`terrain-system.md`](terrain-system.md) +- [`ui-system.md`](ui-system.md) +- [`vfx-system.md`](vfx-system.md) +- [`world-streaming.md`](world-streaming.md) + +The active release work remains in [`ROADMAP.md`](../../ROADMAP.md). Physics +performance candidates live in [`OPTIMISATIONS_PHYSICS.md`](OPTIMISATIONS_PHYSICS.md). + +## Deferred orphaned ideas + +These ideas do not yet have an owning system plan. Add one to a system plan +only after a concrete product need and a measurable acceptance gate exist. + +- Virtual geometry, virtual texturing, virtual shadow maps, and GPU-driven + scene submission as one measured renderer residency program. +- HLOD, impostors, foliage, decals, water, volumetrics, and distance fields as + content-scale rendering features. +- Temporal rendering, dynamic resolution, variable-rate shading, and + automatic quality allocation as a coherent frame-budget policy. +- A first-class material and shader permutation pipeline. +- A frame capture and replay format for renderer diagnosis. +- A shared signed-distance-field service, only if more than one subsystem has + a measured need for it. +- Runtime simulation and animation LOD, after the owning gameplay systems + define acceptable loss of fidelity. +- An engine-wide performance-budget and regression suite, based on real + release scenes rather than generic thresholds. +- Time-travel inspection and subsystem freezing in Studio, after recording + exposes a stable snapshot contract. +- Pipeline versioning, graph overrides, and live algorithm replacement, only + where a safe immutable handoff already exists. + +Each item is deliberately a short reminder, not a specification. The old +document contained competing designs for all of them and made it impossible to +tell which, if any, was current. diff --git a/docs/future-work/TORNADOSIM.md b/docs/future-work/TORNADOSIM.md deleted file mode 100644 index 66be2e5c9..000000000 --- a/docs/future-work/TORNADOSIM.md +++ /dev/null @@ -1,100 +0,0 @@ -# TornadoSim pure Luau port - -This demo ports TornadoSim's arcade result, not its C++ implementation. One -analytical wind field drives every moving thing. It is cheap, deterministic and -good enough for a game scene without a fluid solver. - -The [render refactor plan](RENDER-REFACTOR.md#16-particles-environment-and-tornadosim) -owns the generic particle, field, cloud, lighting and render-test work this demo -can prove necessary. This document keeps the gameplay slice and its proof gates. - -## Source scope - -The source lab has one useful core and several costly presentation systems. - -| Source feature | Pure Luau demo | First pass | -|---|---|---| -| Tangential wind, inflow, lift and turbulence | One `SampleField` function | Yes | -| EF-style storm presets and lifecycle | Tables and script clock | Yes | -| Condensation funnel and dust | `ParticleEmitter` layers | Yes | -| Rain shaft and cloud deck | Particle emitters, `CloudCompute`, atmosphere | Yes | -| Loose debris and tree bend | Kinematic parts with script-held velocity | Yes | -| Lightning and hazard readout | Beam, point light and script UI | Yes | -| Buildings losing pieces | Script-controlled break groups | Yes | -| Full rigid-body debris collision | Engine physics body control | No | -| 1M to 50M custom compute particles | Native render compute path | No | -| Sparse cloud density octree | Native volume renderer | No | -| Procedural spatial audio | Authored audio content and mixer work | No | - -## Existing engine doors - -The first pass needs no engine library or component. - -- `RunService.Heartbeat` runs the field, lifecycle, moving debris and controls. -- `Part`, `Model`, `CFrame`, `Vector3` and `math.noise` are enough for the - analytical field and a bounded kinematic scene. -- `ParticleEmitter` already supplies disc and cylinder shapes, inward and - outward emission, tangential and radial acceleration, noise, drag, size and - transparency curves. GPU simulation owns the visual particles. -- `SkyboxCompute`, `AtmosphereProcedural`, `CloudCompute`, `PointLight`, - `Beam`, `Trail` and `Sound` cover the weather presentation surface. -- Screen GUI controls and labels are available from Luau. - -## First demo slice - -`mono.engine/examples/assets/scripts/TornadoSim.luau` will contain all gameplay state. It -will build a storm plain, a single travelling vortex, a few structures and a -camera. It will expose a compact preset selector and a live hazard display. - -The authoritative function samples an offset from the storm centre and returns -the local velocity and intensity. It uses the same stable shape as TornadoSim: - -1. A softened maximum-wind ring. -2. Outer radial inflow with a smooth influence falloff. -3. Strong central lift and weak distant circulation. -4. Height-based upper wind and deterministic turbulence. - -Every consumer calls that one function. Loose debris stores position, velocity, -mass response and age in one Luau table. The script integrates it at a bounded -step, gives it a ground bounce, and writes its `CFrame`. Trees bend visually; -small building groups release when their local hazard crosses their declared -strength. The field itself remains the only source of wind truth. - -Visual particles stay GPU-owned. A small number of stationary and travelling -emitters make the dust base, condensation funnel, rain curtain and upper cloud -deck. They use the same storm centre and preset values, but do not copy a CPU -particle simulation into Luau. - -## Boundaries for the first pass - -- Keep moving scripted debris bounded. It is a readable gameplay layer, not a - CPU particle system. -- Do not add `ApplyImpulse`, velocity properties, a tornado component or a - native field library before the scene proves they are needed. -- Do not claim rigid collisions, fluid behaviour, volumetric clouds or - million-particle custom compute from this scene. -- Use no external assets for the first runnable version. A later sound pass - needs published wind and thunder content. - -## Proof gates - -- Luau typecheck passes for the new example. -- A headless client run loads the script and advances the world without errors. -- A visual run shows the moving funnel, rain, debris, bend and lightning. -- The status panel reports the sampled wind and hazard at the camera. -- A release profile records the scripted debris count and particle count before - any performance claim. - -## Engine work only after evidence - -Add an engine door only when the first demo hits one of these walls: - -| Proven wall | Smallest follow-up | -|---|---| -| Kinematic debris is not enough | Expose velocity and impulse through existing physics bodies. | -| Particle emitters cannot follow the field shape | Add a generic field-sampling particle force, not a tornado-specific renderer. | -| The scene needs dense cloud self-shadowing | Add a generic volume resource and render node. | -| The scene needs large destruction | Build reusable script-facing break groups before a damage system. | - -This keeps the demo a script consumer first. The engine earns new code only -after the script has shown the missing cut point. diff --git a/docs/future-work/character-system.md b/docs/future-work/character-system.md index 9dfd56e13..789d107ca 100644 --- a/docs/future-work/character-system.md +++ b/docs/future-work/character-system.md @@ -47,6 +47,22 @@ The current default root is described as a capsule but uses a box. That is the first mismatch to remove. `ShapeKind::Capsule` already exists in scene, queries, narrow phase, solving, and Studio collider drawing. +### Predeclared rig and animation storage + +`scene::Skeleton`, `scene::Bone`, `scene::AnimationClip`, `scene::Animator`, +and `scene::AnimationTrack` must register before `ecs::Components::Seal()`. +Registration deferred until an importer, script, or animation system first +uses a row works in an isolated test but rejects a saved character when a host +has already sealed its component registry. + +`Skeleton` and `Bone` remain optional rig rows. `Animator` and +`AnimationTrack` remain general animation rows, so a door or other non-character +object may use them without acquiring character state. `AnimationClip` names +immutable published clip content; `AnimationBuffer` remains the mutable, +world-owned authoring and procedural-bake path described below. None of these +optional rows gains a `MeshPart` property: a property that fails for almost +every unrigged mesh is a misleading script surface. + ## External design checks The plan was checked against current first-party engine documentation. These diff --git a/docs/future-work/physics-expansion.md b/docs/future-work/physics-expansion.md index 81eb0d38e..0704c5f7d 100644 --- a/docs/future-work/physics-expansion.md +++ b/docs/future-work/physics-expansion.md @@ -142,6 +142,11 @@ constraint target, or explicit operation reaches them. ## Constraints and joints +`scene::Constraint` must register before `ecs::Components::Seal()`. A world +that first encounters a saved constraint after startup must be able to load it; +the physics implementation may be unwired while its authored storage is already +part of the world format. + ### One six-axis representation `scene::Constraint` remains the authored representation. Its two attachment diff --git a/docs/future-work/procedural-generation.md b/docs/future-work/procedural-generation.md index fcb2698e0..68a4faf63 100644 --- a/docs/future-work/procedural-generation.md +++ b/docs/future-work/procedural-generation.md @@ -1023,10 +1023,10 @@ procedural artifacts and do not run through this scheduler. ### Materials and shaders -The [render refactor plan](../RENDER-REFACTOR.md#7-materials-and-shader-publication) owns material -instances, shader variants, and GPU rules. Procedural image and parameter -generation may publish ordinary material dependencies. Runtime shader -compilation and render graph execution remain outside this system. +The render pipeline documentation owns material instances, shader variants, and +GPU rules. Procedural image and parameter generation may publish ordinary +material dependencies. Runtime shader compilation and render graph execution +remain outside this system. ## Migration from current experiments diff --git a/docs/future-work/terrain-system.md b/docs/future-work/terrain-system.md index b1b608214..abf33da36 100644 --- a/docs/future-work/terrain-system.md +++ b/docs/future-work/terrain-system.md @@ -346,6 +346,11 @@ policy: Large override maps and edit journals are referenced by stable asset or resource name instead of embedded into a fixed-size component. +`scene::Terrain` registers before `ecs::Components::Seal()` as a world resource, +not as a constructible `Terrain` instance. It holds the graph and seed that +describe terrain. Generated chunks remain derived artifacts owned by the terrain +runtime, never saved ECS rows or network payloads in place of their inputs. + ### Generation request An immutable request contains: diff --git a/docs/future-work/vfx-system.md b/docs/future-work/vfx-system.md index bfaa94433..65cb474f5 100644 --- a/docs/future-work/vfx-system.md +++ b/docs/future-work/vfx-system.md @@ -1123,6 +1123,26 @@ buffer. The reference is explicit and serializable. The live effect samples the new revision at a simulation barrier and applies a declared restart or migrate policy. +### TornadoSim demo boundary and proof + +`mono.engine/examples/assets/scripts/TornadoSim.luau` is a bounded script demo, +not a tornado-specific engine system. One analytical Luau wind-field function +drives kinematic debris, tree bend, hazard readout, and the parameters of +existing GPU particle emitters. The script owns its storm state and caps moving +debris. GPU emitters own visual particle state. + +The initial demo does not prove rigid-body debris, fluid behaviour, volumetric +clouds, dense custom compute particles, or destruction simulation. It earns a +generic engine extension only when a measured scene reaches a clear boundary: +physics-body velocity and impulse for debris, field-sampled particle force for +emitter shape, volume resources for cloud self-shadowing, or script-facing break +groups for reusable destruction. + +Proof requires Luau typechecking, a headless load with world advancement, a +visual run showing funnel, rain, debris, bending, and lightning, plus a release +profile reporting scripted-debris and particle counts before any performance +claim. + ### Asynchronous work Compile, preload, and bake calls return the repository's normal ticket or diff --git a/mono.engine/examples/assets/scripts/TornadoSim.luau b/mono.engine/examples/assets/scripts/TornadoSim.luau index 41b86970d..5a2560d1c 100644 --- a/mono.engine/examples/assets/scripts/TornadoSim.luau +++ b/mono.engine/examples/assets/scripts/TornadoSim.luau @@ -1,8 +1,9 @@ --!strict -- An arcade tornado scene driven entirely by one Luau wind field. -- --- `docs/TORNADOSIM.md` records why this uses kinematic debris and existing GPU --- emitters rather than a new tornado-specific engine system. +-- `docs/future-work/vfx-system.md` §"TornadoSim demo boundary and proof" +-- records why this uses kinematic debris and existing GPU emitters rather than +-- a tornado-specific engine system. local Lighting = game:GetService("Lighting") local Players = game:GetService("Players") From 555cdbe321669eeca9bb7727f87d12b90ce0f259 Mon Sep 17 00:00:00 2001 From: SPOOK_EXE <91944990+SPOOKEXE@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:38:21 +0930 Subject: [PATCH 007/564] Bound build cache growth and avoid PCH preprocessing on cache misses --- CMakeLists.txt | 7 +++++++ Justfile | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5ac7c9f2d..84f00a378 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -392,6 +392,12 @@ endif() # nondeterministic bytes into every `.gch`, so precompiled-header users never # share across presets whatever is set here. # +# `CCACHE_DEPEND=true` keeps a cache miss out of the preprocessor. Without it, +# ccache runs `cc1plus -E -fpch-preprocess` on a PCH-backed source. One physics +# object grew that process past 66 GiB RSS before it was stopped. Ninja already +# requests dependency files with `-MD`, which is what depend mode hashes. +# Direct hits still work; a miss compiles once instead of expanding the PCH. +# # Two calls per build still report as errors, and they are the two PCH # *generation* steps - ccache cannot parse a header as a source, so it passes # them to the compiler untouched. Correct, and 0.11% of the build. @@ -440,6 +446,7 @@ if(MONO_CCACHE) "CCACHE_SLOPPINESS=pch_defines,time_macros" "CCACHE_BASEDIR=${CMAKE_SOURCE_DIR}" "CCACHE_NOHASHDIR=true" + "CCACHE_DEPEND=true" "${MONO_COMPILER_CACHE}") else() set(MONO_CACHE_LAUNCHER "${MONO_COMPILER_CACHE}") diff --git a/Justfile b/Justfile index 44928435c..23aac97e5 100644 --- a/Justfile +++ b/Justfile @@ -1764,6 +1764,40 @@ em-dash-check: fi echo "em-dash-check ok - no U+2014 in ${#files[@]} first-party file(s)" +# Shows which complete preset trees can be reclaimed without touching sources, +# downloads, the test signature cache or the shared compiler cache. `yes` is +# required to delete. dev and release are kept for the normal edit/ship loop; +# ci and the other checks can be rebuilt from their presets when needed. +build-prune apply="no": + #!/usr/bin/env bash + set -euo pipefail + case "{{apply}}" in + no|yes) ;; + *) echo "Use 'just build-prune' to preview or 'just build-prune yes' to delete." >&2; exit 2 ;; + esac + root=$PWD + total=0 + for dir in .cache/build/*/; do + [ -d "$dir" ] && [ ! -L "$dir" ] || continue + name=${dir%/} + name=${name##*/} + case "$name" in dev|release) continue ;; esac + cache="$dir/CMakeCache.txt" + [ -f "$cache" ] || continue + # A build directory copied from another checkout does not belong to us. + if ! grep -qxF "CMAKE_HOME_DIRECTORY:INTERNAL=$root" "$cache"; then + echo "skipping $dir: CMake source is not this checkout" + continue + fi + bytes=$(du -sx --block-size=1 "$dir" | cut -f1) + total=$((total + bytes)) + printf '%-28s %8d MiB\n' "$dir" "$((bytes / 1048576))" + if [ "{{apply}}" = yes ]; then + rm -rf -- "$dir" + fi + done + printf '%s: %d MiB %s\n' build-prune "$((total / 1048576))" "$(if [ "{{apply}}" = yes ]; then echo reclaimed; else echo reclaimable; fi)" + clean: rm -rf .cache/build From b86ea798d8e04fc3fc87f7e991f9e3496b35acd8 Mon Sep 17 00:00:00 2001 From: SPOOK_EXE <91944990+SPOOKEXE@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:39:59 +0930 Subject: [PATCH 008/564] Plan v0.25 render and MCP cleanup --- docs/v025-MCP-CLEANUP.md | 411 +++++++++++++++++++++++++++ docs/v025-RENDER-PIPELINE-CLEANUP.md | 219 ++++++++++++++ 2 files changed, 630 insertions(+) create mode 100644 docs/v025-MCP-CLEANUP.md create mode 100644 docs/v025-RENDER-PIPELINE-CLEANUP.md diff --git a/docs/v025-MCP-CLEANUP.md b/docs/v025-MCP-CLEANUP.md new file mode 100644 index 000000000..bbb8128a9 --- /dev/null +++ b/docs/v025-MCP-CLEANUP.md @@ -0,0 +1,411 @@ +# v0.25 MCP consolidation and cleanup plan + +## Decision + +Keep one engine-hosted MCP surface. Keep `mcpbridge` as the byte-only stdio +adapter. Consolidate the growing product and data-factory additions behind +runtime-owned feature hooks that can be enabled and disabled safely. + +Do not introduce dynamically loaded shared libraries in v0.25. Runtime loading +of native binaries adds ABI, allocator, exception, thread, and unload hazards +before the feature boundary is proven. The first form of hot loading means +installing and removing already-linked providers at runtime. A later plugin ABI +can sit outside the same provider contract once it has a concrete consumer. + +The target is a small, stable control kernel with optional compiled hook +providers. A product creates the kernel once, gives it an owner-thread pump, +and activates named providers only while their backing services exist. Removal +waits for work accepted by that provider to reach a terminal state before it +removes all owned rows and releases captured references. + +## Scope and sources + +This plan covers the MCP control surface, not the external collector, model +training, or dataset-writer implementation. + +`MCP-ADDITIONS.md` is not in this checkout. It was removed in commit +`e464d5c1`; the full historical proposal is available at +`0d0d0b4e:MCP-ADDITIONS.md`, and the current sibling handoff copy is +`../datafactories-docs/MCP-ADDITIONS.md`. Those documents are useful for +intent, vocabulary, bounded-resource rules, and acceptance ideas. They are not +an implementation inventory. Current source and +`mono.engine/control/docs/MCP.md` are the authority for what ships today. + +The historical proposal is much broader than the active narrow handoff. The +active handoff is the revision-fenced `raw-scene/v1` extraction and the existing +factory lifecycle, scene observation, capture, and retained-resource rows. +Everything else must enter as a separately negotiated capability with a named +owner, bounds, lifecycle, and test plan. + +## Current map + +```mermaid +flowchart LR + Client[MCP client] --> Bridge[mcpbridge\nstdio byte pump] + Bridge --> Socket[loopback control Server] + Socket --> Surface[control::Surface\nJSON-RPC and row tables] + Surface --> Core[always-on features\ndiscovery, resources, prompts] + Surface --> Product[product rows\nStudio, client, server, CDN] + Surface --> Factory[data-factory and observation rows] + Factory --> World[DataFactorySession\nworld lifecycle and fences] + Factory --> Render[renderer capture bridge\nasync tickets and resources] +``` + +`control::Server` accepts one loopback client and pumps requests on the host +thread. `Surface::Answer` implements the MCP handshake and dispatches +`tools/*`, `resources/*`, and `prompts/*`. `mcpbridge` intentionally parses no +MCP and forwards bytes between stdio and the loopback socket. This separation is +sound and should remain. + +Products presently assemble feature arrays themselves. Studio changes the list +when `DataFactoryHost` is present. Client conditionally adds data-factory, +audio, script-package, capture, scene, and observation rows. Server and CDN +have their own lists and custom rows. That makes capability shape depend on +several distant construction sites. + +`Surface::Add`, `AddResource`, and `AddPrompt` replace an equal name or URI, +and `Enable` only invokes installers. It does not record provider ownership, +provide removal, prevent a cross-provider overwrite, or drain in-flight work. +Provider lambdas commonly borrow host services. Therefore simply erasing a row +after a host subsystem changes lifetime would be unsafe. + +The largest concentration is in public feature headers: `DataFactory.hpp` +(2,150 lines), `DataScene.hpp` (1,795), and `DataCapture.hpp` (1,386). Each +mixes schemas, argument parsing, operation-ledger use, host calls, result +mapping, and row registration. This is the primary cleanup target. + +## Findings to preserve + +- The loopback-only, one-client control listener is a deliberate local-editor + contract. Do not turn it into a network service as part of cleanup. +- Protocol dispatch stays in one implementation. A new bridge must not parse or + duplicate JSON-RPC semantics. +- Stable strings cross MCP, exported resources, and external manifests. ECS + handles, `Name::Id()`, and declaration-order numbers remain process local. +- Factory writes are fenced by instance, tick, world epoch, and world version. + Keep those checks at every stateful boundary. +- Long operations use the bounded operation ledger and explicit polling. A + timeout is recovered with the same operation ID and canonical arguments. +- Capture remains renderer-owned, bounded, asynchronous, and resource based. + A hook cannot call arbitrary code from the render thread or expose mutable + render state. +- `tools/list` and `negotiate` are the capability contract. A disabled feature + must disappear from both, rather than remain listed and refuse later. + +## Proposed structure + +`mono.engine/control` is shared at L13 and `mono.engine/render` is client tier +at L12. A shared module cannot link a client module. The control kernel must +never depend on renderer headers, symbols, or providers. This is a hard tier +boundary, not a cleanup preference. + +Keep the generic registry and its lifecycle implementation inside `control`, +under `src/hooks/`, where it has no renderer dependency. In v0.25, providers +remain host-local adapters. This keeps the existing tier graph intact while the +provider contract and the actual reuse boundary are proven. + +Keep render capture and render inspection adapters at the client product +boundary for v0.25: `mono.client/src/ControlHooks.cpp` and the corresponding +Studio composition source own the typed renderer context and register their +providers with the shared registry. They can link both `control` and `render` +because the product is already the composition root. Do not put this adapter in +`render`, because L12 `render` cannot link upward to L13 `control`. + +If equivalent host-local adapters persist after the migration, stop and design +their shared home as a separate architecture task. That design must establish a +valid tier and layer for its dependencies before code moves. This plan approves +no new adapter module. `control` remains the protocol kernel and product sources +own final host-local composition. + +```text +mono.engine/control/ + include/engine/control/Surface.hpp protocol kernel and immutable rows + include/engine/control/HookRegistry.hpp provider lifecycle API + src/Surface.cpp JSON-RPC dispatch only + src/HookRegistry.cpp ownership, activation, drain + src/features/ small universal features + src/hooks/ registry internals only + +mono.client/, mono.server/, mono.studio/, mono.cdn/ + src/ControlHooks.cpp compose only providers this host owns + src/ClientCaptureHook.cpp client-only renderer adapter where applicable +``` + +Do not move code merely to make the tree look even. Extract one vertical slice +at a time: schema and validation first, then service adapter, then row builder. +Keep each tool name and JSON schema byte-for-byte compatible until its explicit +contract revision says otherwise. + +### Kernel API + +Use these value-oriented concepts. The final names can follow local style, but +their ownership rules must not change. + +| Type | Responsibility | Required properties | +| --- | --- | --- | +| `HookId` | Stable provider discovery name, such as `data_factory.capture`. | String at all external boundaries. Unique per surface. | +| `HookDescriptor` | Purpose, version, dependencies, capability summary, and declared row names. | Pure metadata. Readable while inactive. | +| `Hook` | Compiled provider factory. | Creates one activation from explicit host services. | +| `HookActivation` | The installed rows, subscriptions, tickets, and teardown logic. | Owns every registration it creates. Noncopyable. | +| `HookLease` | Registry-owned active provider handle. | Generation-bearing. Idempotent close. | +| `HookContext` | Typed dependencies supplied by one product. | No generic service bag, no `void *`, no upward product dependency. | +| `HookState` | `inactive`, `starting`, `active`, `draining`, `failed`. | Queryable through discovery. | + +Rows require an owner token containing the hook ID and activation generation. +`Surface` indexes tools by name, resources by URI, and prompts by name, but the +registry is the only API allowed to add or remove owned rows. A duplicate row +from another active hook fails activation with both owners named. Replacement +within an activation is prohibited. This replaces accidental last-writer-wins +with an observable configuration error. + +Feature functions that are permanently small and host-independent may continue +to register through the kernel during construction. Optional features move to +host-local hooks with typed contexts. Data factory, raw scene, audio, rig, +temporal, visibility, and product rows stay with the host that already owns +their dependencies until a separate architecture design proves a shared home. +Capture, render graph, and camera-rendering-data rows remain client product +hooks, with their renderer dependency outside shared control code. + +### Activation and removal contract + +```mermaid +stateDiagram-v2 + [*] --> Inactive + Inactive --> Starting: enable(id, typed context) + Starting --> Active: all rows installed + Starting --> Inactive: validation or collision failure + Active --> Draining: disable(id) + Draining --> Inactive: rows removed, work terminal, references released + Draining --> Draining: drain timeout is reported and cancellation is refused + Active --> Failed: backing service becomes unavailable + Failed --> Draining: disable(id) +``` + +Activation validates the declared dependency hooks and typed context before it +publishes any row. It then builds rows privately, validates duplicate names, +installs them as one registry transaction, and publishes a changed capability +generation. A failed activation leaves the previous surface untouched. + +Each tool call obtains a short-lived activation guard before invoking its +callback. Disabling first stops new guards, then invokes the provider's +`BeginDrain`. The provider cancels work that has not started, polls or completes +already-started work, releases retained resources only under existing capture +rules, unregisters callbacks, and finally removes its rows. It cannot unload +while a callback, asynchronous ticket, renderer submission, or resource reader +still holds its generation. + +Use the existing bounded operation ledger and capture ticket state as the first +drain participants. Do not add a second operation tracker. `world_retire` is +allowed only after dependent hooks have drained. Renderer capture removal keeps +its current rule: pending work reaches a terminal result, then resources follow +their explicit release or TTL policy. + +The host pump remains single-threaded. Cross-thread producers publish copied +terminal records into the existing bounded queues and never retain a `Surface`, +tool lambda, or host-world pointer. Unload acknowledgements return to the host +thread before row removal. + +### Capability discovery + +Keep MCP-standard `tools/list`, `resources/list`, and `prompts/list` as the +source for callable rows. Extend the engine `negotiate` response with: + +```json +{ + "control_generation": 17, + "hooks": [ + { + "id": "data_factory.capture", + "state": "active", + "revision": "v1", + "tools": ["capture_bundle", "poll_capture", "get_resource"], + "limits": {"maximum_in_flight": 8} + } + ] +} +``` + +The response reports inactive optional hooks only when the caller has requested +diagnostic discovery. Normal capability discovery lists active hooks and their +actual limits. Every activation and removal increments `control_generation`. +The bridge need not change because the protocol response remains ordinary JSON. + +Do not claim MCP dynamic `listChanged` support until the server can notify +connected clients correctly. During v0.25, a client refreshes `negotiate` and +the lists after an acknowledged hook operation. The kernel continues to report +`listChanged: false`. + +## Consolidation matrix + +| Area | Current evidence | Target hook or kernel owner | Migration and test point | +| --- | --- | --- | --- | +| JSON-RPC, tool/resource/prompt tables | `Surface.cpp` owns all standard dispatch. | `control` kernel. | Preserve response envelopes, notification behavior, and unknown-row handling with transcript tests. | +| Loopback listener and stdio bridge | `control::Server` has one client; `mcpbridge` forwards bytes. | `control` transport and `mono.tools/mcpbridge`. | Keep byte forwarding. Add host restart, early stdin close, and disabled-hook discovery integration tests. | +| Common discovery and docs resources | `Discovery`, `Resources`, `Prompts`, architecture and diagnostics features. | Built-in kernel features. | Make construction declarative and compare current schema snapshots. | +| Product rows | Studio, client, server, and CDN each call `Surface.Enable` and add custom rows. | Product `ControlHooks.cpp` composition. | Test the exact enabled-hook manifest per product and expected unavailable capabilities. | +| Factory lifecycle and replay ledger | `DataFactory.hpp`, `DataFactoryOperationLedger`, `world::DataFactorySession`. | Factory host-local hook over the existing session. | Preserve canonical-argument replay, fences, reset, retirement, pause, step, checkpoint, restore, fork, and intervention tests. | +| Raw scene reads and exports | Raw or glTF retained exports in `DataScene.hpp`. | Host-local raw-scene hook. | Test snapshot fence, byte range bounds, stable IDs, release, and teardown retention. | +| Camera rendering data | `get_camera_rendering_data` in `DataScene.hpp`. | Client or Studio product scene-rendering hook. | Test matching snapshot, epoch, view, pipeline, and renderer generation. | +| Render capture | `DataCapture.hpp`, client render bridge, tickets, resources. | Client or Studio product capture hook. | Test queued, ready, cancelled, failed, and drained tickets. Verify snapshot, epoch, view, pipeline, and resource identities. | +| Read-only observation slices | temporal, visibility, rig, audio, occupancy, SDF, and navigation rows. | One hook per independently useful service family. | Test availability, hard bounds, stale fence, unavailable reason, and no world mutation. | +| Script package and render-only operation | control adapter plus product-host callbacks. | Factory host-local package hook; client product `FactoryRender`. | Use explicit dependency on Factory. Test hook activation only when callbacks exist. | +| Renderer graph inspection | `RenderGraph.hpp` and client provider. | Client or Studio product render-inspection hook. | Test no renderer dependency in shared targets or headless products and clean removal after renderer shutdown. | + +## Areas requiring investigation before moving code + +1. Establish the source of truth for every advertised tool. `MCP.md`, + `tools/list`, `negotiate`, and external typed client definitions must be + compared automatically. The plan must resolve any name, required-field, + limit, and error-envelope drift before an extraction changes behavior. +2. Audit lifetime capture in every existing tool lambda. Record whether it + borrows a product, universe, factory session, renderer, resource owner, or + callback. A hook may not outlive any borrowed service. +3. Confirm every asynchronous capture and render-only path has one terminal + owner and a bounded release path during world retirement, renderer reset, + client shutdown, and hook removal. +4. Audit `Surface` copy and move behavior with the shared operation ledger. + Decide whether a runtime registry makes surfaces noncopyable or transfers + only after all activation guards drain. Do not retain a copied live registry. +5. Measure host-thread cost of schema generation, list construction, tool + dispatch, activation, and draining in a release build. Schema work must not + cause a visible frame or tick hitch. +6. Check whether currently reported `listChanged: false` remains correct after + runtime activation. If not, implement notifications as a separate protocol + feature with a real MCP client test. +7. Reconcile the historical broad contract with current capability names. Do + not implement proposals such as generic scene editing, multi-camera atomic + GPU claims, dynamic plugin loading, or new channels merely because they + appear in `MCP-ADDITIONS.md`. + +## Staged migration + +### Stage 0: inventory and compatibility baseline + +Generate checked JSON manifests for Studio normal, Studio factory, client +normal, client factory, server factory, server normal, and CDN. Each manifest +contains server info, feature or hook IDs, tools with input schemas, resources, +prompts, negotiated capabilities, limits, and unavailable reasons. Store only +reviewed source fixtures, never generated output under `.cache`. + +Build direct `Surface` transcript tests and subprocess tests through +`mcpbridge`. The baseline must cover initialization, notification suppression, +unknown calls, a valid tool, a refused tool, resource and prompt reads, and a +large forwarded message. Capture raw factory, lifecycle, and capture flows with +their explicit identity fields. + +Gate: all current tests pass and the manifests are accepted as the compatibility +contract. Any intentional difference requires a contract revision and migration +note before code moves. + +### Stage 1: add owned registration without changing products + +Introduce owner-tagged registration, activation guards, atomic registration +transactions, and a test-only hook. Keep the existing `Feature` API as an +adapter that installs one built-in activation at startup. No existing product +changes its feature list in this stage. + +Gate: duplicate ownership fails before publication; a failed activation leaves +the old lists unchanged; tool dispatch holds a guard; removal waits for a held +guard; repeated disable is safe; all baseline transcripts are identical. + +### Stage 2: move optional slices behind host-local hooks + +Extract rig export, visibility, temporal sample, audio observation, and other +families one at a time behind host-local providers. Each provider has a tiny +typed context and declared limits. Put schemas, parsing, and service adaptation +in separate translation units in the owning host. Do not create a shared module +until a separate architecture design names valid dependencies and layer. + +Gate per slice: schema snapshot equality, direct behavior tests, unavailable +host test, activate-call-disable test, shutdown during pending read test, +`server` configure, and `just check-server-is-headless`. + +### Stage 3: split data-factory lifecycle from its row adapter + +Keep `world::DataFactorySession` as the authoritative lifecycle service. +Extract only the MCP parsing, canonicalization, reply conversion, and +operation-ledger wrapper from `DataFactory.hpp`. The lifecycle hook owns its +rows, but never duplicates factory state or the ledger. + +Gate: all world creation, reset, pause, resume, step, snapshot, checkpoint, +restore, fork, seek, intervention, and retire tests retain their present +outcomes. Test same operation ID with equal and unequal canonical arguments +before and after hook reactivation. + +### Stage 4: extract scene and capture safely + +Move raw scene export and client rendering rows separately through their owning +host adapters. Keep camera rendering data and capture in client and Studio +product adapters. Move capture only after its ticket, resource, renderer reset, +and world-retirement ownership graph is written and tested. The capture provider +must report `draining` while it has tickets and must deny new submissions. It +registers through the shared registry, but `control` retains no renderer type. + +Gate: test pending, ready, cancelled, failed, and released tickets; provider +disable during each state; stale revisions; pipeline-generation reuse; capture +resource reads after terminal completion; and no external call on render thread. +Run `just data-capture-hook-bench` and a release capture profile before and +after this stage with the same scene, backend, resolution, and channels. Verify +the server and CDN target graphs remain free of the client capture adapter. + +### Stage 5: centralize host composition and retire compatibility wrappers + +Replace each product's scattered arrays and custom registration calls with one +manifest builder in `ControlHooks.cpp`. It supplies typed product services and +decides its default active hooks. Delete the legacy feature installers only +after every caller uses a hook provider. Keep no shadow registration path. + +Gate: product manifests match Stage 0 except approved changes; `dev`, `server`, +and `ci` builds pass; `just check-server-is-headless` and +`just check-cdn-is-bare` pass; launch and shutdown smoke coverage shows no +retained hook, ticket, socket, or resource. + +### Stage 6: decide whether a plugin ABI is justified + +Only start this stage after at least two independently developed compiled hooks +need runtime binary replacement. Define a narrow C ABI with version negotiation, +allocator ownership, no exceptions across the boundary, no raw host pointers, +and an explicit unload barrier. Load each binary from an allowlisted local path +with an observable manifest. A plugin that cannot drain never unloads. + +Gate: process-isolated ABI tests, incompatible-version refusal, malformed +manifest refusal, activation rollback, plugin crash containment strategy, and +repeated load-call-disable-unload soak. If these are not needed, retain the +compiled-hook design and do not add this stage. + +## Verification matrix + +| Risk | Required evidence | +| --- | --- | +| Wire compatibility | Golden JSON-RPC transcripts through `Surface` and `mcpbridge`; schema and capability manifests per host mode. | +| Wrong capability advertised | Active hook list and `tools/list` agree; disabled rows are absent; unavailable reason is explicit only where discovery requires it. | +| Name collision | Activation transaction rejects duplicate tool, resource, or prompt ownership with both hook IDs. | +| Use after free on removal | Deterministic held-guard test plus pending ticket, renderer reset, world retire, host shutdown, and repeated disable tests. | +| Duplicate mutation | Ledger tests prove equal canonical operation replay and unequal arguments refusal across restart or reactivation boundaries. | +| Stale world or render data | Fuzz or table tests for instance, tick, epoch, version, snapshot, pipeline revision, view slot, and ticket generation mismatches. | +| Resource leak | Bounded in-flight, cancellation, terminal release, TTL, and shutdown tests. Run a targeted heap soak for repeated capture activation and removal. | +| Render-thread violation | Instrumented assertion or test seam proves hooks only enqueue copied records and render threads never invoke external provider code. | +| Frame or tick hitch | Release benchmarks for list, activation, dispatch, capture submission, and drain. Record allocation counts and worst case duration. | +| Product layering drift | `just test-architecture`; both `dev` and `server` configure and build; `just check-server-is-headless`; `just check-cdn-is-bare`; and a graph assertion that shared `control` has no client-tier or `render` edge. | + +## Completion criteria + +v0.25 cleanup is complete when: + +1. The current advertised MCP contract is captured by reviewed manifests and + transcript tests for every supported host mode. +2. `Surface` has explicit, owner-tagged, transactional registration and safe + removal with no unowned callback path. +3. Data-factory, raw-scene, observation, camera rendering data, capture, and + render inspection functionality is represented by independently removable + host-local hooks, with no reverse dependency from shared control code into + `render`. +4. Every hook has a typed context, declared dependencies, limits, lifecycle + state, and a named owner for asynchronous work and retained resources. +5. Product composition has one local manifest per product, with no duplicate + registration lists or compatibility pathways. +6. Direct engine, stdio bridge, lifecycle, renderer capture, shutdown, memory, + performance, architecture, and headless verification gates pass. +7. `mono.engine/control/docs/MCP.md` describes the final active capabilities, + hook lifecycle, and client refresh behavior, while historical proposals are + clearly marked as proposals rather than shipped behavior. diff --git a/docs/v025-RENDER-PIPELINE-CLEANUP.md b/docs/v025-RENDER-PIPELINE-CLEANUP.md new file mode 100644 index 000000000..54c194311 --- /dev/null +++ b/docs/v025-RENDER-PIPELINE-CLEANUP.md @@ -0,0 +1,219 @@ +# v0.25 render pipeline cleanup plan + +## Purpose + +The render path has become capable enough that its main cost is now understanding where a decision belongs. +This plan makes graph meaning, render execution, GPU lifetime, world presentation, and Studio authoring explicit +ownership areas. It is a cleanup plan, not a proposal to replace the renderer or change the authored pipeline +format. + +The first rule is to preserve a working renderer after every move. Extract private implementation units inside +`mono.engine/render` before considering a new module. The current `render` dependency closure deliberately owns +the SDL device, shaders, resources, and presentation adapters. Splitting it into libraries before stable cut +points exist would add architecture edges without reducing the work needed to understand one frame. + +## Current map + +```mermaid +flowchart LR + Author[PipelineDocument\nauthored edits] --> Graph[Engine::graph\nvalidate, compile, schedule, alias] + Studio[Studio node editor\nload, save, inspect] <--> Author + Graph --> Install[render pipeline admission\ncapabilities and backend availability] + Install --> Runtime[Renderer batch runner\nviews, mutations, command buffers] + Runtime --> Passes[built-in and custom node dispatch] + Runtime --> Gpu[targets, resource images, meshes, shaders] + World[scene and ECS] --> Present[WorldPresentation\ndraw rows and damage] + Present --> Runtime + Runtime --> Profile[profile, previews, visibility] + Profile --> Studio +``` + +The ownership direction is sound: `mono.engine/graph` is device free and `mono.engine/render` consumes its +compiled result. The implementation does not consistently retain that boundary: + +| Area | Current source | Cleanup concern | +|---|---|---| +| Graph model and static planning | `mono.engine/graph/include/engine/graph/RenderGraph.hpp`, `src/RenderGraph.cpp`, `src/Schedule.cpp`, `src/ExecutionPlan.cpp` | The graph holds validation, scheduling, alias planning, and profile types, but renderer admission repeats part of this policy. | +| Node vocabulary | `mono.engine/graph/src/PipelineCatalogue.cpp` | Catalogue metadata is separate from the renderer's backend dispatch table in `mono.engine/render/src/RenderPipelines.cpp`. | +| Pipeline admission and execution setup | `mono.engine/render/src/RenderPipelines.cpp` | One 2,450 line file compiles, checks, partitions, installs, retains, and dispatches pipelines. | +| Frame orchestration | `mono.engine/render/src/Renderer.cpp`, `src/RendererState.hpp` | One 2,896 line file owns batch setup, grouping, hook mutation, targets, history, submission, and recovery. | +| World to draw rows | `mono.engine/render/src/WorldPresentation.cpp`, `src/ViewportFrames.cpp` | Incremental cache invalidation is tightly coupled to a positional revision array and duplicated component lists. | +| Pipeline authoring UI | `mono.studio/src/RenderPipeline.cpp`, `src/RenderPipelineGraph.cpp` | Editor load/save reconstructs the document separately from graph build and shows several inspector views from one stateful file. | +| Portal rendering | `src/PortalImageRuntime.cpp`, `src/PortalImageHost.cpp`, `src/PortalExchange.cpp`, `src/PortalCaptureTree*.cpp` | This is a distinct state machine spread across transport, ownership, preparation, composition, and renderer calls. | + +The line counts are a prioritisation signal only. `PortalImageRuntime.cpp` is about 3,900 lines, `Renderer.cpp` +about 2,896, `RenderPipelines.cpp` about 2,450, `WorldPresentation.cpp` about 1,997, and +`RenderPipeline.cpp` about 1,025. Moves need to follow cohesive state and tested behaviour, not file size alone. + +## Target ownership + +Keep public `Renderer` as the device-facing façade. Its private implementation should have these named owners: + +| Private area | Responsibility | Candidate files | +|---|---|---| +| `PipelineCompiler` | Convert an installed `RenderGraph` into one immutable execution package. Validate graph, schedule, backend support, capability requirements, command-buffer plan, aliases, entity nodes, and retained-node metadata in one result. | `src/PipelineCompiler.hpp/.cpp` extracted from `RenderPipelines.cpp` | +| `PipelineRegistry` | Install, replace, resolve, snapshot, revision, and retire named execution packages. | `src/PipelineRegistry.hpp/.cpp` | +| `FrameBatch` | Own one `Renderer::Render` batch from command acquisition through submit or abort. It owns view ordering, group state, hook mutations, lighting restoration, and history commit or discard. | `src/FrameBatch.hpp/.cpp` extracted from `Renderer.cpp` | +| `RenderNodeExecutor` | Map a node kind to executable backend work. The built-in table, custom node registration, and missing-kind reporting live together. | `src/RenderNodeExecutor.hpp/.cpp` | +| `GraphResourceCache` | Own graph resource images, history generations, alias-backed allocation, previews, and release. | Extract from `RenderTargets.cpp`, `ResourceImage.cpp`, and `RendererState.hpp` only after its lifecycle is specified. | +| `PresentationCollector` | Turn ECS and scene state into presentation rows, damage, and viewport frames. | Private files around `WorldPresentation.cpp` and `ViewportFrames.cpp` | +| `PortalRenderCoordinator` | Coordinate portal demand, topology, transport, image residency, and tree composition. It calls `Renderer` through a narrow private operation interface. | Private headers around existing `Portal*.cpp` files | + +These are folders and private headers, not new public modules. For example, `src/pipeline/`, `src/frame/`, +`src/presentation/`, and `src/portal/` improve locality without widening the engine graph. Do not move generic +GPU wrappers out of `render` until a second, real device consumer needs them. + +## Prioritised work + +### P0: establish contracts before moving code + +1. Define an immutable private `InstalledPipeline` result produced by one compiler entry point. It must contain + the `graph::RenderGraph`, `CompiledGraph`, `ExecutionSchedule`, `ResourceAliasPlan`, planned command buffers, + entity-node set, retained-node metadata, pipeline name, and revision. + + Extract the duplicated assembly now in `Renderer::InstallEngineDefault` and the named-pipeline installation + paths in `mono.engine/render/src/RenderPipelines.cpp`. `Renderer::RenderGraphSnapshot` in + `mono.engine/render/include/engine/render/Renderer.hpp` should be made from this package, rather than being a + second manually maintained projection. + +2. Make backend support a first-class compiler input. Today `CompileRenderPipeline` builds a local `NodeTable`, + adds custom kinds, then checks missing kinds. Keep `NodeCatalogue` in `Engine::graph` as authoring metadata and + inject a `RenderNodeExecutor` capability table from `render`. Do not add SDL or render dependencies to graph. + +3. Give pipeline admission one failure type that preserves the offender, stage, and reason. Existing callers + currently shuttle `core::Name` plus a string through multiple graph and renderer APIs. A value result makes + Studio, MCP, logs, and tests describe the same refusal. + +4. Characterise the current default PBR graph before extraction. Compare its document, compiled order, execution + waves, command-buffer plan, alias plan, retained nodes, and profile schema. This is the baseline for every P0 + move. + +### P1: separate planning from frame execution + +1. Extract `PipelineCompiler` and `PipelineRegistry` without changing the public `Renderer` API. Delete the old + helper paths after all install callers use the package. Avoid a base class or a generic pass framework. + +2. Extract `FrameBatch` from `Renderer::Render`. Give it explicit terminal outcomes: skipped before acquisition, + submitted, submitted after a recoverable view failure, and aborted. Move cleanup for `BatchActive`, command + ownership, pending graph history, visibility snapshots, mutation restoration, and lighting restoration into + that owner. + +3. Split `RenderPipelines.cpp` by ownership: compiler and registry first, then executor and built-in pass family + bindings. Keep pass algorithms in existing focused files such as `ScenePasses.cpp`, `InterfacePass.cpp`, + `RenderParticles.cpp`, and `RenderLod.cpp`. + +4. Rename vague internal terms when extracted. Prefer `InstalledPipeline`, `PipelineCompiler`, + `FrameBatch`, `FrameViewGroup`, `GraphResourceCache`, and `PortalRenderCoordinator`. Retire `Impl::NamedPipeline` + once the registry takes ownership. Do not rename public authored node kinds or pipeline document fields in this + cleanup. + +### P1: make presentation invalidation declarative + +1. Replace `WorldPresentation::SourceRevisions` and its matching enum in + `mono.engine/render/src/WorldPresentation.cpp` with named revision fields or a single declared table that owns + the component type, revision slot, and full versus pose damage class. The present v0.25 LOD change expands the + array from 14 to 15 and adds matching calls in several locations. It works, but future omissions compile. + +2. Put the drawable component collection and `scene::ApplyDrawRenderState` input list behind one private + `PresentationSource` function. `ViewportFrames.cpp` currently has another explicit component tuple. The goal is + one declaration that supplies both viewport copying and world presentation collection. + +3. Keep `WorldPresentation` as the boundary from ECS to copied draw data. Do not push GPU resource handles into + scene components or give graph code renderer residency responsibilities. + +4. Extract damage calculation, source-row collection, skin pose collection, and final row ordering into private + files only after tests pin each contract. The current 1,997-line implementation should become a coordinator, + not a collection of unrelated static helpers. + +### P2: remove duplicated document and editor projection rules + +1. In `mono.studio/src/RenderPipelineGraph.cpp`, isolate conversion between `graph::PipelineDocument` and + `nodegraph::Graph` in a small adapter with a round-trip contract. Keep nodegraph layout data as authoring edits, + and keep graph validity in `Engine::graph`. + +2. Split `mono.studio/src/RenderPipeline.cpp` into document session state, canvas actions, inspector, schedule + panel, profile panel, and resource preview bridge. `DrawRenderPipeline` should coordinate these pieces and not + also contain save policy and diagnostics formatting. + +3. Consolidate label, scope, resource lifetime, resolution, and parameter conversion helpers. The Studio adapter + should use `NodeCatalogue` names and metadata whenever possible. It must not create a second schema for a + render node. + +4. Keep `PipelineDocument` as the canonical persisted representation. Do not persist nodegraph runtime IDs, + compiled schedules, alias placements, previews, or process-local `core::Name::Id()` values. + +### P2: make portal coordination comprehensible + +1. Draw a state and ownership table before moving code. Separate endpoint validity, demand, source capture, + prepared body, shadow route, composition job, and resident image lifetime. Each item needs one owner and one + retirement operation. + +2. Group existing portal files by that state machine under `src/portal/`, preserving private includes and the + render module boundary. Move a state and its tests together in small changes. + +3. Narrow portal calls into `Renderer` to explicit operations for capture, composition, upload, polling, + cancellation, and release. The coordinator should not reach through general renderer state. + +4. Keep copied `world::PresentationAddress` traffic at this boundary. Do not introduce shared world or ECS + pointers into portal work. + +## Investigations required before behaviour changes + +These are review findings, not confirmed defects. Reproduce or disprove each one with a focused test and a trace +before changing logic. + +| Investigation | Evidence and risk | Required evidence | +|---|---|---| +| Scheduler producer choice follows authored node order | `mono.engine/graph/src/Schedule.cpp` chooses the last earlier writer while building reader dependencies. The result is valid only if author order is intentionally the write version contract, including writes in different execution waves. | A matrix of multi-writer, reader, disabled-node, history, and each scope combination. Assert schedule edges and rendered or mock execution output. | +| Graph compiler and renderer compiler can drift | `RenderGraph::Compile`, `CompileSchedule`, and renderer-local `CompileRenderPipeline` each partition or validate different aspects. A new node kind or capability rule can be accepted by the editor then refused only on install. | Table-driven parity tests that assert the same graph status, offender, and stage for graph-only and renderer admission cases. | +| Catalogue metadata and backend dispatch are separate registries | `PipelineCatalogue.cpp` registers node definitions, while `RenderPipelines.cpp` has backend availability logic. A registered node can be authorable but not executable, or executable support can omit user facing metadata. | Test every built-in catalogue kind against the executor and every executor kind against the catalogue, with explicit exemptions for private test kinds. | +| Pipeline document round trip can lose intent | Studio reconstructs authored nodes from a linear edit stream in `RenderPipelineGraph.cpp`; engine `Build` consumes the same stream in `PipelineDocument.cpp`. Group, comment, mute, preview, resource settings, binding order, and malformed partial edits need exact preservation rules. | Golden document round trips through load, graph edits, and save. Compare canonical edits and validate the rebuilt engine graph. | +| Frame early exits may leave batch-owned state asymmetric | `Renderer::Render` has several returns before and after command acquisition, then manages history, visibility, hooks, lighting, and command submission. This is a high-risk cleanup seam even if current code is correct. | Inject failure after each acquisition and each group transition. Assert one submit or explicit abort, cleared active state, correct history disposition, visibility invalidation, and restored lighting and mutations. | +| Presentation cache tracking is index coupled | The v0.25 diff adds `LODSettings` by changing an array count, enum, invalidation call, and state application. A future mismatch can silently stale draw rows. | Per-component mutation tests generated from the declaration table, including add, remove, change, first frame, and unchanged second frame. | +| LOD GPU layout and shader stay lockstep | v0.25 changes `GpuLodSelection` from 80 to 96 bytes and adds `MinimumDistances` consumed by `lod-select.comp`. C++ `static_assert` alone cannot check shader offsets or semantic results. | GPU fixture with override, inherited zeros, invalid override, non-uniform transform, and expected selected levels. Validate reflected offsets when the shader tooling exposes them. | +| Portal retirement paths are complete | `PortalImageHost.cpp` retires compositions based on route, preparation, endpoint, and capture state. Cancellation and release ordering is complex and crosses several portal files. | Model-based sequence tests for endpoint replacement, producer removal, timeout, cancellation during upload, repeated demand, and shutdown. Track each image and job for exactly one terminal release. | + +## Test plan and gates + +Keep focused tests beside their owners. The repository already has useful seams: + +| Contract | Existing starting suites | Add or strengthen | +|---|---|---| +| Graph validity, schedule, aliases, documents, diagnostics, profiles, layout | `mono.engine/graph/tests/RenderGraph.cpp`, `PipelineDocument.cpp`, `PipelineCatalogue.cpp`, `EngineGraph.cpp`, `PipelineDiagnostics.cpp`, `PipelineProfile.cpp`, `PipelineView.cpp` | Compiler result snapshots, catalogue-executor parity, multi-writer scheduling, document canonical round trips. | +| Renderer pipeline admission and graph history | `mono.engine/render/tests/GraphRunner.cpp`, `GraphHistory.cpp`, `CustomNodes.cpp`, `Capabilities.cpp`, `ResourceImage.cpp` | Install replacement, failed admission preservation, revision and snapshot consistency, alias and retained-resource retirement. | +| Frame cleanup and visible output | `HardRender.cpp`, `HardRenderGpu.cpp`, `RenderStageProbe.cpp`, `RenderImageComparison.cpp`, `VisibilityObservation.cpp` | Failure-injection state machine test and a small golden default PBR image fixture. Keep GPU checks opt-in and deterministic. | +| Presentation and viewports | `WorldPresentation.cpp`, `PresentationDamage.cpp`, `PresentationSchedule.cpp`, `ViewportFrames.cpp` | Declaration-table invalidation cases and copy parity between viewport and collector. | +| Portals | `PortalImageHost.cpp`, `PortalCaptureTree*.cpp`, `PortalExchange.cpp`, `PortalTopologyHost.cpp`, `PortalResidentImages.cpp` | State-transition ledger tests and full terminal-release sequences. | +| Studio | `mono.studio/tests/RenderPipelineGraph.cpp`, `NodeGraph.cpp`, `Presentation.cpp` | Document round-trip golden tests, inspector status rendering, schedule and profile display snapshots. | + +Every extraction change must pass its narrow suite first, then the normal repository gates in `docs/CODE_QUALITY.md`: + +1. `just format-check` +2. `cmake --preset dev` and `cmake --build .cache/build/dev -j` +3. `cmake --preset server` and `cmake --build .cache/build/server -j` +4. `ctest --output-on-failure` in both build directories +5. `just check-server-is-headless`, `just test-architecture`, and `just components-check` when components change +6. `cmake --preset ci` and `cmake --build .cache/build/ci -j` + +For rendering changes, run a headless GPU suite only at the final verification stage with user approval, as the +repository instructions require. Record the preset, backend, fixture, dimensions, and tolerance. Profile a +release build before claiming a runtime improvement; extraction alone is not a performance change. + +## Delivery order + +1. Land characterisation tests and the immutable pipeline package with no output change. +2. Extract compiler, registry, and executor. Delete old installation helpers in the same changes. +3. Extract `FrameBatch` behind identical `Renderer::Render` behaviour and failure-injection tests. +4. Replace positional presentation invalidation with the declared source table, then split collector helpers. +5. Separate the Studio adapter and panels with document round-trip tests. +6. Map portal state, then move one lifecycle owner at a time with terminal-release tests. +7. Reassess whether any private area has earned its own engine module. Add one only if it has a stable public API, + at least two consumers, and an allowed layer edge recorded in `mono.tools/architecture/expected_graph.json`. + +## Explicit non-goals + +- Do not rewrite the linear `PipelineDocument` format in v0.25. First prove canonical round trips and isolate its adapter. +- Do not replace the graph with a generic render-graph framework. +- Do not move SDL, shader compiler, or GPU types into public headers. +- Do not merge graph planning into renderer. The existing device-free `Engine::graph` layer is valuable and should become clearer. +- Do not mix this cleanup with new visual features, pipeline schema changes, or a portal protocol redesign. From 51322d34a8c0ea93f9439b3ec5db9c2003d02138 Mon Sep 17 00:00:00 2001 From: SPOOK_EXE <91944990+SPOOKEXE@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:41:34 +0930 Subject: [PATCH 009/564] roadmap-edit --- ROADMAP.md | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8b6ec80bb..05817913a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -64,22 +64,28 @@ The milestone headings below are development labels. Not in line with project ve - [_] add extensive client character tests - [_] add extensive client character CAMERA tests (zooming out and projecting camera through portal) -- [_] improve atomic-game-engine build file usage sizes. Takes over 100GB right now, needs to be reduced. Reduce hash for each mono repository to a reasonable size for each, cleanup old files, etc. Find what takes up all the space and try improve it. +- [x] improve atomic-game-engine build file usage sizes. Takes over 100GB right now, needs to be reduced. Reduce hash for each mono repository to a reasonable size for each, cleanup old files, etc. Find what takes up all the space and try improve it. + +- [x] Prune `PLAN-procedural-planets.md`, `PORTAL-HANDOFF.md`, `RENDER-POST-HOOK-REFACTOR.md`, `RENDER-REFACTOR-TASKS.md`, `RENDER-REFACTOR.md` and `TORNADOSIM.md`. +- [x] Prune old files in `docs/future-work/` as well. e.g. merge `FUTURE_COMPONENTS.md` components into relevent document files in `docs/future-work/`, then leave the remaining orphaned ones in `FUTURE_COMPONENTS.md`. + +- [x] review and plan a cleanup of the render pipeline. Write docs/v025-RENDER-PIPELINE-CLEANUP.md. This can be logic cleanup, better layout, components separation, merging, renaming, potential test points, areas to investigate logic (that seem wrong and need to be investigated), etc. +- [x] plan a consolidation and cleanup for the MCP-ADDITIONS.md systems. Super big, needs to ensure its properly implemented and looks good. Maybe even isolating code to a separate folder and then using hooks to ingest (and make those hooks hot loadable and unloadable so we can disable when we don't need to use them). Write docs/v025-MCP-CLEANUP.md. + +- [_] Do cleanup in `docs/v025-RENDER-PIPELINE-CLEANUP.md` +- [_] Do cleanup in `docs/v025-MCP-CLEANUP.md` -- [_] review over v0.24 and consolidate, improve, tweak, etc. -- [_] Prune `PLAN-procedural-planets.md`, `PORTAL-HANDOFF.md`, `RENDER-POST-HOOK-REFACTOR.md`, `RENDER-REFACTOR-TASKS.md`, `RENDER-REFACTOR.md` and `TORNADOSIM.md`. -- [_] Prune old files in `docs/future-work/` as well. e.g. merge `FUTURE_COMPONENTS.md` components into relevent document files in `docs/future-work/`, then leave the remaining orphaned ones in `FUTURE_COMPONENTS.md`. -- [_] review and cleanup render pipeline (plan first) -- [_] plan a consolidation for the MCP-ADDITIONS.md systems. Super big, needs to ensure its properly implemented and looks good. Maybe even isolating code to a separate folder and then using hooks to ingest (and make those hooks hot loadable and unloadable so we can disable when we don't need to use them). - [_] stress test all underlying engine systems (input, cdn, assets, parallel world, physics, hundreds of players + characters all moving around randomly, etc). for each, find at least 5 optimisations. + - [_] add typed, read-only physics observation hooks at declared fixed-tick boundaries. Use stable string discovery names, typed immutable per-hook contexts and bounded non-blocking records. Define whether each record observes pre-solve, completed-solver or post-integration state; retain exact tick, world, units and availability; and expose completed records to data-factory MCP without allowing a hook to mutate physics state. - [_] add typed, read-only replication observation hooks at declared exchange boundaries. Use stable string discovery names, typed immutable per-hook contexts and bounded non-blocking records. Preserve world, authority, client, baseline, tick and exchange-round identity; expose applied, rejected, repaired and dropped work without crossing a world boundary by pointer; and keep private payloads behind the existing permission boundary. - [_] optimise server startup time - [_] optimise and improve tests (particularly server and physics, can we add deterministic hooks so we can immediately wait for an update for a change instead of guessing with timestamps? test.solver, test.replication, etc) + +- [_] pack multi-channel supporting render data in other channels, depth = r channel - ambient occulusion = g - anti-alias = b, for example. - [_] more lighting capabilities; god rays, blue, depth of field, fog fields (not global fog, more like "fog across area of ground") - [_] create a weather system demo using all the lighting capabilities (clouds, atmosphere, rain particles, etc). - [_] remake the tornado simulation demo using the C++ repository as a base. Check the existing documentation, add missing engine features that we need (ask user questions about it first, you'll need to swap into plan mode), then implement once you get the OK. -- [_] pack multi-channel supporting render data in other channels, depth = r channel - ambient occulusion = g - anti-alias = b, for example. - [_] fix portals so they are seamless. really plan out how to make them seamless and how to handle "standing in the middle" so objects are visually there on both sides of the portal with no seam especially during movement (and how to make replication seamless too) From fdc003a94655bb81ed0f6dc02bb94b48a4ab2ec6 Mon Sep 17 00:00:00 2001 From: SPOOK_EXE <91944990+SPOOKEXE@users.noreply.github.com> Date: Tue, 22 Sep 2026 05:44:24 +0930 Subject: [PATCH 010/564] docs: streamline guides and expand runtime API reference --- CONTRIBUTING.md | 203 +- RUNNING.md | 4214 +-- SECURITY.md | 14 +- docs/CODE_ARCH.md | 18 +- docs/CODE_DOCUMENTING.md | 45 +- docs/CODE_FORMAT.md | 2 + docs/CODE_QUALITY.md | 12 +- docs/THIRD_PARTY_NOTICES.md | 5 +- docs/schema-data.toml | 26676 +++++++++++----- docs/schema.toml | 137 +- mono.client/include/client/Scene.hpp | 31 +- .../include/engine/assets/LocalStore.hpp | 75 +- mono.engine/core/include/engine/core/Xml.hpp | 86 +- .../engine/script/EcsInstanceMethods.hpp | 31 + .../include/engine/script/ScriptCall.hpp | 96 +- mono.engine/script/src/EcsInstanceMethods.cpp | 31 + mono.engine/scripthost/tests/ScriptCall.cpp | 17 +- mono.engine/scriptjs/src/JsEcs.cpp | 11 +- mono.engine/scriptluau/src/LuauEcs.cpp | 11 +- mono.tools/docgen/CMakeLists.txt | 3 +- mono.tools/docgen/RunDoxygen.cmake | 31 +- mono.tools/docgen/pages/Theme.css | 20 + mono.tools/schemadump/CMakeLists.txt | 9 +- mono.tools/schemadump/app/main.cpp | 485 +- .../sourcecheck/include/sourcecheck/Rules.hpp | 39 +- 25 files changed, 19731 insertions(+), 12571 deletions(-) create mode 100644 mono.engine/script/include/engine/script/EcsInstanceMethods.hpp create mode 100644 mono.engine/script/src/EcsInstanceMethods.cpp create mode 100644 mono.tools/docgen/pages/Theme.css diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 801672a07..e3c68e281 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,51 +1,23 @@ # Contributing -Thanks for looking. This engine is being built mostly by and for people coming -from the Roblox community, and the assumption throughout is that you know games -better than you know C++ build systems. +This guide covers the local prerequisites, contribution expectations, review gate, and responsible disclosure path for this repository. ---- +## Get started -## Get it building - -You need: - -| Tool | Version | Why | -|---|---|---| -| CMake | 3.24+ | the build | -| Ninja | any recent | the generator every preset uses | -| A C++20 compiler | GCC 13+, Clang 16+, MSVC 19.3+ | | -| `clang-format` | 18+ | `just format`; optional, but a pull request without it says so | -| `just` | optional | the entry point; raw CMake works too | -| Python 3 | 3.8+ | **`just setup` only** - see below | - -Nothing in the build or the test suite needs a scripting runtime: the test -runner is C++ and the architecture check is a CMake script. - -`just setup` is the exception, and only for shaderc. It pins glslang, -SPIRV-Tools and SPIRV-Headers in its own `DEPS` file rather than as submodules, -so `git submodule update --recursive` clones shaderc and leaves `third_party/` -empty. `utils/git-sync-deps` fills it, and that script is Python. You need it -once, on a fresh clone. - -You do **not** need `glslc` installed. It is built from `mono.vendor/shaderc`, -which is what makes the SPIR-V reproducible between machines. Configure with -`-DMONO_VENDORED_GLSLC=OFF` to use one from your PATH instead and skip building -glslang - faster first build, at the cost of whatever version you happen to -have. - -On Linux you will also want the usual X11/Wayland development packages - SDL -picks its backends at configure time and tells you what it found. +Install a recent CMake, Ninja, C++20 compiler, Python 3, and `just`. +`clang-format` is also required for the formatting check. On Linux, install the +SDL development packages required by the window system you use. ```sh git clone --recurse-submodules cd atomic-game-engine - -just setup # or: git submodule update --init --recursive --depth 1 +just setup just build just run --stats ``` +`just setup` initializes the pinned vendor dependencies and installs the +repository hook. All build output is disposable and lives under `.cache/`. Without `just`: ```sh @@ -54,151 +26,42 @@ cmake --build .cache/build/dev ./.cache/build/dev/client/client --stats ``` -Everything derived lands in `.cache/`. Deleting it costs you a rebuild and -nothing else. - ---- - -## Run the tests - -```sh -just test # only what your change could have affected -just test-all # everything -``` - -The first one is not a guess. Each suite's signature is a hash of its source, -every header that source includes, and the signatures of the suites it declares -a dependency on - so changing a header at the bottom of the stack re-runs -everything above it and nothing else. It prints what it skipped. - -`ctest` from a build directory also works and always runs everything. +[RUNNING.md](RUNNING.md) is the complete command index, including product, +test, benchmark, documentation, and integration commands. -Tests live with the thing they test - `mono.engine//tests/`, -`mono.client/tests/`, `mono.server/tests/`, `mono.tools/tests/`. There is no -central test directory. +## Make a change ---- +Read the root `AGENTS.md`, then every module `AGENTS.md` for folders you touch. +Keep the change focused, add or update the tests that prove its behavior, and +remove code that the change replaces. Public APIs need documentation in their +headers. -## Try it +Before opening a pull request, follow +[the code-quality checklist](docs/CODE_QUALITY.md). At minimum, run the checks +that cover the change and report any relevant check you could not run. A strict +local gate is: ```sh -just run --stats --graph +just preset=ci check ``` -- **F3** - frame rate, and the shape of the last twenty seconds. The minimum - is the interesting number. -- **F5** - the frame graph. **F6**/**F7** move between views: the flamegraph, - time by category, per-system cost, and the metrics counters. -- **Esc** - quit. - -`--uncapped` unpins the frame from your display, which is the only way the -numbers mean anything. `client --help` lists the rest. - -The server is headless and has no window at all: - -```sh -just host --ticks 300 --entities 20000 -``` - -`just check-server-is-headless` configures with no client, and fails if the -staged `server/` directory has grown a `shaders/` folder. That is the tier -split proved rather than asserted. - -[RUNNING.md](RUNNING.md) has the rest: every flag on every program, how to run -one suite directly, how to attach Tracy, and why `--uncapped` is not optional -when you care about the numbers. - ---- - -## Before you open a pull request - -**Work through [`docs/CODE_QUALITY.md`](docs/CODE_QUALITY.md) and [`docs/CODE_BAD_PRACTICES.md`](docs/CODE_BAD_PRACTICES.md).** That is the -completion checklist - the mechanical gate first, then the review questions, -then what the pull request itself has to say. - -It lives there rather than here on purpose. A checklist copied into two files -is two checklists, and within a few months nobody knows which one is current. - -Working with Claude Code, `/run-checklist` walks the whole thing and reports -what it could not verify rather than skipping it quietly. `/new-module` walks -through adding an engine module without missing one of the six things that have -to line up. Both live in [`.claude/`](.claude/README.md) and are checked in. - -Two things the checklist cannot check for you: - -**Keep it small.** A change a reviewer can hold in their head gets reviewed -properly; one that cannot gets approved instead. Several small pull requests -beat one large one, even when the large one is better work. - -**Say what you did not do.** A pull request that names its own gaps is easier -to trust than one that does not mention any. - ---- - -## On AI - -This project uses AI models heavily and says so on the front page. That is a -deliberate choice about pace, and it comes with one condition, which is not -negotiable: - -> **You are responsible for every line you submit.** You must be able to -> explain it, defend it in review, and maintain it. "The model wrote it" is not -> an answer to a review comment. - -Practically, that means: read what it produced before you send it. If you do -not understand a section, either understand it or take it out. A change nobody -can explain is a change nobody can fix, and this is a codebase intended to last. - -Use AI freely for the parts where it is genuinely good - boilerplate, -mechanical refactors, working out an unfamiliar API, writing the test you know -you should write. Be much more careful with it on architecture, on anything -touching the untrusted parsing boundaries, and on anything where "looks right" -and "is right" are hard to tell apart. - -Always test your code, always benchmark and profile your code, always check if you need to rename variables and always check if you need to split code from one file to multiple. - ---- - -## Reporting a bug - -Say what you did, what happened, and what you expected. A frame from `--stats` -or `--graph` is worth several paragraphs. Include your GPU backend - the F3 -panel prints it. - -For anything touching the sandbox, the game file reader or the network path, -see `SECURITY.md` before opening a public issue. - ---- - -## Completion Checklist - -**It lives in [`docs/CODE_QUALITY.md`](docs/CODE_QUALITY.md).** A checklist -copied into two files is two checklists, and within a few months nobody knows -which one is current - so this section is a pointer, not a copy. - -The short version, and where each part is answered in full: +Use concise pull-request descriptions: what changed, why, how it was verified, +and what remains unverified. Keep performance claims tied to the preset, +scenario, and measurement that produced them. -| Ask yourself | Section | -|---|---| -| Have you profiled the code? | [5 · Performance](docs/CODE_QUALITY.md#5--performance) | -| Have you tested the code? | [6 · Tests](docs/CODE_QUALITY.md#6--tests) | -| Are all code paths covered in tests? | [6 · Tests](docs/CODE_QUALITY.md#6--tests) | -| Can you improve the code further? | [8 · Craft](docs/CODE_QUALITY.md#8--craft) | -| Are variables and fields not named generic things? | [8 · Craft](docs/CODE_QUALITY.md#8--craft) | -| Are there dead code paths you must remove? | [8 · Craft](docs/CODE_QUALITY.md#8--craft) | -| Have you formatted your code correctly? | [1 · The mechanical gate](docs/CODE_QUALITY.md#1--the-mechanical-gate) | -| Any 'negative' C++ practices? | [8 · Craft](docs/CODE_QUALITY.md#8--craft) - named, one by one | -| Any 'negative' general practices? | [8 · Craft](docs/CODE_QUALITY.md#8--craft) - likewise | -| Avoid bad code practices | [`docs/CODE_BAD_PRACTICES.md`](docs/CODE_BAD_PRACTICES.md) +## AI-assisted changes -The full checklist also covers the layer stack, the untrusted parsing -boundaries, thread affinity, and what the pull request itself has to say. Those -are the ones a reviewer cannot check for you afterwards. +AI assistance is welcome. The contributor submitting a change remains +responsible for understanding, testing, explaining, and maintaining every line +in it. Treat architecture, untrusted input, and concurrency as review-heavy +areas, not generated boilerplate. -Working with Claude Code, `/run-checklist` walks all of it. +## Bugs and security ---- +For a normal bug, include the command or scene, the expected and actual result, +and relevant logs or captures. For vulnerabilities or hostile-input failures, +follow [SECURITY.md](SECURITY.md) and do not open a public issue. ## Licence -MPL-2.0. By contributing you agree your contribution is licensed under it. +Contributions are licensed under MPL-2.0. diff --git a/RUNNING.md b/RUNNING.md index e3d80e945..f8e1f6c90 100644 --- a/RUNNING.md +++ b/RUNNING.md @@ -1,4054 +1,198 @@ -# Running +# Build and run -Every way to build and run something in this repository, and what each one is -for. +This is the command index for this checkout: use `just` from the repository root, and use each program's `--help` for its runtime options. -For getting a first build working on a fresh machine, see -[CONTRIBUTING.md](CONTRIBUTING.md). This file assumes the clone configures. +`just` defaults to `preset=dev`. Override it before the recipe, for example +`just preset=release build` or `just preset=server test`. Build products live in +`.cache/build//`. Build and test outputs live under `.cache/`; +documentation generators can update checked-in reference files. ---- - -## The short version +## Start here ```sh -git clone --recurse-submodules -cd atomic-game-engine - -just setup # submodules, and shaderc's own DEPS -just build # everything, dev preset -just run --stats --graph # the client, both debug panels open -just edit # the editor, on a new game -just test # only the suites your change could have affected +just setup +just build +just run --stats ``` -Needs CMake 3.24+, Ninja and a C++20 compiler - nothing else. `glslc` is built -from the vendored shaderc, so it is not a prerequisite. Everything derived lands -in `.cache/`. - -A compiler cache is optional and strongly worth having: the build uses ccache -or sccache when one is on PATH, across every preset out of one shared cache. -The ccache default cap is 5 GB, which this tree outgrows - a full cache -silently evicts and the hit rate falls over. On a machine with room, raise it -once with `just ccache 20G` and check the reported lines to confirm the -pressure is gone (`Cleanups` stops climbing). - -On Windows the compiler has to be in the shell's environment rather than merely -installed on the machine, which is a requirement no other platform has and no -error message names. [On Windows](#on-windows) is what it looks like when it is -missing, and `scripts\build-windows.bat` is the build that arranges it itself. +For a specific product, use `just client`, `just server`, `just cdn`, +`just studio`, or `just launcher`. The executables are staged at: ---- - -# Building +| Program | Path | +|---|---| +| Client | `.cache/build//client/client` | +| Server | `.cache/build//server/server` | +| CDN | `.cache/build//cdn/cdn` | +| Studio | `.cache/build//studio/studio` | +| Launcher | `.cache/build//launcher/launcher` | ## Presets -```sh -cmake --preset dev # everything, tests, Tracy, unoptimised first-party code -cmake --preset release # optimised - the only preset that turns -O0 off -cmake --preset server # no client at all, and therefore no graphics stack -cmake --preset cdn # the content origin alone, on a machine with nothing installed -cmake --preset ci # dev, with warnings fatal -cmake --preset bench # release, plus the benchmark binaries -``` - -| Preset | Client | Server | CDN | Tests | First-party `-O` | -|---|---|---|---|---|---| -| `dev` | yes | yes | yes | yes | `-O0` | -| `release` | yes | yes | yes | no | optimised | -| `server` | **no** | yes | no | yes | `-O0` | -| `cdn` | **no** | **no** | yes | yes | `-O0` | -| `ci` | yes | yes | yes | yes | `-O0`, warnings fatal | - -`server` and `cdn` are the two presets that prove something rather than build -something. `server` proves the client tier is absent; `cdn` proves the content -origin needs no graphics stack at all - it configures where there is no Vulkan -SDK, no SDL and no shader compiler. - -## The `ci` preset, and the hook that runs it - -`ci` is `dev` with `MONO_WERROR=ON`, which makes every warning fatal. Nothing on -GitHub runs it and nothing on GitHub is going to - that is a decision, and -`docs/retired/DEFERRED.md` D00005 carries it. What runs it is your own push: - -```sh -just install-hooks # once per clone; `just setup` already does it -``` - -which points `core.hooksPath` at the checked-in `.githooks/`, and -`.githooks/pre-push` runs `just preset=ci check` before a push leaves the -machine. No branch push starts anything on GitHub - the one workflow there -builds release artefacts from tags - so the push is the last moment anything -verifies the tree, and the hook verifies all of it rather than only the -compile. - -**It exists because this preset went uncompilable three times while being -described as the standard.** At v0.4 - a `-Wmissing-field-initializers` in -`core::Arguments` and a `-Wdangling-reference` across `world`'s suites. Twice -more inside v0.15, the second a `-Wdangling-reference` in `cdn::OriginFromFlags` -iterating a `std::span` straight off a temporary `Flag`, live while a roadmap -line written hours earlier said the preset exited 0. Each was there for as long -as it took somebody to think of typing `preset=ci`. A check nobody runs stops -being read and then stops being true, which is the same thing this repository -already learnt from `just docs-check` at v0.2. - -**The hook runs the whole chain, not just the build.** It used to build and not -test, on the argument that the suites were `just check`'s job and a gate that -failed for somebody else's half-finished module would get skipped every time. -That argument assumed a remote build was still coming; with branch pushes -building nothing anywhere, a tree that compiles but fails its suites would -otherwise be caught by nobody. So the hook holds a push to the same -`just preset=ci check` a person runs by hand - format, build, tests, -architecture, source rules, shaders, bindings, typecheck, determinism, replay, -client smoke, orphans - and the escape for a shared tree with live warnings in -it is `git push --no-verify`, said out loud. - -| What | Cost, measured on this machine | +| Preset | Use | |---|---| -| `just preset=ci build`, nothing changed | ~1 s | -| `just preset=ci build`, a day of another preset's drift | ~1 min | -| `just preset=ci build`, from an empty `.cache/build/ci/` | ~3 min, once - 1,998 targets, vendors included | -| `just preset=ci check`, warm | ~3 min, and `test-all` is most of it - plus determinism, replay and client smoke | - -`ci` builds into `.cache/build/ci/`, a tree of its own, so the first push after -working in `dev` recompiles what changed since the last push rather than -nothing. That is part of the cost; the rest is the chain actually running. -Warm, the hook costs minutes, and it is expensive exactly when a lot has -changed, which is exactly when it should run. - -Skip one deliberately with `git push --no-verify`. There is no way to skip one -accidentally, and that asymmetry is the point. - -It compiles the working tree rather than the commits being pushed, so in a tree -several people or agents are editing at once, somebody else's live warning -refuses your push. That is the tree you are publishing, so it is the right -answer - but it is worth knowing before it happens. - -**Third-party code is optimised in every preset, and only first-party code is -not.** `AGENTS.md`'s argument for `-O0` - a profile should measure what this -engine does rather than what the optimiser rescued - is about this engine, and -SDL is not it. Measured on the editor: `SDL_SubmitGPUCommandBuffer` is where the -Vulkan backend turns a recorded command buffer into queue submissions, and the -`submit` span read **17 ms in a `dev` build against a p50 of 0.2 ms in -`release`** on one scene and one machine. That is not the renderer being slow; -it is somebody else's library at `-O0`, and it made every `dev` profile point at -the wrong thing. - -So `MONO_OPTIMISE_VENDOR` is on by default and `mono.vendor` builds at `-O2` -with its debug information kept. First-party targets append their own `-O0` -after it and the later flag wins, so `dev` still measures unoptimised engine -code. Pass `-DMONO_OPTIMISE_VENDOR=OFF` when the thing being debugged *is* a -vendored library. +| `dev` | Default development build. | +| `release` | Optimized shipping-cost build. | +| `profile` | Instrumented profiling build. | +| `server` | Headless server-only build. | +| `cdn` | Content-origin build. | +| `ci` | Strict CI build. | +| `bench` | Optimized benchmark build. | +| `bench-o0`, `bench-o1`, `bench-o2`, `bench-o3` | Benchmark compiler-optimization comparisons. | +| `dist-dev` | Development distribution build. | +| `windows-cross` | Windows cross-build. | -The first configure of a client preset builds glslang, SPIRV-Tools and shaderc, -so that the `glslc` compiling the engine's shaders is pinned rather than -whatever is on your PATH. It is the slowest part of a fresh build and it happens -once. `-DMONO_VENDORED_GLSLC=OFF` skips it and uses a system `glslc`. - -`just` works against `dev` unless told otherwise. **One override, written before -the recipe name, and it applies to every recipe:** +Configure or build a preset directly: ```sh +just preset=release configure just preset=release build -just preset=release run --stats --uncapped just preset=server test ``` -It is not a recipe argument. `build` is derived from `preset` when the Justfile -is read, and an argument cannot reach a derived variable - which is what made -the older `just test server` configure one preset and then run another's -binaries. The override is applied before anything is derived, so the configure, -the build and the directory the binary is run from cannot disagree. - -## Building all the monos - -```sh -just build # every target the preset configures -just preset=release build # the same, optimised -cmake --build --preset dev # without just -``` - -## On Windows - -```bat -scripts\build-windows.bat :: everything, dev preset -scripts\build-windows.bat client :: one target and its deps -scripts\build-windows.bat engine_ecs engine_world :: several -set PRESET=release (then run it) :: any other preset -``` - -The same configure and build as everywhere else, with the compiler environment -put in front of them. That is the whole of what the script adds, and it is not -optional: the presets generate Ninja, and Ninja has no per-command environment - -`build.ninja` is a flat list of literal command lines, so CMake cannot record -the toolchain's include and library paths in it. MSVC reads those from `INCLUDE` -and `LIB` in the environment instead, and a plain `cmd` or PowerShell window has -neither. - -Configuring still succeeds without them, so the first sign of it is every source -file in the repository failing at its first `#include` of anything at all: - -``` -fatal error C1083: Cannot open include file: 'cstddef': No such file or directory -``` - -which reads like the standard library is missing and is really the shell being -wrong. `vcvars64.bat` is what sets those variables, and a Developer Command -Prompt is nothing more than a `cmd` window that has already run it - so this -script runs it too, inside its own `setlocal`, and nothing it sets outlives the -build. Started from a Developer Command Prompt it finds the environment already -there and leaves it alone. - -`just build` has the same requirement, because the environment belongs to the -shell rather than to the tool driving CMake. The Visual Studio generator is the -one thing that does not, since MSBuild rebuilds the environment from the -`.vcxproj` - but it is not the generator the presets pin, and it is not the one -the build times here assume. - -Build once with this and the demo and studio scripts work from an ordinary -window too: they call CMake before running, and a build with nothing to do never -reaches the compiler. - -## Building one mono - -Every module is one CMake target, so building one is `just build `. -Its dependencies come with it; nothing above it does. - -```sh -just build engine_ecs # mono.engine/ecs and what it needs -just build client_lib # mono.client's library, not the program -just build test_render # one test binary -just preset=release build engine_ecs # any of the above, other preset -``` - -| Folder | Library target | Alias | Test binary | Tier | -|---|---|---|---|---| -| `mono.engine/core` | `engine_core` | `Engine::core` | `test_core` | shared | -| `mono.engine/parallel` | `engine_parallel` | `Engine::parallel` | `test_parallel` | shared | -| `mono.engine/ecs` | `engine_ecs` | `Engine::ecs` | `test_ecs` | shared | -| `mono.engine/world` | `engine_world` | `Engine::world` | `test_world` | shared | -| `mono.engine/spatial` | `engine_spatial` | `Engine::spatial` | `test_spatial` | shared | -| `mono.engine/scene` | `engine_scene` | `Engine::scene` | `test_scene` | shared | -| `mono.engine/gui` | `engine_gui` | `Engine::gui` | `test_gui` | shared | -| `mono.engine/assets` | `engine_assets` | `Engine::assets` | `test_assets` | shared | -| `mono.engine/physics` | `engine_physics` | `Engine::physics` | `test_physics` | shared | -| `mono.engine/effects` | `engine_effects` | `Engine::effects` | `test_effects` | shared | -| `mono.engine/script` | `engine_script` | `Engine::script` | `test_script` | shared | -| `mono.engine/bake` | `engine_bake` | `Engine::bake` | `test_bake` | shared | -| `mono.engine/graph` | `engine_graph` | `Engine::graph` | `test_graph` | shared | -| `mono.engine/game` | `engine_game` | `Engine::game` | `test_game` | shared | -| `mono.engine/examples` | `engine_examples` | `Engine::examples` | `test_examples` | shared | -| `mono.engine/net` | `engine_net` | `Engine::net` | `test_net` | shared | -| `mono.engine/delivery` | `engine_delivery` | `Engine::delivery` | `test_delivery` | shared | -| `mono.engine/replication` | `engine_replication` | `Engine::replication` | `test_replication` | shared | -| `mono.engine/control` | `engine_control` | `Engine::control` | - | shared | -| `mono.engine/audio` | `engine_audio` | `Engine::audio` | `test_audio` | client | -| `mono.engine/input` | `engine_input` | `Engine::input` | `test_input` | client | -| `mono.engine/render` | `engine_render` | `Engine::render` | `test_render` | client | -| `mono.engine/ui` | `engine_ui` | `Engine::ui` | `test_ui` | client | -| `mono.client` | `client_lib` | `Mono::client` | `test_client` | client | -| `mono.server` | `server_lib` | `Mono::server` | `test_server` | server | -| `mono.unified_tests` | `unified_tests_lib` | `Mono::unified_tests` | `test_unified_tests` | client | -| `mono.studio` | `studio_lib` | `Mono::studio` | `test_studio` | client | -| `mono.cdn` | `cdn_lib` | `Mono::cdn` | `test_cdn` | shared | -| `mono.tools/testrunner` | `testrunner_lib` | `Tool::testrunner` | `test_testrunner` | shared | -| `mono.tools/linecount` | `linecount_lib` | `Tool::linecount` | `test_linecount` | shared | -| `mono.tools/sourcecheck` | `sourcecheck_lib` | `Tool::sourcecheck` | `test_sourcecheck` | shared | - -The names are derived, not chosen per module: `mono_add_library` makes -`engine_` for an `Engine::` module and `_lib` for a product's own -library, and `mono_add_tests` makes `test_`. See -`mono.build/MonoLibrary.cmake`. - -The remaining tools are also built from `mono.tools/`: `bindings`, `docgen`, -`scriptcheck`, `mcpbridge`, `contentimport` and `assetc`. They are command-line -tools rather than engine modules; `testrunner`, `benchrunner` and `linecount` -are the other tool entry points. - -**`engine_input` and `engine_render` do not exist under the `server` preset.** -`mono.engine/CMakeLists.txt` only adds them when `MONO_BUILD_CLIENT` is on, so a -server configure never compiles SDL and never needs a shader compiler. That is -what makes "the server contains no graphics stack" a property of the build -rather than a claim about a link line - and it is why -`just preset=server build engine_render` fails with `unknown target` rather than -quietly building it. - -## Building one program - -```sh -just client # the client program and only its dependencies -just server # the server program and only its dependencies -just cdn # the content origin and only its dependencies -just build testrunner # the test runner -just preset=release client # optimised -``` - -`mono.engine` is libraries and never a product, so there is no target that -"builds the engine" on its own. Building a program builds the subset of modules -it links. - -## Where things land - -Each preset writes to `.cache/build//`: - -``` -.cache/build/dev/ -├─ client/ the client - binary, SDL3, shaders/resources/ -├─ server/ the server - no shaders, no SDL -├─ cdn/ the content origin - no shaders, no SDL -├─ tools/ testrunner -├─ tests/ every test binary -├─ lib/ static libraries, intermediate and never shipped -└─ shaderstage/ compiled SPIR-V, staged into each program that links it -``` - -A program's directory is runnable as it stands - see -[Running from somewhere else](#running-from-somewhere-else). Libraries are -intermediate and ship nowhere. - -## Cleaning - -```sh -just clean # .cache/build - every preset's build tree -just clean-all # .cache - including the smart-test cache -``` - -## Formatting - -```sh -just format # clang-format -i over every first-party .cpp and .hpp -just format-check # fails if anything is misformatted, changes nothing -``` - -Both skip `mono.vendor/` by construction: the directory list is explicit rather -than `find .`, because reformatting a submodule turns every future update into a -conflict. - -**`mono.studio/` is not in that list, and it should be.** It is a first-party -member that has never been swept, so its files are formatted by whoever last -edited them. Adding it is a one-line change and a fifty-eight file diff, which -is why it has not been folded into a feature commit - do it on its own. - ---- - -# What there is to run - -`mono.engine/` is libraries. No `main.cpp` lives under it and nothing ships from -it alone, so there is no single binary that "runs the engine" - there are thin -mains over the parts of it they need. - -| You want to | Run | Adds, over the engine | -|---|---|---| -| Pick one of the below without remembering its flags | `launcher` *(v0.18)* | a window, and nothing else | -| Run a script with nothing else in the way | `atomic` *(v0.6)* | nothing | -| Build a game | `studio` *(v0.7)* | the editor: explorer, properties, script editor, run and play | -| See something on screen | `client` | window, input, renderer, and the client half of networking | -| Host a simulation with no window | `server` | the tick loop, and the hosting half of networking | -| Serve a game's content | `cdn` | a content store, published and signed, served over HTTP | -| Exercise one module | its test binary | Catch2 | -| Re-run only what your change affected | `testrunner` | - | -| Check the architecture held | a CMake script | - | -| Put a server under two hundred real clients | `loadtest` *(v0.16)* | many genuine sessions in one process, and a flamegraph of the server | - -**The client and the server are shims, not the engine.** What they add is the -part that has to exist between two machines - name resolution, peer-to-peer, -hosting, the session - plus, on the client, presentation. A script that needs -none of that does not need either program, which is what the standalone runtime -is for. - -`client --help`, `server --help` and `studio --help` print their own options, -generated from the option declarations, so they cannot drift from what the -program accepts. - -**`--describe` prints the same table as JSON** *(v0.18)*, and every program in -the tree answers it because `core::Arguments` declares the flag itself. It -carries both settings surfaces - the options, and `core::Flags`' declared table - -and it is what the launcher builds its screens out of. - -```sh -./client --describe | jq '.options[] | select(.takesValue) | .name' -``` - ---- - -## The launcher *(v0.18)* - -```sh -just launch # the front screen -just launch --mode cdn # straight onto one mode -``` - -A window with one button per mode - Play, Join, Host, Studio, Serve content - -and, behind each, a form holding **every option and every setting that program -declared**. Nothing is filtered out; it is split across three tabs: - -| Tab | What is on it | -|---|---| -| Common | The four to seven options that decide what the run *is*, filled in | -| All options | Every option the program declared, grouped by name prefix | -| Engine settings | `core::Flags`' table, written as `--flag NAME=VALUE` | - -Both option tabs edit the same rows, so a value typed on one is the value on the -other. The search box above the tabs filters all three at once, and each group -header carries its hit count so a collapsed group still says how much is inside. - -An option whose value is a `PATH` or a `DIR` gets a browse button - a page for a -file, a folder for a folder, and the folder one picks **several at a time**: tick -three and confirm, and the option gets three rows. The ticks survive walking into -another parent, so the folders do not have to be siblings. `+` gives an option -another value by hand and `-` takes a row away. - -Ctrl+Enter launches, Escape goes back. - -It shows the command line it will run, in full, above the Launch button, with a -Copy next to it. That line is the same list it hands the child, so pasting it -into a terminal reproduces the run exactly. - -**It links none of the programs it starts.** It finds them staged beside it - -`/client/client` and so on - asks each one `--describe`, and spawns the -one you picked. So it needs them built: - -```sh -just build # everything, then every mode is available -just build cdn && just launch --mode cdn # or one program and its mode -``` - -A mode whose program is not staged is greyed out with the reason on the row, -which is the ordinary state under the `server` and `cdn` presets. Each row also -shows its program's version - two different versions in one tree means a -half-rebuilt tree, and that is worth seeing before the run rather than after. - -Host and Serve content keep the launcher up: it reports whether the child is -running, how long for, and how it ended, and offers Stop, Kill and Restart. Play, -Join and Studio hand the display over and the launcher minimises until the child -exits. - -The launcher has its own few options: - -```sh -./launcher --mode host --width 1400 --height 900 --scale 1.25 -./launcher --headless --frames 5 # for a smoke test; needs a frame budget -``` - -Forms live as long as the window. There are no saved profiles - `--config PATH` -is on every mode's form like any other option, and a settings file is the thing -that already does that job. - ---- - -# Settings *(v0.15)* - -Every program takes the same three, on top of its own options: - -```sh -./client --config atomic.cfg # a settings file -./client --flag client.width=1600 # one setting, above everything else -./client --flags # print every setting and where it came from, then exit - -ATOMIC_CONFIG=atomic.cfg ./server # the file, from the environment -ATOMIC_CLIENT_WIDTH=1600 ./client # one setting, from the environment -``` - -**What wins is decided by where a value came from, not by what ran first:** - - built-in default < config file < environment < command line - -so a config file cannot overwrite what somebody typed, whichever order the -program happens to read them in. `--flags` prints the source beside each value, -which is the answer to "why is this not what I set". - -## The file - -Sectioned `key = value`, where the section is the setting's prefix. `#` and `;` -start a comment, and a double quote keeps a value that contains one. - -```ini -# atomic.cfg -[engine] -log-level = trace -jobs.workers = 8 - -[server] -tick-rate = 30 -listen = true -listen-port = 9099 -idle-sleep = never - -[client] -# A setting that is genuinely several repeats its key, and order is kept. -content-sources = dir:/srv/atomic/processed -content-sources = 10.0.0.4:9080 - -[content] -gif = false # this process will not decode a GIF -svg = false # nor rasterise an SVG - -[cdn.publish] -mp4 = false # and an origin will not publish one -``` - -**A key naming no setting this program has is an error**, not a shrug - the same -position `--help` takes for an unknown option, and for the same reason: a typo -that is silently ignored fails at the behaviour rather than at the file. Run -`--flags` to see what a program actually has. - -**A file named with `--config` and missing is an error too**, where no file at -all is ordinary. A program launched with `--config prod.cfg` that silently ran -on defaults is the deployment failure this whole layer exists to prevent. - -**A repeated key appends and a source that outranks it replaces.** Three origins -in a file are three lines and all three are meant; one `--flag` on the command -line replaces all three, rather than being appended to a list the person running -it cannot see. A `--flag client.content-sources=` with nothing after it is how a -command line says "none". Nothing is split on a separator, so a path may contain -anything. - -## Where a client's content comes from *(v0.16)* - -A server gives its clients content one of two ways, and **which one is a field -rather than a shape**: `server.content-mode`, `relay` or `redirect`. There is no -second server program, no second settings type and no rebuild between them, for -the reason `cdn`'s three deployments are flag combinations rather than three -classes - moving between them has to stay a deployment decision. - -| Mode | What crosses | The client talks to a CDN | -|---|---|---| -| `relay` | content, over the game link the client already has | **no** | -| `redirect` | a list of origins, a grant and the publisher key | yes, to what it was told about | - -**`relay` is the default**, because it asks least of a player's network: one -port, already reached, already admitted. - -### The settings - -| Setting | Means | -|---|---| -| `server.content-mode` | `relay` or `redirect`. Anything else warns and uses `relay` | -| `server.content-sources` | An origin, as `dir:PATH` or `HOST:PORT`, optionally `NAME=` in front. **Repeatable, and the order is the priority** | -| `server.content-publisher-key` | 64 hex characters - the publisher whose signature content must carry | -| `server.content-store` | Unchanged. Also the fallback for `content-sources` when that names nothing | -| `server.content-grant-key` | Unchanged. What a `redirect` grant is signed with, and what the origin checks | -| `client.content-allowed-hosts` | A host a **server-named** origin may live on. Repeatable; empty allows any | - -`server.content-sources` is spelled exactly as `client.content-sources` is, -because it means the same thing. A server with a `content-store` and no -`content-sources` fetches from its own store, so the self-hosted case is one -flag rather than two saying the same thing. - -### Relay, in full - -```ini -# atomic.cfg - a server that holds the only origin connection -[server] -listen = true -listen-port = 9000 -content-mode = relay -content-store = /srv/atomic/processed -content-grant-key = 7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a -content-publisher-key = ba42458e83ba... -``` - -```sh -just host --config atomic.cfg -just run --connect 127.0.0.1:9000 --publisher-key ba42458e83ba... -``` - -The client asks the server for `/manifest`, `/dictionary` and `/bundle/` -over the game link and **verifies every byte against the publisher's signature** -exactly as it would off a socket - relaying moves the transport and not the trust -boundary. The server tells it the publisher key at admission, so a client that -was given none still has a root of trust. - -**The client has no authority in it, and the limits are the server's.** It may -ask and it may ask again; how often is `server::ContentRelay`'s to decide. A -client over its allowance has the request **dropped** and counted, and one that -keeps at it is flagged and refused outright for a cooldown - refused rather than -disconnected, so a client on a bad script stays distinguishable from one on a bad -network and can recover. `ContentRelayStatistics` counts asking-too-fast, -nothing-to-serve and the-link-was-full apart, because those are three incidents -with three different fixes. - -**Content never outranks the simulation.** A relayed piece is offered *after* the -world has been published, out of whatever is left of that tick's link budget, and -a piece the link would not take is offered again on the next tick from exactly -where it stopped. - -### Redirect, in full - -```ini -# atomic.cfg - a server that names the origins instead -[server] -listen = true -listen-port = 9000 -content-mode = redirect -content-sources = near=10.0.0.4:9080 -content-sources = far=203.0.113.9:9080 -content-store = /srv/atomic/processed -content-grant-key = 7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a -content-publisher-key = ba42458e83ba... - -[client] -# What this machine will let a server point it at. Empty allows any. -content-allowed-hosts = 10.0.0.4 -content-allowed-hosts = 203.0.113.9 -``` - -At admission the server sends the list, **a grant issued for that session**, and -the publisher key. The grant is what lets `cdn::Gate` admit the client's requests -without the origin knowing anything about sessions or players - so the origins -need the same `--grant-key` and nothing else about the game. - -**What the client does with the list is decided by where each value came from**, -which is this file's precedence rule applied one layer along: - -- **A source this client was configured with wins and is tried first.** The - server's list is *appended*, never substituted - the order of the list is the - policy, so "mine first, then whatever the host knows about" needs no flag. -- **The link itself goes last**, when there is one. It is the source that always - exists, so it is the one that answers when nothing before it did. -- **A publisher key pinned with `--publisher-key` is kept.** A server's is - adopted only when none was pinned, because a pinned client refuses rather than - downgrades. -- **A server-named origin is untrusted.** It passes `client.content-allowed-hosts` - before it is fetched from, and one naming a host *name* rather than an address - is skipped with **one** warning - `net::Endpoint::Parse` refuses a name on - purpose, because resolving one blocks and nothing on the fetch path may block. - -A server that names a hostile origin still cannot hand a client content that -verifies: the manifest's signature is checked against the publisher key, then a -group's length against that manifest, then every asset against its root. - -## Turning content formats off - -Two settings per format, and they are two because they are different verbs: - -| Setting | Means | -|---|---| -| `content.
` | this process will not decode, route or hand it over | -| `cdn.publish.` | this form does not enter a publication | - -`` is the extension - `gif`, `svg`, `mp4`, `png`, `glb`, `spv` - plus -`unknown`, which is every extension this build has no row for. Turning -`content.unknown` off closes the list to what the engine understands. - -```sh -./cdn --publish art/ --store cdn/ --signing-key HEX --flag cdn.publish.svg=false -./client --flag content.mp4=false -``` - -An origin refuses at **publish** time and nowhere else, and that is a fact about -an origin rather than an omission: after a publish there are only hashes, and a -hash cannot be walked back to a name. A refused file is never chunked, never -stored and never in the manifest - `cdn` says how many it refused, and `assetc` -keeps a row per source saying which form it was. - ---- - -# The editor *(v0.7)* - -```sh -just edit # a new game, one world, a baseplate -just edit --game My.agame # open one -``` - -The one program where `RunService:IsStudio()` is true. It writes a `.agame`, -which is the file the other two programs read: - -```sh -just host --game My.agame # a dedicated server hosting every world in it -just run --game My.agame # single-player, both roles in one process -``` - -### Editing a universe and a world - -Click a row in the Explorer and the Properties panel describes it. There are -three kinds of row and all three answer: - -- **the universe row** at the top: name, execution mode, maximum catch-up ticks, - bus budget per tick, channel queue limit and channels per world, with the - federated flag, world counts, fault counts, tick cost and bus traffic - read-only; -- **a world row**: `TickRate`, `IdleTickRate`, `PhysicsTickRate`, - `ReplicationTickRate`, the simulated network latency and the fault limit, with - the world's state, isolation, rendering profile and per-world statistics - read-only. A world's *name* is changed with Rename Scene in the row's own - context menu, because the universe's registry is keyed on it; -- **an instance row**: its class's properties, as before. - -**`PhysicsTickRate` is the one to reach for on a world that cannot keep up.** -Zero follows the tick rate; anything lower runs the solver every few ticks while -scripts, signals and rendering keep the tick rate. A climbing `Dropped Ticks` in -the same panel is what says a world needs it. - -### Options - -| Option | Default | What it does | -|---|---|---| -| `--verbose` | off | log at trace level | -| `--force-serial-compute` | off | run parallel dispatches on one thread | -| `--game PATH` | - | open a game file at startup | -| `--rojo PATH` | `$ATOMIC_ROJO_PROJECT` | sync a Rojo project or universe once the scene exists | -| `--config-root DIR` | user config folder | keep this run's preferences, keybinds and layout in `DIR` | -| `--width`, `--height` | 1600×900 | window size | -| `--scale FACTOR` | 1.0 | multiplies every font and padding | -| `--tick-rate HZ` | 60 | simulation rate while running | -| `--frames N` | - | exit after N frames, for a script or a screenshot | -| `--capture PATH` | - | write the viewport's world to a BMP and carry on | -| `--headless` | off | run with no window at all; needs `--frames` | -| `--run MODE` | `edit` | start in `edit`, `server` or `play` | -| `--uncapped` | off | draw with no frame rate ceiling | -| `--frames-in-flight N` | 2 | frames the CPU may queue ahead of the GPU, 1 to 3 | -| `--stats`, `--graph` | off | open the statistics or frame-graph panel | -| `--assets` | off | open the assets manager | -| `--viewports N` | 1 | open N viewport panels; `--viewport2` is the old spelling of `--viewports 2` | -| `--profile-snapshot PATH` | - | write a frame-graph snapshot on exit | -| `--idle-close SECONDS` | 300 | close an empty world after this long | -| `--mcp-port PORT` | off | open the loopback control surface | -| `--override-assets-directory DIR` | - | read staged data from here | - -**`--rojo` is how an external project is checked without driving the menu.** -Syncing is otherwise a file prompt and two clicks, which makes "does this -repository still sync" something nobody verifies. With no flag the editor reads -`ATOMIC_ROJO_PROJECT`, so a shell that works on one game can carry it - the flag -is for one run and the variable is for a day, and nothing writes the variable -back. A path ending `.universe.json` syncs every world it names; anything else -is read as one project into the scene that is open. - -```sh -ATOMIC_ROJO_PROJECT=~/Documents/GitHub/raceapet/default.project.json \ - ./.cache/build/dev/studio/studio --headless --frames 3 -# synced 1356 instances, 1082 scripts from RaceAPet -``` - -The count is the check. It should equal the number of `.luau`, `.lua` and -`.json` files the project's `$path`s actually reach - a package whose -`default.project.json` maps `lib` contributes `lib`, and nothing else it was -published with. - -**`submit` is where the GPU is paid for.** The passes above it only *record* -commands; `SDL_SubmitGPUCommandBuffer` is where the driver gets the work. Studio -defaults to two frames in flight so the CPU can record the next frame while the -GPU finishes the previous one. Setting `--frames-in-flight 1` makes submit block -for the previous frame and removes the extra frame of input latency. Measured on -the four-world demo: p99 6.9 ms at one, 6.1 ms at two, and the same 0.21 ms -median either way. - -**The editor is not paced by the display.** It starts with vertical sync off and -a 120 fps ceiling, because sync puts a whole refresh - 16.7 ms on a 60 Hz panel, -before the compositor takes its turn - between the mouse and the viewport, and -that delay is what dragging something feels like. The ceiling is what stops the -other extreme: a still scene redrawn nine hundred times a second is a laptop -with its fans up for one picture. - -Both are on the Preferences page under **Frames**, live, so a viewport that tears -is one click from paced and the ceiling is a slider. `--uncapped` removes the -ceiling for a run, which is what to pass when the number being read is the -frame's own cost - otherwise the sleep padding each frame out to 8.3 ms is -measured as that cost. On a device with no immediate present mode the editor says -so and stays paced by the display. - -### The Demo tab *(v0.14)* - -The ribbon's last tab, and its one entry is **Demo Nodes** - a typed node graph -with live evaluation. It changes nothing in the scene; it is there to be looked -at, and to be the place the two node systems `ROADMAP.md` wants get designed -against rather than invented twice. - -``` -drag port → port connect. Types must match, or it says why it refused -drag a wired input picks the link up and moves it -drag port → empty a palette of what would fit there -right click the palette anywhere -middle or alt-drag pan · wheel zooms to the cursor -Del · F delete the selection · fit -``` - -What it computes is terrain. **Noise, Ridged, Domain Warp, Terrace, Slope, -Threshold and Combine** are the sync half - they run inside the frame, so a -slider drag re-runs the chain between frames. **Colourise** turns a height field -into an actual picture, which is what the thumbnails on the nodes are drawing. - -**Erode** and **Staged Task** are the async half. Erosion is genuinely slow at -256², so it runs on a worker and the node grows a progress bar and the stage it -is on; the frame keeps drawing. Two staged tasks in two branches run at once -because the evaluator starts every node whose inputs are ready - there is no -scheduler deciding it, readiness *is* the schedule. - -Three properties worth knowing while using it: - -- **A result is cached against a hash** of the node's parameters and its inputs' - hashes, so one slider recomputes exactly the sub-tree below it. Dragging a - node recomputes nothing: position is not in the hash. -- **A node whose input is still being computed waits** rather than running with - the unconnected fallback, which would cache a picture of nothing under a hash - that claims otherwise. -- **Live** follows every edit; turn it off and drive it with **Build** when the - graph has a six-second task in it. - -The inspector down the right-hand side shows the selected node's picture large - -the same texture the node draws, so it costs one conversion - with its stages and -whatever number it produced. - -### Driving it with no display - -```sh -just studio-smoke # loads, plays, renders, writes a capture -just edit --headless --frames 12 --run play --capture shot.bmp -``` - -For window, swapchain, docking and mouse tests without touching the live -desktop or Studio configuration, run the whole editor on a private X display: - -```sh -scripts/run-studio-virtual.sh --frames 120 --run play -``` - -**`--headless` is a renderer with no window rather than a hidden one.** There is -no swapchain, nothing is presented, and the overlay and editor chrome do not -draw - but the game loads, the panels lay themselves out, `--run play` starts the -scripts, the worlds tick and the world is drawn into an offscreen target that -`--capture` writes out. A hidden window would still own a swapchain, and whether -one can be acquired for a window nobody can see is a per-platform answer nobody -should have to know. - -That is what makes the editor checkable by a build server, by a golden-image -comparison, or by something driving it that is not a person - none of which -should depend on a display being free. - -`--capture` works with a window too, and captures the world rather than the -whole editor: the chrome is drawn onto the swapchain, and SDL does not promise -that is readable. What it answers is "did the scene render", which is the -question a renderer is asked. - -### The file it writes - -A `.agame` is one XML document holding the universe, every world, every -instance and every script's text. It is meant to be read: - -```xml - - - - - - - - 128, 1, 128 - - - -``` - -Only properties that differ from their class default are written, which is what -keeps a scene of a thousand parts a file you can read a diff of. A single world -exports on its own as a `.aworld` - File ▸ Export Active World - and imports -back into any universe. - -**It is not a snapshot and does not replace one.** `--record` still writes the -binary format, which carries a *running* universe including tick counters and -bus state and is same-build only. A game file is content: it survives an engine -version, and that is what it is for. - ---- - -# Running a script file *(v0.6)* - -The client and server can load a scene script, and the unified harness can load -one for its authority. A game is a script, not a compiled artefact; the studio -opens an authored game file: - -```sh -just run --script .cache/build/dev/assets/examples/scripts/Rings.luau -server --game My.agame --tick-rate 60 -``` - -The client and server use explicit options because neither program treats a -bare positional path as a script: - -```sh -just run --script path/to/game.luau -server --game path/to/game.agame -``` - -`.ts` is TypeScript/JavaScript and `.luau` is Luau; which one a file is comes -from its extension, and a game may mix them. TypeScript is transpiled to staged -JavaScript during the build when the pinned compiler is available, with a -`.js.map` beside each one - **so a script that throws names the line in the -`.ts` you wrote** rather than a line in the generated file. Stripping types -shifts everything below a multi-line annotation upward, so the two rarely agree. -`mono.engine/examples/assets/scripts/` holds the script demos, each written twice - once in each -language, doing the same thing - so that the binding surface is exercised from -both. - -### Opening an example in the studio - -Every staged `.luau` scene is offered by the studio in three places, all of which -already offer New World: - -- the **World** menu, as `New Scene from Example`; -- the universe's right-click menu at the top of the **Explorer**; -- the **Example...** button in the **Worlds** panel, beside New and Import. - -Picking one adds a world named after the file and puts the scene in it as a -`Script` in `ServerScriptService`, so nothing is built until Play runs it and -Stop takes it away again. The list walks the staged directory rather than a -hand-kept table, so a scene added to `mono.engine/examples/assets/scripts/` is there after a -build. - -It is refused while anything is running, for the reason New World is: the -snapshot Stop restores was taken before the run began, so a world added during -Play would vanish on Stop. - -### The stress scenes *(v0.17)* - -Three scenes exist to be measured rather than looked at. All three name their -knobs at the top of the file and say what each one costs. - -| scene | what it loads | run it with | -| --- | --- | --- | -| `StressParticles.luau` | fourteen bays covering every authored `ParticleEmitter` property, then 1,024 parts carrying five emitters each - 512,000 particles | `just run --script .../StressParticles.luau --stats` | -| `StressPhysics.luau` | 100,000 unanchored blocks in a tray that tilts, so nothing ever settles | `server --game .../StressPhysics.luau --physics-tick-rate 20` | -| `StressMirrors.luau` | an ico-sphere mirror ball - 80 facets, 16 of them mirrors | `just run --script .../StressMirrors.luau` | - -Two things are worth knowing before running them rather than afterwards. - -**A client does not simulate `StressPhysics.luau`.** A client installs the -character systems and not the physics pipeline, so a scripted client world -integrates nothing: the blocks hang in the air. The studio's Play and -`server --game` are the two hosts that install it, and -`--physics-tick-rate` - or the world's `PhysicsTickRate` in the studio - is what -makes a hundred thousand bodies affordable, by solving slower than the world -ticks. Measured on `release`, 24 threads, headless at 30 Hz over 600 ticks: the -tick rate costs a 361 ms mean tick, and `--physics-tick-rate 10` costs 125 ms. -The scene's own header carries the percentiles, and the short version is that a -hundred thousand contacting bodies is past interactive either way. - -**`StressMirrors.luau` states its own bounce depth**, and the line is a guard -rather than a preference: a ball is the worst shape the automatic depth rule has, -because every pane can see most of the others and it therefore asks for one level -deeper every frame. The passes go as `panes x (panes - 1) ^ (levels - 1)`, so -sixteen panes cost 16 at one level and 3,600 at three. Compare depths with -`--surface-bounces N`, which overrides the scene. - -`dev` is `-O0` and no frame-rate number from it means anything. Build `release` -before quoting one. - -### Shared Luau libraries - -`mono.engine/examples/assets/scripts/libraries/` holds Luau *libraries* rather than scenes. Every -directory under it is staged with its structure intact and mirrored into -`ReplicatedStorage` as a tree of `ModuleScript` instances before any scene runs, -so a script finds `ReplicatedStorage.MagicCore` the way it would in a Rojo place. -`script::MountModuleTree` does the mirroring and follows Rojo's rule that -`init.luau` collapses into its own directory. - -| library | what it is | -| --- | --- | -| `MagicCore` | pure-data spells: config, compile, projectile, effect, status, presets | -| `MagicRuntime` | the part of a compiled spell this engine can draw | -| `TerrainCore` | pure-data voxel terrain: noise, height field, edits, meshing | -| `TerrainRuntime` | terrain boxes as Parts | -| `MagicTests` | `MagicCore` and `TerrainCore`'s own 183-test suite | - -`MagicCore` and `TerrainCore` came from an external Rojo project and are byte -identical to it, which is the point: they are checked by running that project's -own tests here. `MagicRuntime` and `TerrainRuntime` are this engine's, because -that is the only layer that names an instance. - -```sh -just run --script .cache/build/dev/assets/examples/scripts/Magic.luau # spells cratering terrain -just run --script .cache/build/dev/assets/examples/scripts/Libraries.luau # libraries, loaded and exercised -just run --script .cache/build/dev/assets/examples/scripts/MagicTests.luau # their tests, in this VM -``` - -**`MagicRuntime` draws everything the Roblox original draws.** A -`ParticleEmitter` per authored emitter - 42 across the five demo lanes, which -`Magic.luau` prints at startup - plus a `Trail` behind each projectile, a muzzle -`Beam` and a `PointLight`. - -It drew only a body until v0.18. The module was written when this engine had -`Part` and none of the rest, said so at the top of itself, and went on saying it -after `mono.engine/effects` landed - so the spells solved correctly, cratered -the terrain, and looked like coloured cubes. Two things had to change: the -module, and `examples::LoadScene`, which registered the 3D and 2D class trees -and not the effects one. See `lib/MagicRuntime/init.luau` for how a -`Timeline.EmitParticles` burst is spelled without a `ParticleEmitter:Emit`. - -### Autocomplete while you write one - -Both languages are typed against files generated from the class table, so an -editor knows what a script may name without anything being restated by hand: - -| file | what it is | checked in | -| --- | --- | --- | -| `mono.engine/script/bindings/engine.d.luau` | the Luau definitions | yes, generated | -| `mono.engine/script/bindings/engine.d.ts` | the TypeScript type root | yes, generated | -| `.luaurc` | strict by default, and the lints | yes | -| `luau-lsp.json` | points the language server at the definitions | yes | -| `tsconfig.json` | lists the type root; `types: []`, no DOM | yes | -| `package.json` | pins the exact `tsc` the check runs | yes | -| `.vscode/settings.json` | the same luau-lsp keys, for VS Code | **no** - `.vscode/` is gitignored | - -**Nothing needs installing.** The language server is vendored at -`mono.vendor/luau-lsp` and built on demand: - -```sh -just luau-lsp # clones the submodule if needed, prints the binary's path -``` - -That recipe also applies `mono.vendor/patches/luau-lsp/*.patch`, and **stops -rather than building without one**. The patch lands on a copy of the submodule -under `.cache/vendor/luau-lsp`, never on `mono.vendor/luau-lsp` itself - which is -why building a language server does not leave a modified submodule in every -`git status` afterwards. There is one today: it -registers the `Enum` prefix so `local face: Enum.NormalId` resolves the way it -already does in `just typecheck`, and the file's own preamble says why it is a -patch here rather than a fork. If it ever fails to apply, upstream moved the code -it edits - the message names the file to read. - -Point your editor at that binary and at `luau-lsp.json`. `.vscode/` is -gitignored - editor configuration is personal here - so `luau-lsp.json` is the -copy that survives a fresh clone, and a VS Code `settings.json` should mirror it -rather than diverge from it. - -**One of its settings is load-bearing rather than a preference.** -`luau-lsp.fflags.enableNewSolver` must be on: the declarations use the `keyof` -and `index` type functions, which exist only in Luau's new solver, and without -it the definitions file fails to load *entirely* - every global reads as -unknown, which looks like the file is missing rather than misconfigured. - -TypeScript needs no separate setup: `tsconfig.json` lists the type root and -`package.json` pins the compiler, which `just typecheck` installs on first run. - -Both languages are checked together by `just typecheck`, which `just check` -runs - see [The script type check](#the-script-type-check) for what it catches -that `just bindings-check` does not. The declarations themselves are regenerated -by `just bindings`. **A change to either is a change to what every script can -name**, so the diff is the review. - -They do not describe the same surface everywhere, and that is deliberate: the -two VMs differ. `game:GetService("Workspace")` and `RunService:IsServer()` are -Luau's, and each file says what its own VM installs rather than what the other -one has. - -### Autocomplete in the studio's own editor - -The above is for the editor you already use. The Script Editor in the studio has -its own, and it needs no language server and no configuration: - -| key | what it does | -| --- | --- | -| `Ctrl+Space` | offer a list, whatever is under the caret | -| `.` or `:`, or two characters | offer one automatically | -| `Up` / `Down` | move through it | -| `Enter`, `Tab`, or a click | accept | -| `Escape` | dismiss | -| `Tab` with the list closed | indents, as always | - -It offers classes inside an `Instance.new` call, properties after a dot, methods -and signals after a colon, enum sets and their members, the globals of whichever -language the script's `CodeSourceContainerSelector` selected, that language's -keywords, the identifiers already in the file, and **the names of the instances -beside the script in the tree** - which is the one thing luau-lsp cannot know, -because it reads files and not a world. - -**None of that list is written down anywhere.** Classes, properties and enums -come from `ecs::Classes` and `ecs::EnumTable`; the globals and instance methods -come from `script::Runtime::Surface`, which walks the global table of a VM built -for the purpose. A global added anywhere in `mono.engine/script` is offered with -nothing else changing, and one removed stops being offered in the same commit. -The reason it is built that way rather than from a list is in -`script/Vocabulary.hpp`, and it is two bugs this engine has already shipped. - -It does **not** infer types. A local from `Instance.new("Part")` resolves, -because the class is written on the line; one from `FindFirstChild` gets the -union of every scriptable property instead - a longer list, never a wrong one. -`D00114` carries what narrowing it would take and why the obvious answer only -helps one of the two languages. - -The list shows the typed prefix highlighted in each row and, under it, what -kind of thing the chosen row is - for a keyword, its one-line doc. - -**Resting the mouse on a word** shows the same information as a tooltip: a -keyword's doc line, what a global is, an enum set, a class and its parent, a -sibling instance, a narrowed local's class, or a property's type and declaring -class. It stays quiet over strings, comments, numbers, empty space and -anything the editor does not know, and it never appears while the completion -list is up. - -**The minimap** on the code field's right is a shrunken impression of the -whole file - bright stripes for identifiers, dim for punctuation, since the -field itself does no syntax tinting - with the visible region marked. Click or -drag it to scroll. - -### What happens today - -The Luau runtime, QuickJS runtime, bindings and game-file reader are active. -`--script` loads a scene script, and `--game` loads an authored `.agame` file. -The file extension selects Luau or JavaScript for script files; TypeScript -sources are transpiled to staged `.js` files when the pinned TypeScript compiler -is available. `atomic` is still not a target or a recipe. - -The example sources are real scenes, not placeholders. The default client scene -is `Rings.luau`; staged script demos live under -`.cache/build//assets/examples/scripts/` and authored worlds under -`.cache/build//assets/examples/worlds/` after a build. A missing TypeScript -compiler skips JavaScript twins and leaves Luau scenes available. - ---- - -# The client - -```sh -just run # dev preset, no panels -just run --stats --graph # both debug panels open -just demo # the same, spelled shorter -scripts/demos/run-demo.sh # the same again, without just -./.cache/build/dev/client/client # directly, no just and no build -``` - -`just run` passes everything after it straight through, and builds the client -first. - -### One script per scene - -`scripts/demos/` holds a `run-.sh` and a `run-.bat` for every -example, so seeing one is a command rather than a path to look up: - -| Script | Scene | -|---|---| -| `run-demo` | the default scripted scene - `examples/scripts/Rings.luau` | -| `run-rings` | orbiting, spinning parts - the loading path | -| `run-skygrid` | a lattice of blocks in empty sky | -| `run-terrain` | 16384² voxel terrain, streamed around a camera | -| `run-magic` | spells fired at terrain they dig holes in | -| `run-magic-tests` | the ported libraries' 183 tests, run here | -| `run-libraries` | `MagicCore` and `TerrainCore`, loaded and exercised | -| `run-interface` | a `ScreenGui` built entirely from a script | -| `run-mirrors` | one room of mirrors, each with a different effect - the rendering path | -| `run-mirrors-4-worlds` | four worlds composited into one frame | -| `run-portals` | a square building with three rooms in it, and a lap that closes early | -| `run-non-euclidean` | six exhibits, each a room that lies about its own size | -| `run-meshes` | imported meshes and textures. Wants `--cdn` | -| `run-mesh-grid` | bakes and publishes art, then draws it | -| `run-local-server` | one server and several clients, all on this machine | -| `run-local-server` + `SCENE=PlayerList.luau` | the same, with a live player list in every client | - -### Somebody to be *(v0.14)* - -```sh -scripts/demos/run-local-server.sh # a server and two clients -scripts/demos/run-local-server.sh 4 # four clients instead -PORT=9100 scripts/demos/run-local-server.sh # a different port -SCENE=Slide.luau scripts/demos/run-local-server.sh -``` - -**A server hosting `Playground.luau`, and a client window per player.** Each one -is admitted, given a blocky character on the spawn pad and told which player it -is; WASD walks it, Space jumps, the right mouse button turns the camera. Every -client sees every other character move, because the movement happens once - on -the server - and what crosses is the intent going up and the transform coming -down. - -**This is not `mono.unified_tests`, and the difference is the reason to -run it.** That harness cuts `net` out of the middle to prove the -serialise/deserialise seam; this puts the socket, the handshake, the cipher and -the bandwidth budget back, and adds the thing neither of them had - more than -one player. `--net` is on by default in the script because the F4 panel is where -this demo is read from: two characters that do not move have three explanations, -and the panel separates them. - -### Who is in the game *(v0.15)* - -```sh -SCENE=PlayerList.luau scripts/demos/run-local-server.sh 4 -``` - -**The same four clients, and a panel in each naming all four.** A name appears -when a client starts and vanishes when one is closed, and each client's own row -is tinted - with everybody called `Player1` through `Player4` there is otherwise -nothing on screen saying which of them you are. - -**The rows are written into each player's own `PlayerGui` and not into -`StarterGui`.** A `StarterGui` is a template that is cloned when a character -spawns, so a row added after somebody joined never reaches the copy they are -looking at; a `PlayerGui` is live *and* private on the wire, and it is the only -place both are true. Watching one client's panel while another closes is the -demonstration. - -**TAB holds the panel open where there is a keyboard, and there is not one on a -dedicated server** - so in this arrangement the panels stay shown. Press Play in -the studio, or run `./client --script PlayerList.luau`, to see the toggle -itself. Holding a key is a fact about a *viewer* and closing that gap needs a -script running in the replica, which `docs/DEFERRED.md` `D00122` carries. - -**The same arrangement without a second program is the studio.** Press Play and -the editor hosts both halves in its own viewports: a server view and a client -view, with a character in the client one. `Spawn Player` and `Remove Player` on -the ribbon act on the viewport you are in, so a Run becomes a Play one client at -a time, and two clients is what turns "the replica disagrees with the server" -into "these two clients disagree". A new game opens with a **Playground** and an -**Arena**, and a pad in each that teleports you to the other. - -**Live Instances** is where those two halves are listed, and it opens itself when -a run starts. A row per server and a row per client, each with the counts that -say whether a client is keeping up, and a `View` on each that is the way back to -that instance's viewport - closing a view no longer loses it. `Stop` on a client -row removes that client, which is also what the ribbon's Stop does while you are -looking at one, and `+ Player` on a server row admits another. A client view is -listed here rather than among the scenes in the Worlds panel: it exists only -between Play and Stop and there is nothing about it to author. - -### Things fall *(v0.13)* - -A new game gained a fourth world at v0.13, and it is **Slide** - a curved -ramp with blocks that spawn at the top, slide down, launch off the lip and are -destroyed ten seconds later. It is the first world this engine ever simulated. - -**The physics module was complete and connected to nothing.** Integrate, broad -phase, narrow phase and solver had suites, benchmarks and no consumer: -`RegisterPhysicsSystems` was called from `physics/tests/` and nowhere else. Every -world that shipped was anchored throughout, which is why nobody noticed - an -anchored part carries no rigid body at all, so a scene of anchored geometry -integrates nothing and solves nothing. - -Two things were missing, and they are separate features: - -| | | -|---|---| -| the pipeline | `PreparePhysicsWorld` and `RegisterPhysicsSystems`, per world | -| the weight | `scene::PrepareGravity` and `RegisterGravitySystem` | - -**`Engine::physics` deliberately has no gravity and should not gain one.** A -top-down game should not have to switch one off, so `RigidBody` carries no -gravity scale and the pipeline has no gravity step - weight is a rule the world -holds. `scene::Gravity` is that rule: a resource, so a world under water or on -the moon authors a different vector, defaulting to 9.81 m/s² down. Earth's, in -metres, because this engine measures parts in metres - Roblox's 196.2 is the same -acceleration in studs and copying it here would make everything fall twenty times -too fast. - -The editor installs both on every world it makes. **It costs an anchored world -nothing**, which is why it can be on everywhere rather than behind a switch -nobody would find. - -For a script the whole of it is one line: - -```lua -part.Anchored = false -- and it has a rigid body, and it falls -``` - -### Swapping a mesh's texture *(v0.13)* - -A `MeshPart` names two things and they are independent: - -```lua -part.MeshId = "characters/hero.amesh" -part.TextureID = "skins/hero-winter.atex" -``` - -**Setting only `MeshId` still works** - the part wears whatever each of its -submeshes recorded at bake time, which is how a character with six sheets loads -without a script knowing any of them. What it does not give you is a handle: the -sheet names live *inside* the mesh file, so there is nothing to read and nothing -to put back. - -`ContentService:GetMeshTextures(mesh)` is that handle: - -```lua -local worn = ContentService:GetMeshTextures("characters/hero.amesh") -part.TextureID = worn[1] -- the same picture, said out loud -part.TextureID = "skins/summer.atex" -- a different outfit -``` - -It answers in **submesh order, unsorted, duplicates kept** - unlike every other -list that service hands out. Which run wears which is a fact, and a character -with twenty submeshes sharing four sheets is four names repeated. An untextured -run is an empty string in its own slot rather than a hole, so the index keeps -meaning "submesh number". A built-in wears nothing and answers an empty table, -as does a mesh this world has not been told about. - -**`TextureID` overrides every run at once** - Roblox's rule and this one's - so a -twenty-submesh character given one sheet wears that sheet all over. That is the -thing to know before reaching for it on an imported model. - -`run-mesh-grid` shows both halves: each cell names its own sheet explicitly when -it has exactly one, and a row of identical cubes below wears the characters' -sheets, so the only difference between them is a string. - -### What a mirror can show *(v0.13)* - -A `SurfaceCamera` has an `Effect`, and `run-mirrors` gives each of its four walls -a different one: - -| `Enum.SurfaceEffect` | What it looks like | -|---|---| -| `None` | the reflection as rendered | -| `NightVision` | an image intensifier - everything to green, lifted, grained, vignetted | -| `Thermal` | a heat map, black through blue, magenta, red and yellow to white | -| `Cctv` | grey, scanlined, with a bright band rolling down it | -| `Swirl` | the image twisted about its own centre, turning slowly | - -```lua -local reflection = Instance.new("SurfaceCamera") -reflection.Face = Enum.NormalId.Back -reflection.Effect = Enum.SurfaceEffect.Thermal -reflection.Parent = pane -``` - -**A grade on the way out, not a second render.** The surface pass draws the world -exactly as it would have whatever the effect says; the effect is applied in -`opaque.frag` where the pane samples the texture. So a graded wall costs the same -as an ungraded one - no extra target, no extra pipeline, no extra bind - and -switching one at runtime redraws nothing. - -That is also why a reflection of a reflection is graded once. The texture holds -an ungraded picture and only the pane showing it grades, so standing between the -thermal wall and the swirl gives you a corridor carrying both, each applied by -the wall it belongs to rather than compounding down the recursion. - -**Thermal reads luminance as temperature**, which is a lie an engine with no -thermal model cannot avoid. It looks right because bright things in a lit scene -usually are the hot ones, and `scene::SurfaceEffect` says so rather than implying -otherwise. - -**A closed list rather than a shader name**, and that is a deliberate limit. This -pipeline has one fragment program for opaque geometry; a mirror naming an -arbitrary program would need a pipeline per program, a compilation path, and an -answer for what happens when the file is missing on somebody else's machine - -which is the render graph `ROADMAP.md` puts behind a prototype project, not a -field. Every effect here is a handful of instructions on the fragment that -samples an image somebody already rendered. - -### Holes that lead somewhere else *(v0.14)* - -A `Portal` is a `SurfaceCamera` with one more property on it, and that property -is the whole feature: - -```lua -local hole = Instance.new("Portal") -hole.Face = Enum.NormalId.Back -hole.Destination = someOtherWall -- and the wall is now a hole -hole.Parent = pane -``` - -A mirror puts its camera where the eye would be reflected through the pane's own -plane. A portal puts it through `destination · half-turn · source⁻¹` instead. -Everything after that is the mirror's path unchanged - the same surface pass, the -same projected sampling in `opaque.frag`, the same per-surface `TagFilter`, the -same one-frame-old texture - so a hole costs a mirror and nothing else. - -**Nothing constrains the two panes to describe one space**, and that is the -non-Euclidean part. A destination turned, moved, or placed three hundred units -away is still a legal pair, so a room can be bigger on the inside and a corridor -can turn through more than four right angles. `run-portals` is a square building -with four quarters and three rooms in it: hall, library and garden clockwise -round the middle, and one pair of holes joining the garden's west wall to the -hall's south wall, where the fourth room would have been. The two panes are -perpendicular, so the pair carries a quarter turn - walk the loop and you make -three right turns and arrive where you started, facing the way you set off. The -middle of that building is a cone point with ninety degrees missing. -`NON-EUCLIDEAN.md` is the investigation behind it. - -**`Face` is resolved on the destination too, and it is the one rule to know.** -The far frame is built by applying the *portal's own* `Face` to the destination's -transform, so the destination must be a part whose matching face points at the -space the hole should show. Aim it at a wall whose matching face points the other -way and nothing complains - the pane renders, and it shows the empty space behind -that wall. For unrotated rooms that means the wall on the same side of the far -room; rotating the destination is the general answer. - -**A destination that is missing, cleared or deleted falls back to a mirror** -rather than to a blank pane. A surface that stopped reflecting reads as something -to fix; a pane that vanished reads as a broken renderer. - -**You can walk through these.** `scene::CrossPortals` maps a body - and both -halves of its `Motion`, and the camera's yaw when the body is the one the camera -follows - through the same product the picture goes through, and `scene::OpenPortals` -takes the pane's collider out of the solver's way so a walker reaches it at all. -Press Play in the studio on `Portals-1-world.luau`, or host it with -`scripts/demos/run-local-server.sh`; the standalone client has no character and -walks the lap on rails instead. What is left of `docs/retired/DEFERRED.md` D00112 is the -seam on the frame you cross, which needs the portal chain rendered inside the -frame, deepest first. - -**`Bidirectional` off makes it a one-way door.** By default a mouth may be -entered from either side and the pair's map is its own inverse - walk through -and walk back and you are where you started. Turn it off and only a body that -enters *in front* crosses, where in front is the side the face's normal points -at: the side the pane shows its image on. That is an entrance you cannot walk -back out of, or an exit you cannot be pulled back into. Nothing else changes - -the pane still draws from both sides, still cuts a body standing in it and still -lights the room behind it, because a mouth that vanished when you walked round -it would read as a rendering fault rather than as a rule. - -**A pane must be one part and it should be white.** One part because the -rectangle a surface camera is fitted to and the rectangle `CrossPortals` tests -against is that part's face - a hole built out of several is several holes -against a budget of sixteen. White because `opaque.frag` tints the projected -image by the pane's own colour, so a grey pane shows the far room dimmed, which -reads as a lighting bug in a room that is lit correctly. - -**`NonEuclidean.luau` is the catalogue rather than the mechanism.** Six exhibits -in a row, twelve holes, and the camera sweeps past them: a tunnel shorter inside -than out and one longer inside than out, a house with four doors onto three -rooms, a pillar with a different room behind each side, a hill whose bottom -opens onto its own top, and a cell that holds four times the volume it occupies. -Every one of them is the same pair of panes with the destination moved - no new -engine code, which is the point. The one shape it *cannot* express is the tunnel -that changes your scale, because the map through a portal is rigid; that is -filed with D00112 as well. - -```sh -scripts/demos/run-demo.sh Terrain --stats # uncapped, held at 165 fps -scripts/demos/run-demo.sh Terrain --stats --graph # extra flags reach the client -MAX_FPS=60 scripts/demos/run-demo.sh Terrain --stats # hold a different rate -MAX_FPS=0 scripts/demos/run-demo.sh Terrain --stats # no limit at all -PRESET=release scripts/demos/run-demo.sh Terrain --stats # any preset but `server` -scripts\demos\run-demo.bat Terrain --stats # Windows, same everything -``` - -**`--uncapped --max-fps 165` is one decision rather than two**, and every script -here makes it. `--uncapped` alone turns off the vblank wait and lets the loop -run as fast as the GPU allows - several hundred frames a second of heat for a -display that shows a fraction of them. The vblank wait alone paces to whatever -the display reports, which is not comparable between two machines and is not -what a variable-refresh monitor does. So: do not wait for the display, and do -not run away from it either. - -The pair is what `--max-fps` is for, and it does nothing without `--uncapped` - -with the wait on, the display is already the limiter and a second one fighting -it produces judder rather than a lower number. - -**Running a demo without them is what a bottleneck looks like when there is -none.** Bare, `EditableMesh.luau` reports a mean frame of 7.8 ms with a 34 ms -tail and reads as choking; with the pair it is 1.3 ms, and uncapped with no -ceiling at all it is 0.26 ms - a quarter of a millisecond of actual work behind -eight of waiting. The whole difference is the `submit` span, which is the CPU -sitting on the vblank, and it is worst on a scene that is *not* busy: with only -one frame in flight there is nothing queued to cover a missed interval, so -missing by a hair costs a whole one. - -`--frames-in-flight` is the other end of that and is **not** the cure - measured -on this machine the tail grew with the queue rather than shrank, 35 ms at one, -52 at two, 69 at three, because a deeper queue means a longer stall when a -present is late. It is here for parity with the studio, which has had it since -v0.14, and because it is the first knob anybody reaches for. Reach for -`--uncapped` instead. - -Everything shared lives in `_common.sh` and `_common.bat`; a scene script is a -header, a filename and its own flags. They call CMake rather than `just`, so the -two halves cannot drift apart, and they resolve the repository from their own -path - run them from anywhere. The `.bat` wants a Developer Command Prompt, -because it builds before it runs and a plain `cmd` window has no compiler in it; -`scripts\build-windows.bat` first leaves nothing for it to compile, and -[On Windows](#on-windows) is the reason either is necessary. - -### Options - -``` ---stats Open the F3 statistics panel at startup ---net Open the F4 network panel (needs --connect) ---graph Open the F5 frame graph at startup ---uncapped Present without waiting for vblank ---max-fps N Hold this frame rate; needs --uncapped ---frames-in-flight N Frames the CPU may queue ahead of the GPU, 1 to 3 ---verbose Log at trace level ---force-serial-compute Run parallel dispatches on one thread ---worlds N Worlds to simulate and composite (default 1) ---view-spacing UNITS World units between composited views (default 40) ---entities N Cubes in the demo scene, per world (default 2048) ---tick-rate HZ Simulation ticks per second (default 60) ---frames N Exit after N presented frames ---width PX Window width (default 1280) ---height PX Window height (default 720) ---profiler-tab NAME frame, categories, systems, counters or heap ---script PATH Luau or JavaScript scene to run at startup ---game PATH Game file to play single-player (.agame) ---connect HOST:PORT Replicate a world from this server ---server-key HEX Pin the server identity ---cdn SOURCE Content source; repeatable, `dir:PATH` allowed ---content-cache DIR Keep verified content between runs ---publisher-key HEX Pin the content publisher ---sound PATH Loop a .wav or .mp3 ---capture PATH Write a BMP near the end; needs --frames ---capture-sequence DIR Write each frame as BMP + camera JSON; needs --frames ---enable-profiler SECONDS Wait for a Tracy profiler before starting ---profile-seconds SECONDS Run for this long, then exit ---profile-snapshot PATH Write a frame-graph snapshot when the run ends ---heap-report PATH Write a heap profile when the run ends ---heap-growth-limit BYTES_PER_S Exit 3 if a tag's live bytes climb faster than this ---heap-warmup SECONDS Leave this much of the start out of the growth fit ---override-assets-directory DIR Read shaders and data from here ---help Show this text -``` - -Naming a `--profiler-tab` opens the graph, and `--profile-seconds` turns -collection on - asking to see something is not a separate flag from showing it. -`--profile-snapshot` does the same and then writes the window out, which is how -a profile gets read rather than looked at: the overlay is a picture and the -snapshot is a table with a mean, a median and a worst reading per span. - -**Pair it with `--force-serial-compute` or the interesting spans are missing.** -A world ticks on a pinned worker and a span opened off the frame's owning -thread is refused, so `worlds (pinned workers)` arrives as one bar with the -whole tick inside it and nothing underneath. Serial makes the frame slower on -purpose and complete. - -**And read the table as per occurrence, not per frame.** A run that is dropping -ticks runs several of them per frame, and each one opens its own `ecs.systems`; -the column is the worst *single* reading, so the parent can be several times -the child without a millisecond being unaccounted for. - -`--game` plays a `.agame` written by the editor: every world in it is -simulated, its scripts run with both roles true, and there is no socket and no -server library involved - single-player is the format and a VM, not a server -hosted in this process. Given both `--game` and `--script`, the game file wins -and the client says so rather than choosing quietly. - -For a supervised portal image producer, the driver launches `client` with -`--game PATH --headless --frames N --presentation-world NAME ---presentation-session SESSION` and an inherited `ProcessChannel`. -The session must be positive and fresh for each host lifetime. The selected -world must exist in the game. Only that world runs locally; the other world -names remain remote routes. -For a live producer, replace `--game PATH` with -`--connect HOST:PORT --server-key PUBLIC_KEY`. This renders an authenticated -replica under `--presentation-world NAME`, without a local demo, fresh player, -movement messages or audio device. It advertises only after the snapshot joins, -and withdraws the endpoint if the source session ends. Game-file and live-source -arguments are mutually exclusive. Trusted driver directories supply remote world -names that were not part of the replica. -It advertises its image endpoint, accepts trusted driver route updates and -serves HDR requests between ticks. Stop or channel disconnect ends the loop. -These flags require a supervising process, so a standalone shell invocation -without the inherited channel fails startup. -Supervised producers may use `--frames -1`: their driver link and replication -source bound their lifetime. Ordinary headless clients still need a frame budget. - -A listening Server can own this launch with `--presentation-program PATH`, where -PATH is the staged Client executable. The option also passes to remote world -hosts. Each listening host launches one live producer, pins its server identity, -grants its temporary client identity through restricted admission, and advertises -the delegated image/topology endpoints through its own presentation directory. -The producer consumes one replication connection slot. Shutdown or producer -failure withdraws its endpoints; there is no automatic producer restart yet. -Omitting the option keeps the Server deployment independent of a graphics stack. -Supervised hosts load saved projects by their granted world names; ungranted -worlds stay remote and run no local scripts. - -Ordinary connected Clients discover image/topology routes through their existing -authenticated play connection. Server grants private return channels per player -and withdraws them on disconnect. Control/session endpoints stay out of the player -presentation directory. No additional Client flag is needed. Presentation streams -are bounded to 64 frames and 32 MiB per direction, with at most 16 player streams -per Server. A successor connection replaces the old Client route directory. -An exited or disconnected image producer is reaped and restarted with a fresh -identity and session. Its old endpoints are withdrawn before retrying. Repeated -failures back off from one second to 30 seconds; 30 seconds connected resets that -delay. Server shutdown cancels pending retries. -Once joined, Client displays the replica's own camera and unshifted draw rows; -`--view-spacing` remains for composing local worlds before a play connection joins. -Portal surfaces, lighting and image requests follow the joined world through -successor adoption. The `[portal-successor]` process test checks discovery and a -decoded seam-image request alongside the six session handoff outcomes. It does -not compare the pixels of a complete physical crossing. - -Build `client` and `test_client`, then run -`.cache/build/dev/tests/test_client '[presentation-host]'` for the actual -process-channel GPU check. It covers saved and live worlds, changed lighting -pixels, source-session loss and driver shutdown. It uses an isolated configuration -and game under the build's tests directory. -Build `server` too and run `test_client '[server-presentation-host]'` for the -Server-owned launch and relay check. It covers restricted admission, seam and eye -images, a saved project with an ungranted world, Stop and driver disconnect. -The player-connection cases discover routes, receive topology and a fragmented -128 KiB image over authenticated UDP, and recover after a missing-endpoint request. -The consumer in this fixture is a CPU Connector; it does not verify a complete -standalone Client walk through the portal. -On POSIX, the player/seam case also expires its first producer, observes endpoint -withdrawal and receives another image from its replacement over the same player -connection. A retired-receipt request must not close that connection. The Windows -case does not inject this producer lifetime limit. - -Run `test_client '[portal-product-walk]'` for the combined physical round trip. -It uses the real Client, a listening Server, its supervised destination and both -image producers. SDL keyboard events drive entry and return; the test requires -both Client session adoptions. Its saved game runs both worlds at 30 Hz and then -60 Hz against the listening driver's 30 Hz cadence, with both trailing and -scroll-selected first-person cameras. Replicated LocalScripts sample the local -character's Humanoid camera subject on Heartbeat before entry, after adoption -and after return. Each stage checks zoom while stationary before resuming movement; -a moving predicted camera and the delayed authoritative body are different samples. -Missing services and retired characters are outside this sample window. -When trace logging is compiled in, the fixture checks actual move submissions -for increasing ticks in each connection, including updates between presentations. -Right-button mouse motion must also change the observed camera direction during -both legs. Mouse events follow captured frames, including the missing-rig gap; -the accumulated control yaw must not reset at adoption. Each camera/rate case -runs with automatic follow and with a LocalScript explicitly assigning the -Humanoid to `CameraSubject`. Each combination runs both a stop-at-adoption case -and a case holding its movement key for 12 destination submissions, for 16 -scenarios total. Held-key captures add `-held` before `-frames` and require moving -native prediction on both legs. Capture metadata includes `subject_automatic` so -the explicit case cannot silently exercise automatic follow instead. Only this -property opts into runtime writes on a live predicted camera; authority-owned -cameras and ordinary replica properties remain protected. Each case records 600 -frames at a 60 Hz presentation limit, checking -every BMP and its matching camera metadata. Every frame after the initial -Humanoid binding must contain visible scene pixels. The fixture's default camera -far plane must survive binding and both handoffs. -Every foreign-eye frame must have an image, and every ready whole-eye image must -show the fixture's floor pixel, catching missing replies and images bound to a -different world or draw slot. The final eye -must return to `server.world`. Source-world portal-surface continuity remains a -separate check. -The 128 x 128 sequences are at -`tests/portal-client-walk-{30,60}-{first,third}-frames/` under the build directory. -Explicit-subject sequences add `-explicit` before `-frames`. -Capture metadata records `submitted_move_tick`, `replication_applied_tick` and -`unconfirmed_inputs`. `predicted_root` remains the immediately reconciled replay -baseline; `presented_predicted_root` is the shared fractional body/camera pose. -Small positional corrections blend out over 100 ms of presentation time. -Larger ones use at most half walking speed and settle within one second; -corrections beyond that bound snap to authority. Remaining offset/time are -recorded separately. The held movement gate measures -the displayed pose. Authority, replay coverage and input acknowledgements are -never delayed by this presentation correction. Its vector maps through the -portal on adoption; stopped movement still settles, and unchanged authority -poses do not restart the correction timer. Input submissions must keep advancing through Proceed and -source retirement; the client's input clock is separate from the server's world -clock. Protocol 12 carries explicit consumed-input acknowledgements, so Client -and Server must be rebuilt together. -The product Client keeps submitted input ticks monotonic across adoption. -`input_local_epoch` and `input_sequence_epoch` show how the current replica's -clock maps onto that timeline; the replica's own `tick` is unchanged. The walk -checks increasing submissions across connections as well as within each one. -Portal host movement uses the PPT5 bus envelope and carries the originating -client input stamp through control assignment and acknowledgement. All portal -hosts must use the same build. `AcknowledgedInputTick` in a transfer receipt -confirms destination control assignment; the separate optional `Motion` sample -contains a completed destination tick, input stamp, root pose and prediction -movement state. The sample is captured after physics and animation and is decoded -atomically. Motion samples also carry `SimulationSeconds`, the completed -world clock copied with the pose, independently of the acknowledged input stamp. -The shared motion codec has grown by eight bytes; rebuild all Clients and -Servers together. Held and native replay use this clock to keep acknowledged input duration -separate from integrated world time. The mapping survives adoption. When authority advances beyond all recorded input time, reconciliation accepts -its completed pose and rebases the uncovered interval onto that pose. It does -not wait indefinitely for a slow client clock. Unacknowledged control and jump -edges remain active even when their integration interval is already covered. -The authenticated source session forwards newer completed samples -under the accepted transfer claim. `portal_handoff.completed_motion` records -those accepted by the client, and the product walk requires them in both -directions. Pending handoffs replay retained submitted moves against these -samples using each move's recorded prediction duration. `portal_input_history` -reports retained count, coverage, last submission, applied sample ticks and -discarded inputs. `prediction_authority_world` identifies the destination when -its sample supplies the held prediction baseline. Run -`test_client '[portal-product-camera-clear]'` for four offscreen round trips -with a LocalScript clearing CameraSubject during source retirement, then an R -key restoring Humanoid follow after adoption. It checks the cleared pose across -the switch and completes the return. -Run `test_client '[portal-product-image-handoff]'` for the 30/60 Hz third-person -fixed-eye adoption checks. A blue destination floor distinguishes the far side -from the orange source floor; the check requires blue pixels to survive the -local-to-remote image switch. Keep representative before/after captures when -inspecting a failure, and remove redundant image conversions after review. This -check does not prove character appearance parity or absence of black frames -while the eye itself crosses the portal. -Run `test_client '[portal-input-history]'` for scaled-seam replay, history coverage -and snapshot lifetime checks. Client adoption carries the mapped presentation -onto the accepted destination rig and ignores older authority updates. The walk -requires prediction on each adoption frame. Body and Humanoid-follow camera use -a shared fractional prediction pose; adoption carries its phase between local -clocks without changing replay coverage. `test_client '[prediction]'` covers -fractional body/camera movement, replay duration and scaled-seam phase continuity. Native destination correction can -still jump later; these gates do not establish seamless movement. -For control timing, run the walk with -`ATOMIC_ENGINE_LOG_LEVEL='info,portal-input=trace'`. The opt-in `portal-input` -category logs forwarded and native assignments with destination incarnation, -player, input tick, world tick, step duration, direction and root position. -In the product Server, forwarded assignment runs before that world tick's -physics, while native assignment runs after physics and first affects the next -tick. Keep the final assignment for each physics tick when comparing held -controls; several received inputs may overwrite one another before a step. -These traces do not measure release cost or prove visual continuity. -`MoveInput::StepSeconds` carries seconds per client input tick separately from -host physics duration. Product Client fills it from its simulation clock; zero -means unavailable timing for callers with no such clock. Negative and nonfinite -values are rejected. The move payload is now 22 bytes, and forwarded PPT5 moves -preserve duration through retries and same-build snapshots. Rebuild Client and -Server together. Timed native portal controls now use a 64-entry queue on the authority Player. -Its clock is anchored to the last forwarded physics assignment. Controls for the -same physics tick coalesce while preserving jump edges. Pending input can lead -by at most one second or one physics step, whichever is longer. Untimed local -control cancels the queue; invalid or changed clock rates are refused. The -completed pose reports physics-applied input while this queue is active. -`test_game '[portal-input-schedule]'` checks timing, acknowledgement, capacity, -snapshot restore, rig replacement and return transfer. The `route=scheduled` -trace is pre-physics, like forwarded assignment. Adoption now carries the receipt-validated source history into the new -connector's bounded prediction buffer, mapping movement into destination space. -The connector resends this history before newer input and retains its unsent -suffix through local budget refusal. A matching applied pose can retire inputs -already handled by the source. Run `test_replication '[input-continuation]'` for -both wire modes with tight budgets and early applied-pose retirement. Actual -network loss/reordering and reconnect stress still need broader coverage; -held-movement camera cadence and the first destination-pose correction remain -open. -Server also sends `PlayMessage::PlayerMotion`, pairing a completed own-player -pose with that connection's input frontier, using physics-applied input for the native portal queue. This uses the same bounded -motion codec but a distinct message from the old source portal receipt. Client -prediction after adoption now uses these atomic samples, retaining unconfirmed -inputs until a matching pose is applied. `native_prediction` reports received -and applied pose/input ticks; `prediction_covered_through` exposes retained-input -coverage. Samples wait for the matching root component, and cannot acknowledge -an uncovered input prefix or replace prediction with a nonfinite replay result. -`test_game '[player-motion]'` checks the -codec; `test_server 'a client is told which player*'` checks real owning-client -delivery and a native input stamp distinct from the world tick. Build target -`server` explicitly before running process tests; rebuilding `test_server` -alone does not relink the program they launch. -Shots carry their rendered authoritative fractional tick separately from the -input sequence. The 36-byte shot payload requires matching rebuilt Client and -Server binaries. Run `test_examples '[shooting]'` for the codec and -`test_server "a client's click is a shot*"` for current and historical target -views with an independent input sequence. Zero or out-of-history view time uses -present state; this check does not verify shots across a pending portal handoff. -While a handoff is pending, `portal_handoff` records Proceed, Crossed, Resume, -Ready and Commit alongside destination character count and accepted-rig presence. -An unassigned destination character is only an availability diagnostic; it is -not evidence that this player's transfer receipt has been accepted. -`retained_character` identifies the local four-instance camera hold. Its stored -pose is `retained_root`, never `authoritative_root`; `predicted_root` records the -advancing presentation pose. `prediction_authority_tick` and `predicted_velocity` -identify that prediction's baseline and current motion. During a handoff, -`destination_applied_tick` identifies the successor replica's completed update; -`through`, `through_origin` and `through_scale` map source poses into destination -coordinates for comparison with `accepted_root`. These are distinct clocks and -poses, not proof that forwarded input has advanced destination physics. -The walk requires moving retained prediction to advance when input advances. -This is a GPU check and does not yet compare every displayed camera or pixel -across the seam. -Run `test_server '[portal-product-walk]'` for the CPU saved-game round trip at -both world rates over QUIC and datagram. It requires the transferred character -rig before Commit on entry and return, with its Humanoid health preserved. -Run `test_replication '[applied-order]'` for deterministic reordered structure, -multipart acknowledgement and bounded recovery checks. `[replica-clock]` verifies -that joins and resnapshots preserve local simulation and presentation time. - -### The heap *(v0.18)* - -The `heap` view is the one tab that is not about the last frame, and that is why -it is arranged the other way up: a plot of live bytes over minutes first, then -the tag tree under it. A frame that is fast and forty megabytes heavier than the -one before it reads as healthy on every other view here. - -Tags come from the `ENGINE_PROFILE` scopes the flamegraph is already made of, so -a row on one has a row on the other. `LIVE` is a tag and everything under it; -`SELF` is that tag alone; `GROWTH` is a least-squares slope over the readings, -sampled once a second. A dash means the tag is not moving. - -**A slope alone is not a leak, which is what the `--heap-growth-limit` check is -careful about.** A world loading its content is a step, and a step has a large -slope; a leak is a line. The check requires both a rate and a *fit* - see -`HeapProfile::RUNAWAY_FIT` - and `--heap-warmup` keeps the load out of the -window altogether. - -```sh -./client --headless --frames 1000000 --profile-seconds 120 \ - --script Rings.luau --heap-report heap.txt -``` - -writes the totals, the forty heaviest tags and the growth of each. Adding -`--heap-growth-limit 8192` makes the run exit 3 and name every tag over it, -which is what `just heap-soak` is built on. - -The hooks are compiled in by `MONO_HEAP_PROFILE`, which is on in every preset -but `release` - a shipped build does not pay a 24-byte header on every -allocation. A `release` client says so rather than showing an empty tree. - -### Soaking for leaks *(v0.18)* - -```sh -just heap-soak # five scenes, a minute each -just heap-soak 300 # five minutes each, so twenty-five -just heap-soak 60 8192 15 "Stress" # one scene, everything spelled out -``` - -Arguments are positional. A minute of wall clock is about a quarter of a million -headless frames and a real 60 Hz of ticks, so both axes a leak can live on are -exercised; the reports are left in `.cache/heap-.txt` whether the run -passes or fails, because a green soak is the baseline the next one is read -against. - -Not part of `just check`: it needs a GPU, for `just client-smoke`'s reason. - -### Benchmarks - -```sh -just bench # only what a change could have affected -just bench-all # every suite -just bench-accept # make what was measured the new baseline -just bench --filter ecs # one area -``` - -The same selection as `just test`, over `bench/` instead of `tests/`: a -benchmark declares `TEST_SUITE_ID` and gets the same cascading signature, so a -change at the bottom of the stack re-measures everything above it and nothing -else. That matters more here than for tests - a test suite costs milliseconds -and a benchmark suite costs seconds by design. - -Always against the `bench` preset, which optimises. A debug build measures the -debug build, and the danger is not that it is slower: it is that the *ratios* -between two implementations invert. - -``` -engine.ecs.bench.iteration - Each · 500k entities 198.84 us -1.8% - EachParallel · 500k entities 90.46 us +33.6% slower -``` - -**A number is reported, never enforced.** `just bench` does not fail on a slow -figure and it should not: a laptop on battery, a CI runner with a noisy -neighbour and a desktop with a compile going all swing further than most real -regressions - the `+33.6%` above is one of those, not a change to the code. Read -the number, then decide. `docs/CODE_QUALITY.md`'s rule about attaching a -measurement to an algorithm change is what this exists to serve. - -Take a baseline on a quiet machine, and say so in the commit. One taken while -something else was compiling makes every later run look like an improvement. - -### Compositing several worlds - -```sh -just run --worlds 3 --entities 512 -``` - -Three whole worlds, each with its own clock, its own store and its own view -channel, drawn into one frame side by side. They are *placed* rather than -overlaid because two worlds' coordinates do not mean the same thing - nothing -says they should, and drawing two scenes inside each other and calling it one is -the mistake `--view-spacing` exists to avoid. - -The renderer draws what the compositor took off the channels rather than -reaching into a store. Between a world at its tick rate and a frame at the -display's sit three slots and an atomic index, so a slow frame **drops rather -than throttles a simulation** - and a producer that stalls keeps its last frame -instead of vanishing for one. - -`--name=value` works everywhere `--name value` does. Everything after a bare -`--` is a path, including something that looks like an option. - -### While it is running - -| Key | Does | -|---|---| -| **F3** | frame counter - FPS now, and min/avg/max over the last twenty seconds | -| **F5** | frame graph - last frame's scope tree, and the heap | -| **F6** / **F7** | next / previous frame-graph view | -| **PgUp** / **PgDn** | scroll a graph taller than the panel | -| **-** / **=** | shallower / deeper flamegraph | -| **F8** | write `frame-graph-snapshot.txt` beside the binary | -| **Esc** | quit | - -The five frame-graph views are the flamegraph, time by category, per-system cost -from the scheduler, whatever was written to the metrics sink, and the heap. - -#### Reading the flamegraph - -One row per span, indented by nesting, with a colour chip for its category and a -timeline strip on the right showing *when* in the frame it ran - which the -numbers cannot say, because two systems costing 2 ms each read identically -whether they ran back to back or with the GPU wait between them. - -| Column | Is | -|---|---| -| `MS` | this frame | -| `RMAX` | the worst single reading in the last 300 frames | -| `SHARE` | of the frame | - -**`RMAX` is the column to read first.** A span costing 0.2 ms now and 14 ms -every fortieth frame shows 0.2 in `MS` on a panel repainted at any rate a person -can watch, and the fortieth frame is the one worth knowing about. The header -says how much history that maximum is over, because a worst case over a fifth of -a second and one over five seconds are different claims. - -Rows deeper than the depth limit are hidden and their nearest visible ancestor -is marked `+`, so a collapsed subtree never looks like a leaf. - -#### F8, for what the panel cannot show - -The panel shows one frame. `F8` writes the retained window - five seconds or -20,000 frames, whichever comes first - to `frame-graph-snapshot.txt`: mean, p50, -p99 and max per span, then the forty worst frames and the biggest spans in each. -That last section is what separates "this span spikes" from "the whole frame -went with it". - -Collection only runs while the panel is open, so `F8` with `F5` closed has -nothing to write and says so rather than leaving a zero-byte file. - -#### Stopping the graph on the bad frame - -In the studio's frame-graph panel, **Event scheduler** arms rules that pause the -graph on the frame that meets one. The reported case is a pump that lags now and -then: - -| Field | Set to | -|---|---| -| subject | `span` | -| name | `pump events` | -| test | `over` | -| threshold | `2` | - -The next frame whose `pump events` spans total more than 2 ms freezes the panel -with *that* frame on it, and the pause label says what fired and what it read. -**Resume** disarms the latch, so the next bad frame stops it again. - -A rule is evaluated where the frame is collected, not where it is drawn. That is -the whole reason the feature exists: the panel samples four times a second at its -shortest interval, and the frame you are hunting is one frame long. Subjects are -a span's inclusive or self time, a category's self time, the whole frame, the -unmarked remainder, or the dropped-span count. Rules are saved with the rest of -your preferences and armed at start-up, whether or not the panel is open. - -An `under` rule waits for its span rather than firing on a frame that never ran -it: "`pump events` under 1 ms" is a question about a frame that pumped events. - -### Measuring rather than watching - -```sh -just run --stats --graph --uncapped -``` - -**Always pass `--uncapped` when you care about the numbers.** Without it the -frame is paced by your display, every frame reads as 16.7 ms, and the flamegraph -is dominated by the swapchain wait. With it you see what the frame actually -costs. - -Remember that `dev` builds first-party code at `-O0` on purpose - a profile -there measures what the engine does rather than what the optimiser rescued. Use -the `release` preset when you want the shipped number instead: - -```sh -just preset=release run --stats --graph --uncapped -``` - -### Repeatable runs - -```sh -just run --frames 600 --entities 4000 --uncapped -``` - -`--frames` makes the client usable from a script or a CI job. The demo scene is -a function of elapsed time and is deterministic, so two runs with the same -arguments simulate the same thing - which is what makes comparing them mean -anything. - -**`--entities` is also the view channel's ceiling**, which is worth knowing -before it bites: it sizes the buffer a world publishes its draw list through, so -a scripted scene with more parts than that number publishes nothing at all and -the window is empty. The log says so - *"N instances is past this channel's -maximum"* - and the fix is to raise `--entities`, not to shrink the scene. - -### Seeing a frame - `--capture` - -```sh -just run --frames 60 --capture shot.bmp -``` - -Writes a BMP of the scene near the end of the run and carries on. **A diagnostic -rather than a feature, and it changes how the frame is rendered**: a capture -needs an offscreen target, so asking for one puts the scene into a texture and -presents the window from that. A game pays nothing for it because the flag is -off. - -Needs `--frames`, because the capture is requested one frame before the last so -that it is written by the next and the run still ends when it was told to. - -Use `--capture-sequence DIR --frames N` to record every rendered frame as -`0.bmp` / `0.json` through `N-1.bmp` / `N-1.json`. The JSON records the actual -submitted camera, controller angles/basis, input and eye worlds, portal mapping, Humanoid subject and -authoritative/predicted character roots when available. Portal entries record -the sampled image handle, authored key and aperture geometry. World names may be local -replica aliases; the eye history records its authored world name. -The frame budget must be positive, and `--capture` cannot be combined with this -flag. Each capture waits for GPU readback and writes files, so use this for -visual diagnosis, not performance measurements. - -```sh -just run --frames 60 --entities 2048 \ - --script .cache/build/dev/assets/examples/scripts/Meshes.luau \ - --cdn dir:store --publisher-key PUBLIC --capture meshes.bmp -``` - -The closing log line is the other half of the same question: *"88302 triangle(s) -in 136 draw call(s) at the busiest frame"*. A world of cubes is twelve triangles -an instance and a world of imported meshes is tens of thousands, so a run whose -triangle count did not move is one where every `MeshId` resolved to the fallback -cube - which is the deliberate degraded state and looks like a scene of boxes. - ---- - -# The server - -Headless. No window, and no renderer in the binary at all. - -```sh -just host # 30 Hz until you stop it -just host --ticks 300 --entities 20000 -./.cache/build/dev/server/server --help -``` - -### Options - -``` ---unpaced Tick back to back instead of pacing to the tick rate ---graph Collect the frame graph (for a Tracy capture) ---verbose Log at trace level ---force-serial-compute Run parallel dispatches on one thread ---mcp-port PORT Open the loopback control surface (default 8734) ---tick-rate HZ Ticks per second (default 30) ---physics-tick-rate HZ Physics steps per second (default: the tick rate) ---replication-tick-rate HZ Snapshots per second (default: every tick) ---entities N Entities in the placeholder world (default 4096) ---ticks N Exit after N ticks ---seconds N Exit after N seconds ---game PATH Scene script, or a .agame universe to host (v0.7) ---record PATH Write a recording of this run ---replay PATH Replay a recording instead of simulating ---override-assets-directory DIR Read staged data from here ---chatter Make every world publish on a shared topic ---host NAME Run as a supervised host under a driver ---world NAME A world this host was granted (repeatable) ---remote-world NAME Place this world in a host process (repeatable) ---worlds-per-host N Shared worlds per host process (default 8) ---host-program PATH The program a host runs (default: this one) ---processes N How many processes share this machine ---listen PORT Serve a world to clients over UDP ---transport MODE quic (default), datagram, or both ---identity-key HEX Ed25519 seed for the server identity ---content-store DIR Serve a local content store ---content-port PORT Port for the attached content origin ---content-grant-key HEX Secret used for content grants ---help Show this text -``` - -### Three rates, not one - -A world ticks, steps its physics, and publishes snapshots. Those are three -different costs and they get three different numbers: - -```sh -./server --game My.agame --tick-rate 60 --physics-tick-rate 30 --replication-tick-rate 20 -``` - -- `--tick-rate` is what scripts, signals and character input run at. -- `--physics-tick-rate` is what the solver runs at. Lower it when a world is - spending its tick in physics and the scripts still need the full rate; raise - it for a world of fast, precise bodies. Zero follows the tick rate. -- `--replication-tick-rate` is how often a snapshot goes on the wire. Zero - publishes every tick. Lowering it does not lose state: the world holds its - change bits across the ticks it does not publish, so a property written on - any of them still reaches the client on the next one that does. - -Both are measured in *simulated* seconds, so a suspended world owes nothing for -the time it was asked to and an idle world at 2 Hz cannot publish twenty times a -second however loudly it was asked to. - -The three flags apply to the worlds this program creates itself. A `.agame` -carries `physicsTickRate` and `replicationTickRate` per world under -``, and those win - a scene authored to solve at 30 solves at -30 whoever hosts it. - -### Recording and replaying - -A recording is one snapshot plus every bus envelope applied since, which is -complete because a world is deterministic given its state and its inbox. - -```sh -./server --entities 512 --ticks 200 --unpaced --record run.rec -./server --replay run.rec # the same run, again -./server --replay run.rec --record again.rec # and record what it replayed -``` - -The third form is what `just replay-check` runs: `again.rec` has to come back -byte-identical to `run.rec`, which says the snapshot, the frame times and every -envelope all reproduced - not merely that the replay survived. -`just determinism` makes the weaker but broader claim, that two live runs of one scene -produce identical files. Both are same-binary, same-machine; cross-machine -agreement is deliberately not promised, because floating point differs between -compilers and chips. - -### Host mode - -A host is not a different program. It is this one, holding some of a universe's -worlds in its own address space so that a hard fault in one of them takes that -process rather than the server - which is what makes the grouping a deployment -decision instead of an engine one. - -You do not run the host side by hand. You run the *driver* side, and it spawns -what it needs: - -```sh -./server --seconds 10 --chatter --remote-world lobby --remote-world arena -``` - -That starts one host holding both worlds, links it, and routes every bus -operation through the driver's own MessagingService, MemoryStore and DataStore - -there is one router, so a world behaves the same wherever it is held. `--chatter` -exists because there is no game file yet and therefore no traffic: it makes every -world publish its name and tick on a shared topic, which is the only thing that -crosses a link until v0.5 gives worlds something real to say. - -Running the host side directly is refused: - -```sh -./server --host host.one --world lobby --world arena # refuses: no driver -``` - -Deliberately. A host with no driver would tick worlds nobody asked for and answer -to nobody, and accepting it would make `--host` look like a way to run the server -under a nicer name. - -`--processes` is the worker budget. Every process calling for one worker per core -is the bug it prevents: a driver and seven hosts on a twenty-four core machine -would run a hundred and ninety threads over twenty-four cores. The driver works -it out from the hosts it is about to spawn and passes the answer down, so you -should not normally set it. - -### Stopping it - -Ctrl-C, or `SIGTERM`. The handler sets one flag that the loop reads between -ticks, so the current tick finishes and the run summary still prints: - -``` -30 tick(s) over 0.97s · mean 0.336 ms · slowest 0.540 ms · 0 overrun(s) -``` - -**`overruns` is the number worth reading.** It counts ticks that took longer -than their budget. Zero means the tick rate was actually held; anything else -means the server is behind, and `slowest` tells you by how much. - -### Measuring a tick - -```sh -just host --unpaced --ticks 1000 --entities 50000 -``` - -`--unpaced` removes the sleep between ticks, so `mean` measures the simulation -rather than the pacing. Use it for any comparison; leave it off to check that a -given entity count actually holds a given tick rate. - ---- - -## Every arrangement of the halves *(v0.18)* - -```sh -just unified # the bisection, one screen of it -just unified --all # all twelve, one line each -just unified --arrangement lossy+relayed # content over a link that loses -``` - -`unified_tests` holds a server and a client in **one process** and lets you -choose what goes between them. It answers two questions that a pair of real -programs cannot. - -**Which stage lost the world.** `--arrangement direct` hands the authority's -byte vectors straight to the replica: no socket, no framing, no cipher, no -acknowledgement window, no MTU. The table it prints is a column per stage - -produced, sent, applied, drawn - so the first column that stops making sense is -the answer. A blank scene here is above `net`; a blank scene against a real -server and a full one here is below it. - -**Whether the modules agree with each other.** Underneath the table it prints -every module's own report - `replication`'s authority and replica, `net`'s -sessions and links, `cdn`'s publication, `server`'s relay, `client`'s content -link, `network`'s beacon and directory, and `core`'s heap - and then the claims -that span two of them. Those are the ones no module's own suite can make, -because the tier system stops each module linking the other end of its seams: - -``` -contradictions - client/server the relay answered 12 route(s) in full and the client reassembled 11 -``` - -### The three axes - -| axis | values | what it adds | -|---|---|---| -| transport | `direct`, `loopback`, `lossy` | nothing, a real `net` link, a link that drops datagrams | -| content | `relayed` | a `cdn` publication, a `server` relay, a `client` link | -| discovery | `advertised` | a `network` beacon announcing and a directory collecting | - -Names join with `+` in any order, and `--all` runs the whole cross product - -twelve of them. `--list-arrangements` prints the names, which is how -`just unified-soak` stays in step with the axes rather than holding a copy. - -### Options - -| option | what it does | -|---|---| -| `--arrangement NAME` | one arrangement; `direct` unless given | -| `--all` | every arrangement in turn, one summary line each | -| `--list-arrangements` | print the names and exit | -| `--entities N` | rows in the placeholder world (64) | -| `--scene PATH` | author the server's world from a scene script instead | -| `--ticks N` | ticks after the join (120) | -| `--seconds N` | run on wall clock instead, for the heap axis | -| `--tick-rate HZ` | the authority's rate (30) | -| `--frames-per-tick N` | frames drawn per tick (4) | -| `--delay-ticks N` | the snapshot buffer's delay (2) | -| `--drop N,N,...` | ordinals to lose silently | -| `--quiet` | the reports only, no line per tick | -| `--heap-report PATH` | write the heap profile when the run ends | -| `--heap-growth-limit BYTES` | exit 3 when a tag climbs faster than this | -| `--heap-warmup SECONDS` | readings to leave out of the growth fit (10) | - -`--drop` numbers different things per transport, because a transport can only -lose what it carries: outgoing **messages** under `direct`, datagram **arrival -numbers** under `lossy`. `loopback` drops nothing - it exists to add framing and -nothing else. A `lossy` run with no `--drop` uses a built-in set that lands -inside the join, so the reliable channel's retransmission is exercised rather -than merely available. - -The exit code is `0` when every arrangement joined and no module contradicted -another, `1` when one did, and `3` when a heap tag ran away. - -### Soaking the seams *(v0.18)* - -```sh -just unified-soak # twelve arrangements, 25s each -just unified-soak 60 # twelve minutes -just unified-soak 30 4096 10 # tighter limit, longer warm-up -``` - -`just heap-soak` asks whether drawing a world leaks. This asks whether -*crossing* one does, which is a different question with different answers: a -leak in a session's retransmission buffer or in the relay's reassembly is -invisible to a client that is not connected to anything. - -One process per arrangement, deliberately - a single process running all twelve -in turn has one heap history with twelve workloads in it, and a slope fitted -across that is fitted across the changeovers. Reports land in -`.cache/heap-unified-.txt` whether the run passes or fails. - -Not part of `just check`: at the default it is five minutes, and a check -somebody skips is a check that is not run. - ---- - -## Which transport a session runs on - -**QUIC is the default and the server decides. The client has no flag.** - -```sh -server --listen 9000 # quic, which is the default -server --listen 9000 --transport datagram # the stack this engine had before v0.19 -server --listen 9000 --transport both # whichever a client opens with -``` - -A client always opens with QUIC. A server that does not serve it answers with a -refusal rather than with silence, and the client retries over the datagram -stack immediately - one round trip, not a timeout. A server that serves only -QUIC refuses a datagram hello the same way. Either way the log line says which -transport the connection landed on and why: - -``` -replication: quic did not connect (the server does not serve this transport) - retrying over the datagram wire. -replication: connected over datagram on attempt 2 of 2 -``` - -**Both modes share one UDP port.** There is no second socket and no second -accept loop: the first packet from an unknown peer is a QUIC Initial or a -`net::Packet`, and one bit of its first byte says which. `mono.engine/net/ -include/engine/net/Wire.hpp` carries the bit positions. - -A server that is announcing itself puts its mode in the advert, so a client that -found it in a browser opens on the right stack and pays no refusal at all. A -typed-in address has no advert, so that client pays one round trip when the -server is on the old stack. - -Both transports use `--identity-key` when supplied. Otherwise the server draws -an ephemeral signing identity for the run and logs its public key. A client must -pin that public key through trusted discovery or configuration to identify the -server. Portal lease routes carry the destination's public key for this purpose. - ---- - -## Proving which server a client reached - -```sh -server --listen 9000 --identity-key $SEED # 64 hex characters, an Ed25519 seed -client --connect HOST:9000 --server-key $PUB # the public half the server logs -``` - -**Without a trusted server-key pin the exchange identifies nobody.** It is encrypted, so a -listener on the path learns nothing; but whoever *carries* the two key-exchange -messages can substitute their own key, hold one session with each side and read -everything. `net/Handshake.hpp` has said so since v0.3. - -With them, every `Welcome` carries an Ed25519 signature over the transcript, and -a relay cannot produce one - it would have to make the server sign a transcript -naming the relay's own ephemeral key. A client whose pin does not match refuses -outright rather than connecting anyway: - -``` -replication: this is not the server that was pinned - refusing to connect. -``` - -The server prints the public half on start-up, which is what to give a client: - -``` -replication identity f78b1da9b3dfb3fa3a3e54c43e79389d2f04d6bccb62984f28bd6f91798a750d -``` - -**It is the same key a publisher signs content with** - `cdn --signing-key` and -`client --publisher-key`. A server and the content it serves are one identity as -far as a player is concerned, and two keys would be two things to distribute and -two chances to pin the wrong one. - -**Both ends default to the weaker mode and both say so**, because refusing to -run without a key would refuse every deployment in this engine today, and -refusing quietly would be worse than either. - ---- - -## Finding a server without being told an address - -Everything below is off by default. A recipe that does not ask for it opens no -extra socket and broadcasts nothing. - -### On the same switch - -```sh -server --listen 0 --advertise --session-name "User's game" -client --browse -``` - -The server announces itself once a second to `255.255.255.255:47600` and the -client listens there. `--listen 0` binds an ephemeral port and the announcement -carries **the port that was bound**, so nothing has to be agreed in advance. - -The address a client dials is the address the announcement *arrived from*, with -the advertised port. A host binds `0.0.0.0` and cannot know which of its -addresses a given client can route to; the one a datagram already crossed needs -no guess. - -| Flag | On | What it does | -|---|---|---| -| `--advertise` | server, cdn | announce on the subnet | -| `--session-name NAME` | server | what a browser shows | -| `--browse` | client | look instead of being told | -| `--browse-seconds N` | client | how long to look (default 3) | -| `--session-name NAME` | client | join that one rather than the first | - -**The search is the one blocking wait in the client**, and it happens before the -loop starts, in the same place as binding a socket. A beacon announces once a -second, so anything under two seconds is a coin flip. - -### Invited only - -```sh -server --listen 0 --advertise --session-key "a sentence we agreed on" -client --browse --session-key "a sentence we agreed on" -``` - -A private session's announcement carries a MAC under the key, so a client -holding it can tell the session it was invited to from somebody else's wearing -the same name. A key is 64 hex characters or a passphrase, and the same words -derive the same key on both machines. - -**Private authenticates; it does not hide.** A private session on a subnet is -visible to everybody on that subnet and joinable by nobody without the key. A -browser shows it as locked, which is deliberate - the person about to be given -the key has to be able to see it exists. - -### Across the internet - -```sh -cdn --store DIR --rendezvous-listen 47601 # somewhere already reachable -server --listen 0 --rendezvous ORIGIN:47601 --session-name "mine" -client --rendezvous ORIGIN:47601 --session-id 036e0c6d109c14220d0d7d2bdae7239a -``` - -The point introduces two peers and carries none of their traffic. Both sides -then poke each other directly until one gets through; the address that results -is on **the same socket the session uses**, because a router's NAT mapping -belongs to a port. - -The rendezvous point runs inside the content origin rather than as a fifth -program: it holds an id, an address and a timestamp, and it needs to be -somewhere an operator has already put on an address. - -**A private session is not listed at the point and cannot be.** The point holds -no key and must not - that would make every operator of one a holder of every -private session's secret. So reaching a private session needs its id, which the -host hands over along with the key. `server --advertise` prints both: - -``` -announcing session 036e0c6d109c14220d0d7d2bdae7239a (private) on the local subnet -``` - -**There is no relay.** When both routers refuse, the attempt fails and says so: - -``` -could not reach session 036e... through ORIGIN:47601 -``` - -That is an honest answer. A hidden fallback would make "peer-to-peer" mean two -different things depending on the day, and a relay is bandwidth somebody pays -for. - -### Distribution streams - -The same three reaches, offered by a content origin instead of a game server: - -```sh -cdn --store DIR --advertise # LAN -cdn --store DIR --advertise --stream-key SECRET # private, key required -cdn --store DIR --rendezvous POINT:47601 # listed for anyone off-subnet -cdn --store DIR --rendezvous-listen 47601 # be the meeting place -``` - -A stream is not a second kind of origin - the same six routes are served to -everybody. What a stream decides is how a client *finds* it and whether it was -invited, and `--stream-key` gates discovery rather than delivery: a grant is -still what admits a fetch. - -### What a part collides as - -A part is drawn at its `Size` and collides at its `CollisionShape`, and nothing -keeps those the same. **View → Collider Outlines** draws what the solver -actually has: a colour per face, so a hull reads as an object rather than as a -tangle of lines. - -**View → Collider Shape** picks which of the three a part has: - -| Mode | Draws | -|---|---| -| As chosen | What `CollisionShape` selects - what actually collides | -| Precise | The baked triangle soup, for anything that has one | -| Hull | The baked convex hull, for anything that has one | -| Bounds | The part's own box - what a shape falls back to when its name does not resolve | - -The two that are *not* selected are usually what answers "why does this collide -like that": a rock whose hull swallows the gap it should have, a chunk whose -bound is a box the size of the whole tile. A mode with nothing baked to show -falls back to drawing what the collider actually is, because the absence is the -answer for a part somebody expected a hull on. - -**Fill faces** fills them as well as outlining them - filled is how a shape reads -as a solid, outlined is how two overlapping ones stay separable. **Hide -textures** draws the world flat while the view is open, because a wireframe over -a textured scene is a wireframe over a photograph. - -### Geometry a script builds, and standing on it - -An `EditableMesh` is drawn *and* collides. `MeshPart.MeshId` names it for the -renderer and `CollisionGeometry` names it for the solver: - -```lua -local mesh = Instance.new("EditableMesh") --- ... AddVertex / AddTriangle ... - -local part = Instance.new("MeshPart") -part.MeshId = mesh.ContentId -part.Parent = workspace -part.CollisionShape = Enum.ShapeKind.Mesh -- or Hull -part.CollisionGeometry = mesh.ContentId -``` - -**Build the vertices around the mesh's own origin.** A baked shape is used in -the part's object space and is not scaled to it, so a mesh written in world -coordinates draws correctly - `ToGpu` fits it to the part - and puts its -collider wherever the part is not. - -**The shape arrives on the next tick.** `physics::RegisterPhysicsSystems` bakes -it in `PreSimulation` for every host that solves, and a collider naming a shape -that has not resolved yet collides as the part's own bound. For a terrain chunk -that bound is a solid box the height of the whole tile, so a streamer should -leave a new chunk `CanCollide = false` for one frame - `Terrain.luau` does, and -says why where it does it. - -**The soup is baked always and the hull only when a collider asks for one.** -Measured on a 4,225-point chunk the soup costs 1.3 ms and quickhull costs 7.3, -and a heightfield's hull is a dome over its summit. Switching a part to `Hull` -later still gets one, on the next tick. - -Shapes are forgotten when their mesh is destroyed, so a world that streams a -mesh per chunk does not accumulate one per chunk ever built. - -### In the editor - -**View → Team Create.** The editor announces itself at the same layer, sees the -other editors on the subnet or through a point, and hands over a session id and -a key to invite somebody with. - -**Edits replicate.** Host a session, and every editor that joins sees what you -do - a create, a delete, a reparent, a property write. A recording crosses as -one message, so "set these forty parts to neon" arrives whole or not at all. - -The panel lists the editors it can see; **Join** connects to one, and the row -underneath reports what has crossed. - -**Undo does not replicate, and that is deliberate.** Ctrl+Z reverses what *you* -did, never what somebody else did. An editor that undid a colleague's change -because you pressed it once too often would be an editor nobody could work in. - -**Two editors on one model take turns, and neither loses their work.** Before a -waypoint goes out, its author asks the host for the subtree it touches. If -nobody has it, the host hands it over and the edit goes; if somebody does, the -request waits in line. When the person in front is done the next one goes, and -their change lands *on top of* the first. - -**Nobody is ever refused for being second.** That is the whole reason there is -a queue rather than a rejection: somebody asking for a model in use is not -doing anything wrong, they are second, and second still gets a turn. - -**The person does not wait.** Their edit is applied at their own machine the -moment they make it; what waits for the turn is the *message*. A queued editor -carries on working and their waypoints go out in the order they made them. - -If somebody else's edit is ordered ahead of one you are still waiting to send, -your machine re-applies yours on top when theirs arrives - so every editor ends -on the same answer, and it is the host's order that decides which. - -A turn covers a subtree, not one instance: a turn over a model that let -somebody else edit its parts would order nothing, because moving a model moves -its children. Two editors in different corners never wait for each other. - -**A grant has a short guard**, so an editor that is handed a subtree and then -dies costs the next person a pause rather than the session. It is a bound on -one protocol step, not a lease on editing. - -**The ordering is at the host**, which is already the thing that decides order. -The panel shows whose turn it is and how many edits are waiting; a guest running -a modified build cannot jump the queue. - -**Everybody has to have the project open already.** A join carries edits, not -the document - a scene the peer does not have is an edit that is dropped and -counted. Open the same `.agame` on both machines first. - -### ChangeHistoryService - -A plugin tells the editor what one undo should reverse, exactly as it does in -Roblox: - -```lua -local ChangeHistoryService = game:GetService("ChangeHistoryService") - -local recording = ChangeHistoryService:TryBeginRecording("Set selection to neon") -if not recording then - return -- a recording was already in progress -end - -for _, part in Selection:Get() do - part.Material = "Neon" -end - -ChangeHistoryService:FinishRecording(recording, Enum.FinishRecordingOperation.Commit) -``` - -Forty property writes, one press of Ctrl+Z. That grouping is the reason the -service exists and is also the unit a shared document will travel in - a peer -that applied half of a group would show a state the author never saw. - -`Commit` keeps the recording as its own step, `Cancel` reverts it and puts -nothing on the redo stack, and `Append` folds it into the step before. - -| Method | | -|---|---| -| `TryBeginRecording(name, displayName?)` | the identifier, or nil when one is already open | -| `FinishRecording(id, operation, finalOptions?)` | `Commit`, `Cancel` or `Append` | -| `IsRecordingInProgress(id?)` | | -| `GetCanUndo()` / `GetCanRedo()` | | -| `Undo()` / `Redo()` | raises when there is nothing | -| `SetWaypoint(name)` | merges everything since the last cut | -| `ResetWaypoints()` / `SetEnabled(state)` | | -| `OnUndo(f)` · `OnRedo(f)` · `OnRecordingStarted(f)` · `OnRecordingFinished(f)` | | - -**Two differences from Roblox, and both are the seam rather than a choice.** - -`GetCanUndo` and `GetCanRedo` return a table, because a host call answers one -value - `local can, name = table.unpack(ChangeHistoryService:GetCanUndo())`. - -The events are calls that take a handler rather than signals with `:Connect`, -because the host seam has no `RBXScriptSignal` type and inventing one for four -events would be a second way to hear about something. - -**One recording at a time for the editor, not per plugin.** This service is the -editor's single history; two plugins recording into one undo stack would produce -a step neither of them described. - -**`SetWaypoint` merges and the editor never calls it.** Roblox's rule is that the -changes between two waypoints are one undo; this log's default is one edit per -step, so a cut merges everything since the previous one. A plugin that writes -forty properties and then calls it gets one step. The editor's own edits are -unaffected, which is the point rather than an oversight. - ---- - -# The content origin - -Serves a game's content out of a directory. Two deployments, one program: beside -the game for single-player, LAN and split-screen, or on its own for a large -content collection. Nothing inside the program tells them apart - the difference -is which directory it mounts and who can reach it. - -Publishing and serving are **two invocations, and the split is deliberate**: the -signing key belongs to whoever publishes the game and the origin holds none, -which is what makes it safe to deploy on hardware nobody here owns. - -## Quick CDN setup - -Build with `just cdn`. Put baked assets in `content/`, choose different -64-character hex signing and grant secrets, then publish: - -```sh -SIGNING_KEY=YOUR_64_HEX_SIGNING_SECRET -./.cache/build/dev/cdn/cdn \ - --publish ./content --store ./store --signing-key "$SIGNING_KEY" -``` - -Save the `publisher key` printed by the command. To use the folder directly: - -```sh -PUBLISHER_KEY=THE_KEY_PRINTED_BY_PUBLISH -just run --cdn dir:./store --publisher-key "$PUBLISHER_KEY" -``` - -To serve the same store over HTTP: - -```sh -GRANT_KEY=YOUR_DIFFERENT_64_HEX_GRANT_SECRET -./.cache/build/dev/cdn/cdn \ - --store ./store --grant-key "$GRANT_KEY" --port 9080 -``` - -`curl http://127.0.0.1:9080/health` should answer `ok`. - -### Use a custom CDN from a game server - -In another terminal, point the game server at an IP address its clients can -reach: - -```sh -GRANT_KEY=THE_SAME_64_HEX_GRANT_SECRET -PUBLISHER_KEY=THE_KEY_PRINTED_BY_PUBLISH -CDN_HOST=192.168.1.20 -just host --game My.agame --listen 9000 \ - --content-grant-key "$GRANT_KEY" \ - --flag server.content-mode=redirect \ - --flag server.content-sources="$CDN_HOST:9080" \ - --flag server.content-publisher-key="$PUBLISHER_KEY" -``` - -The CDN and game server must use the same grant key. - -### Add the store to Studio - -Open **Edit > Preferences > Content**: - -1. Choose **Add local store**. -2. Set **Use** to `read` and **Location** to the published `store/` directory. -3. Paste the publisher key under **Trust**. - -Changes save immediately. For a remote origin, choose **Add origin** and enter -its `HOST:PORT`. Protected remote downloads still need a grant from a game -server, so use the local store in Studio for direct authoring and preview. - -### Connect a client - -Normally the server supplies the CDN address, session grant and publisher key: - -```sh -just run --connect GAME_SERVER:9000 -``` - -To pin your own CDN and key, pass them explicitly. The client tries this source -before any source announced by the server and refuses a different publisher: - -```sh -PUBLISHER_KEY=THE_KEY_PRINTED_BY_PUBLISH -CDN_HOST=192.168.1.20 -just run --connect GAME_SERVER:9000 \ - --cdn "$CDN_HOST:9080" --publisher-key "$PUBLISHER_KEY" -``` - -That HTTP CDN must accept the grant issued by the game server. A `dir:` source -needs no grant. - -The detailed publishing, serving and troubleshooting reference follows. - -### Publish a directory of files - -```sh -./.cache/build/dev/cdn/cdn \ - --publish ./content \ - --store ./store \ - --signing-key $(printf '7a%.0s' {1..32}) -``` - -It walks the directory, cuts every file into content-defined chunks, writes them -into the store, classifies each asset from its extension, groups them, trains a -compression dictionary if there is enough content to learn from, and signs the -manifest root. It prints the root and **the publisher key**, which is what a -client has to be told: - -``` -[info] cdn: published 5 assets in 1 bundles - 717432 bytes of content in 717432 bytes of chunks -[info] cdn: manifest root 8a1c34d1d3f8... -[info] cdn: publisher key ba42458e83ba... -``` - -Republishing is cheap: unchanged content is already in the store and every write -of it is a no-op. - -### Serve one - -```sh -just serve --store ./store # serve a prepared content store -./.cache/build/dev/cdn/cdn --store ./store --grant-key HEX --port 9080 -``` - -```sh -curl http://127.0.0.1:9080/health # ok 5 assets 1 bundles -curl -o manifest.acm http://127.0.0.1:9080/manifest -curl -o group.zst -H "x-atomic-grant: HEX" http://127.0.0.1:9080/bundle/ -``` - -### Options - -``` ---store DIR The content store to serve or publish into ---publish DIR Publish this directory of files into the store, then exit ---signing-key HEX 64 hex characters - the Ed25519 seed to sign a publish with ---grant-key HEX 64 hex characters - the secret shared with the server ---port N Port to listen on (default 9080; 0 binds an ephemeral one) ---ingest-key SECRET Accept uploads at /ingest from whoever sends this ---inbox DIR Where uploads land (default: the raw/ beside a processed store) ---upstream NAME=HOST:PORT An origin to forward a miss to. Repeatable ---allow-upstream Forward a miss. Off unless asked for ---no-local-first Always ask an upstream - a pure proxy ---no-cache-upstream Do not keep what an upstream returned ---compression-level N Zstd level groups are prepared at (default 9) ---cache-bytes N What the prepared-group cache may hold ---frames N Serve this many pumps and exit. For a smoke test ---gui Watch it serve in the terminal ---verbose Log at trace level -``` - -### Watching it serve - -```sh -./.cache/build/dev/cdn/cdn --store ./store --grant-key HEX --port 9080 --gui -``` - -A scrolling terminal view of the origin, on the alternate screen, redrawn four -times a second: - -``` -atomic - content origin · 0.0.0.0:9080 - -NETWORK - now out 31.8 KB/s in 4.9 KB/s - last hour out 42.5 KB in 6.6 KB (60 minutes, the newest partial) - since start out 42.5 KB in 6.6 KB - out ···························································█ peak 42.5 KB/min - in ···························································█ peak 6.6 KB/min - -REQUESTS - bundles 0 · manifests 40 · dictionaries 0 · health 40 - refused 0 · missing 0 · rejected 0 - group payload served 0 B - prepared cache 0 groups · 0 B of 256.0 MB - -CONTENT - 4 assets in 1 bundles - 752.0 KB of content, uncompressed - 752.0 KB on disk in 12 chunks - -BY KIND … LARGEST 5 … ASSETS (4, largest first) … -``` - -| Key | Does | -|---|---| -| `↑` `↓` or `k` `j` | one line | -| `PgUp` `PgDn`, or `b` and space | one screen | -| `g` `G` | top, bottom | -| `q` or Ctrl-C | leave, restoring the terminal | - -**Out and in are measured at the socket**, so they count headers, health checks -and a request that never finished arriving - which is what an operator watching -bandwidth wants. `group payload served` is the other question, what delivery -actually cost, and one number could not answer both. - -**The log level is raised to errors while it is up**, because the log and the -dashboard share a screen and the log would win a line at a time. It goes back on -the way out, and the summary still prints. - -`--gui` on something that is not a terminal - a pipe, a log file, a service -manager - warns and serves without it. Escape sequences written into a log file -are a log nobody can read. - -`--grant-key` is **required to serve**, and it is not a convenience to remove. -An origin that admitted everyone would be deciding who may have what, which is -the server's job. - -The three deployments are flag combinations rather than three programs: - -| Deployment | Flags | -|---|---| -| Local store - serve your own disk | the default | -| Cache server - local first, forward a miss, keep it | `--allow-upstream --upstream a=host:port` | -| Pure proxy - always ask, keep nothing | `--allow-upstream --no-local-first --no-cache-upstream` | - -### Attached to a server instead - -A server can run one in-process, which is the self-hosted case: - -```sh -just host --content-store ./store --content-grant-key HEX --content-port 9080 -``` - -That store is also what a `relay` server relays out of and what a `redirect` -server names, unless `server.content-sources` says otherwise - see -[Where a client's content comes from](#where-a-clients-content-comes-from-v016). - -The grant is then issued and verified across a function call, and **both halves -are real** - the MAC is computed and checked. A path skipped in the -configuration people develop against is a path that breaks the first time -somebody ships the other one. - -### Fetching it - -```sh -just run --cdn 127.0.0.1:9080 --publisher-key HEX --content-cache ./cache -just run --cdn dir:./store --publisher-key HEX # a local store, no wire -``` - -`--cdn` is repeatable and **the order is the priority**: the first source that -answers wins, and one that fails is passed over. That is how "local cache first, -otherwise ask the origin" is expressed - there is no policy flag, because the -order of the list *is* the policy. The studio edits the same list under -Preferences → Content. - -Without `--publisher-key` nothing is fetched, and that is deliberate: a client -that accepted an unsigned manifest would have no trust boundary at all. - ---- - -# Audio - -```sh -just run --sound ./assets/tone.wav # plays it on a loop -just run --sound ./assets/track.mp3 # the same, and the decoder is picked - # from the bytes rather than the name -``` - -**Two formats, and the second arrived with a licence rather than with a change -of mind.** RIFF/WAV - 8, 16 and 24-bit integer PCM and 32-bit float - and MPEG -Layer I, II and III, behind minimp3, which is CC0. `.ogg` and `.flac` are still -classified by the content manifest and **not decoded**: each is a vendored codec -and a licence decision, and listing an extension without a decoder behind it -would be worse than the honest gap. - -### A sound in a world - -`Instance.new("Sound")` is a class like any other, and **its parent decides how -it is heard**: - -| Parented to | Heard | -|---|---| -| `workspace`, or any service | everywhere, at one level - music | -| a part, or anything with a place in the world | from that part, falling off between `RollOffMinDistance` and `RollOffMaxDistance` | - -```lua -local music = Instance.new("Sound") -music.SoundId = "audio/lilium-lainu.mp3" -- the manifest's name, extension included -music.Looped = true -music.Volume = 0.6 -music.Parent = workspace -music.Playing = true -``` - -`SoundId` names a **published asset**, exactly as `MeshId` names a mesh - so the -client plays it when it is pointed at a store that has it and is silent when it -is not. Setting `Playing` before the content has streamed is fine: the row keeps -asking and it starts on the frame the asset lands. - -**`Playing` is a property rather than a `Play()` method**, and that is a fact -about the script binding rather than about audio. Methods live on one metatable -shared by every instance, so a `Play` there would be a method on every `Part` in -the world. Roblox has this property too and `sound.Playing = true` is what it -means. - -There is a working one in `mono.engine/examples/assets/scripts/Terrain.luau`: - -```sh -cdn --publish ./content --store ./store --signing-key HEX # content/audio/*.mp3 -just run --script .cache/build/dev/assets/examples/scripts/Terrain.luau \ - --cdn dir:./store --publisher-key PUBLIC -``` - -``` -[info] content: audio/lilium-lainu.mp3 decoded (342.3s, 48000 Hz, 2 channel(s)) -[info] content: 0 mesh(es), 0 texture(s) and 1 sound(s) registered -``` - -Decoding and resampling happen **once, at load**, never on the device thread - -which is why the line above reports the device's rate rather than the file's. - -**A machine with no audio output is not an error.** The client says so and runs -quietly: - -``` -[info] audio: no output available (No available audio device) - running silently -[warning] audio: 'tone.wav' decoded (1.00s) but there is no output on this machine -``` - -A file that cannot be read, or is not audio this engine decodes, **is** an error -and stops start-up - and it is reported whether or not there is a device, so a -typo'd path is visible on a headless box too. - -### What it is doing underneath - -The pipeline is a node graph: `Player` inputs, `Fader`, `Emitter` and `Bus` -processors, one `Output`. A tick never touches it - it posts a command carrying -a **sample deadline**, and the mixer splits its block at every deadline inside -it. That is the one thing here that is a requirement rather than a refinement: a -game ticks at frame rate and audio runs at sample rate, so a sound applied at -the top of whichever block comes next is audibly early or late. - -`mono.engine/audio/AGENTS.md` carries the rest. - -A store that is missing, or that holds no manifest, is refused at start-up with -exit code 1, rather than being accepted and failing one request at a time. - -What exists is `cdn::ContentRoot` - the boundary between a content name and the -filesystem. It refuses traversal by default, and both of its checks are -load-bearing: components are checked before the disk is touched, which catches -`..` and absolute names but cannot see a symlink, and the resolved path is then -checked for containment, which catches the symlink. A symlink that stays inside -the root is served, because an atomically swapped `current` is the deployment -pattern this is for. - -Content addressing, the hierarchical hash, grants, and streaming groups so a -game builds progressively are built. What is still open at v0.9 is `control/` -(the upload API and dashboard, in -TypeScript), invalidation, and chunk-level verification of what an upstream -returned - today that is a length check against the signed manifest, which is -real and is not the whole of one. - -### Proving it needs no graphics stack - -```sh -just check-cdn-is-bare -``` - -Configures with no client and no server, builds, and fails if the staged `cdn/` -directory has grown a `shaders/` folder or if another program was built into a -cdn-only preset. The tier rule is what actually enforces this - `mono.cdn` is -`shared` tier, and a `shared` target may link only `shared` - so a presentation -module reaching this link line fails the configure with the edge named. The -recipe is the version of that anybody can see without a graph query. - ---- - -# The tools - -## The test runner - -```sh -just test # only what your change affected -just test-all # everything -just test --gpu-tests # everything, including headless GPU cases -just test-list # what it would run, and why -./.cache/build/dev/tools/testrunner --help -``` - -GPU cases carry the `[gpu]` tag and are excluded from ordinary test runs. Pass -`--gpu-tests` when a Vulkan device is available. This forces every suite to run, -including the GPU cases, with `Renderer::Initialise(nullptr)`: a real device, -shader compiler, pipelines, compute queues, offscreen targets, captures and -readbacks, but no window or swapchain. A missing or broken device fails the run -instead of silently skipping coverage. - -For the render module alone, `just render-check` builds and runs the existing -Catch suite's GPU cases. `just render-check '[fixture]'` selects the analytic -projection/depth fixtures; other Catch filters work in the same argument. -The optional second argument is the backend, currently `vulkan`. Requesting an -unimplemented backend fails explicitly. A missing device fails the tests. - -Fixtures compare named graph images against independent CPU pinhole rays, with -odd/non-square targets, padded transfer rows, depth overlap, clipping, edits and -camera motion. Failure bundles go beside the test binary under -`render-failures///`: inputs and graph, device/driver, shader -hashes, exact expected/actual bytes, preview images and a mismatch mask. Float -depth previews share the reference depth scale; raw files preserve precision. -The recipe records the source revision, including a dirty marker. - -`just render-preparation-bench 5` measures whole camera batches signing unchanged -world rows and one-row edits in the optimized `bench` preset. It is a CPU -preparation baseline, not GPU or full-frame timing. Cache/baseline paths stay -under `.cache/build/bench`; results print to the terminal. - -`just shader-fuzz 10000` builds the real cooked shader parser with Clang -libFuzzer, AddressSanitizer and UndefinedBehaviorSanitizer, then runs a bounded -mutation campaign from three generated transport seeds. It checks transactional -refusal and canonical round trips. A seed is transport-valid metadata and does -not certify an executable shader. This headless target creates no device. -Pass a different Clang C++ executable as the second argument if needed, with -`CC` naming its matching C compiler. The dedicated build, corpus and crash -artifacts stay under `.cache/build/shader-fuzz/`. `-max_len=65536` bounds this -routine campaign; the asset suite separately checks the 64 MiB container cap. - -`just presentation-fuzz 10000` instruments the actual cross-world presentation -message parser with the same sanitizers. It checks canonical message round trips -and transactional refusal of malformed envelopes. It shares the Clang build -tree above, with separate `presentation-corpus` and `presentation-artifacts` -directories under `fuzz/`. Run the two fuzz recipes sequentially because both -configure that build tree. This campaign uses the same 64 KiB mutation bound; -the world suite separately checks maximum payload sizes and queue pressure. - -``` ---build DIR A configured build directory ---cache PATH Cache file (default .cache/smart-tests.txt) ---report DIR Where test-output.md/.html go (default .cache) ---no-report Write no documents ---all Run every suite, cache or not ---gpu-tests Run every suite, including headless GPU cases ---list List suites and signatures, run nothing ---verbose Name every skipped suite ---jobs N Suites to run at once (default 2; 1 is one after another) -``` - -**Suites run beside each other, and the default is two.** The slowest suites are -the ones that wait: `server.replication` is 35 seconds of a 168-second run and -`server.hostmode` another 12, and nearly all of both is a client ticking in real -time while a spawned server process gets somewhere. That wait cannot be -shortened without breaking what it waits for, and a sleeping suite does not need -a core - so the saving is running them alongside each other. - -Measured on this machine, 24 threads: - -| `--jobs` | Wall clock | Stability | -|---|---|---| -| 1 | 2 min 54 s | the old behaviour | -| 2 | 1 min 36 s | three clean runs | -| 4 | 1 min 11 s | `server.replication` red once in three | - -Two is the default because it is the fastest setting that was not observed to -flake: loading the machine loads the server the tests are waiting for, and a -runner that goes red under its own concurrency is worse than a slow one. Results -are printed in list order rather than completion order, so a run can still be -diffed against another. - -It prints what it skipped, and warns when it had to narrow - no header closure -for a suite, an unknown `TEST_DEPENDS`, a dependency cycle. Those warnings mean -the cascade is covering less than it claims to, so do not ignore them. - -To force a full re-run, either pass `--all` or delete `.cache/smart-tests.txt`. -That file is text: one tab-separated line per suite, so you can also delete a -single line to re-run one thing. - -`just preset=server test` runs the server preset's suites with the server -preset's runner - the preset override reaches `--build` too, so the binaries and -the build directory cannot come from different presets. - -## The report - -Every run writes `.cache/test-output.md` and `.cache/test-output.html`, and -prints both paths. `--list` writes nothing, because it ran nothing. - -Sections are the suite identifiers themselves: `engine.core.arguments` sits -under `engine`, then under `engine.core`, and is a row of its own. There is no -second taxonomy to keep in step with the first. - -Both documents cover **every** suite, not only the ones this invocation ran. A -suite the cascade skipped shows its last known numbers and says `pass (cached)` -in its result column - a green row you cannot tell from a row nothing -re-checked is a green row that lies by omission. The counts and durations behind -those rows live in `smart-tests.txt`, which is why it is at `v2`; a `v1` cache is -discarded on sight rather than reported as a tree of suites holding no tests and -costing no time. - -The numbers come from the test binaries. `mono.build/testmain` registers a -Catch2 reporter named `mono` that writes one tab-separated line per test case, -and the runner asks for it alongside the console reporter - so the output you -read when something goes red is unchanged, and the report is a record of the run -rather than a parse of its console text. You can ask a binary for it directly: - -```sh -./.cache/build/dev/tests/test_core --reporter "mono::out=-" -``` - -Neither document carries a timestamp. Two runs that learned the same thing -produce the same bytes, so a diff shows what moved rather than that it was -written again. - -`ctest` writes no report. It never consults the cache either - see below. - -### Timings - -The runner prints what each suite cost as it goes, and both documents carry the -same numbers - `Time` and `Slowest case` columns in the Markdown tables, and a -flamegraph in the HTML. - -**Two clocks, measuring two different things.** A suite is timed by the runner, -from the outside, so its number includes starting the process and running its -static initialisers. A case is timed by the reporter, from the inside. A suite -is therefore always wider than its cases add up to, and that gap is real: it is -the fixed price of a suite existing, paid once per suite per run. - -That gap is the first thing the report is good for. If `engine.core.arguments` -costs 300 ms and its slowest case costs 29 µs, none of that 300 ms is a test. - -`Time` beside `Slowest case` is the other diagnosis. A slow suite whose slowest -case is most of it is one pathological test; a slow suite whose slowest case is a -fraction of it is a lot of ordinary ones. Those want different fixes. - -### The flamegraph - -`test-output.html` opens with one. Width is wall-clock, depth is the identifier -one component at a time - everything, then `engine`, then `engine.core`, then the -suite, then its cases. Hover a box for its name and what it cost. Widest first, -so what is worth looking at is where you are already looking. - -It is nested `div`s with percentage widths and no script, so it stays -proportional when you resize the window and renders on a machine with no network. - -A suite the cascade skipped is a **leaf** - washed out, with no cases under it. -`smart-tests.txt` is one line per suite, so it keeps a suite's total and not its -breakdown; one line per *case* would be a different file with a different -contract. Run `just test-all` for a graph that goes all the way down. - -## Everything, always - -```sh -cd .cache/build/dev && ctest --output-on-failure -ctest -N # list without running -ctest -R ecs # only suites matching a pattern -``` - -`ctest` never consults the cache. Use it before a pull request - there is no CI -to use it in, and [the `ci` preset](#the-ci-preset-and-the-hook-that-runs-it) -says why; use `just test` in the inner loop. - -## One suite, directly - -Test binaries are ordinary Catch2 executables: - -```sh -./.cache/build/dev/tests/test_ecs # all of it -./.cache/build/dev/tests/test_ecs "a component round-trips" -./.cache/build/dev/tests/test_ecs "[scheduler]" # by tag -./.cache/build/dev/tests/test_ecs -# "[#Store]" # by source file -./.cache/build/dev/tests/test_ecs --help # Catch2's own options -``` - -`-# "[#File]"` is how the runner re-runs exactly one suite, since a suite is one -file. - -They also answer one option Catch2 does not know about: - -```sh -./.cache/build/dev/tests/test_ecs --mono-suites -``` - -which prints `id source dependencies` for each suite it contains. -That listing is how the runner discovers what exists, rather than scanning -sources and hoping a regex holds. - -## The architecture check - -```sh -just test-architecture -``` - -It needs a *configure*, not a build - its input is the `target-graph.json` that -CMake emits. Directly: - -```sh -cmake -DGRAPH=.cache/build/dev/target-graph.json \ - -DEXPECTED=mono.tools/architecture/expected_graph.json \ - -P mono.tools/architecture/CheckTargetGraph.cmake -``` - -This is not what enforces the tier rule - `mono_check_all_tiers` does that at -configure time and fails the build with the offending edge named. This checks -the graph against the checked-in expectation, so that an architectural change -shows up as a diff somebody reviews. - -## The source-text architecture rules - -```sh -just source-check -``` - -The other half of `test-architecture`. That one reads CMake's output, so it can -see the module set, the tiers, the link sets and the layer heights; it cannot -see a member's type, a header's includers, or an argument reaching a writer. -This reads first-party C++ as text and checks the four rules -`docs/CODE_ARCH.md` §11 listed as convention until v0.19: a private copy of data -the ECS owns, a pointer inside a type marked as crossing a world boundary, a -`core::Name` serialized as its `Id()`, and a header under `include/` that -nothing outside its module includes. - -It needs a *build* of one target and nothing else - the tool reads sources, not -objects. Directly, and with `--rule` for one rule at a time: - -```sh -./.cache/build/dev/tools/sourcecheck . # every rule -./.cache/build/dev/tools/sourcecheck . --rule name-id # one of them -./.cache/build/dev/tools/sourcecheck . --verbose # waived findings too -``` - -Three of the four gate. `public-header` reports and never fails: an unwired -subsystem is not dead code, and it currently names 87 of 393 public headers, -twenty-five of them `mono.studio`'s. - -A rule is switched off at one declaration with a comment above it, reason -included - a waiver with nothing after the colon is reported rather than -honoured: - -```cpp -// arch-waiver ecs-copy: composed from N views for one frame out. No world -// holds this camera, because it is not any world's camera. -engine::scene::Camera ComposedCamera; -``` - -`just source-check` runs the fixture trees under -`mono.tools/sourcecheck/tests/fixtures/` before it runs the repository, because -a scanner that read nothing would report success over both. - -## The shader check - -```sh -just shader-check -``` - -Every `.spv` the build produced, against the resource contract -`SDL_CreateGPUShader` documents: one entry point named what the renderer asks -for, at the stage the filename claims; every resource carrying an explicit -`layout(set = ..., binding = ...)`; every resource in the descriptor set SDL -names for its stage; bindings contiguous within a set; and no SPIR-V capability -outside an allowlist of what MSL can express. - -It also reads the translation back. The build writes an `.msl` beside every -`.spv` - `mono.tools/shadercross` runs `Engine::msl` over each one - and this -holds each translation to the module it came from: one entry point, named -`main0` because MSL reserves `main`, qualified for the right stage; the file -structurally well-formed; and every `[[texture]]`, `[[buffer]]` and -`[[sampler]]` index the one SDL's documented order derives. A `.spv` with no -`.msl` beside it is a failure rather than a skip. - -Directly, and without `--quiet`, for the per-shader table - including the -`[[texture(n)]]` or `[[buffer(n)]]` each resource lands on: - -```sh -./.cache/build/dev/tools/shadercheck .cache/build/dev/shaderstage -``` - -One shader by hand, if you want to read what a translation looks like: - -```sh -./.cache/build/dev/tools/shadercross \ - .cache/build/dev/shaderstage/resources/opaque.frag.spv -o /tmp/opaque.frag.msl -``` - -**It says nothing about a Metal device.** There is no Metal compiler here, so -"the MSL is valid" means balanced, prefaced and bound where SDL will look - a -type error inside a function body passes. What it is for is the half of -`docs/DEFERRED.md` D00001 that a machine with no Mac can answer, and that half -is now larger than it was: MSL, DXIL and DXBC all derive their bindings from -those descriptor sets, and the MSL derived from them is on disk to be read. A -`server` or `cdn` preset compiles no shader and the recipe says it skipped -rather than passing quietly. - -## The stress test *(v0.16)* - -Two hundred real clients against one server, and a flamegraph of what the server -spent the tick on. - -```sh -just preset=release stress # 200 clients, 45 seconds -just preset=release stress iter1 200 45 # the next capture, under another name -just preset=release stress quick 50 20 45200 # fewer clients, a different port -``` - -**Run it on `release` or `bench`.** First-party code is `-O0` under every other -preset, so a tick cost measured there is a number about the compiler. The recipe -does not force the preset, for the reason none of them do: the override goes -before the recipe name and applies to everything derived from it. - -It is deliberately not part of `just check`. It takes a minute, its numbers -depend on what else the machine is doing, and a gate that fails because somebody -started a build is a gate people learn to ignore. - -### What it runs - -`mono.tools/loadtest` opens N genuine sessions in **one process** - a UDP socket -each, a real X25519 handshake, a real cookie challenge, a real admission, a -sealed stream and an `ecs::Store` replica the snapshot and every delta are -applied into. It sends a move input every tick once the server has given that -client a character. - -One process rather than N, because `client --headless` still builds a GPU device -and two hundred of those measure the driver rather than the server. The harness -links no `render`, `input`, `audio`, `ui` or `client` - see -`mono.tools/loadtest/CMakeLists.txt`. - -```sh -./.cache/build/release/tools/loadtest --help -./.cache/build/release/tools/loadtest --port 45100 --clients 200 --seconds 45 -``` - -The server it points at is an ordinary `server` with three flags that exist for -this: - -```sh -server --game .cache/build/release/assets/examples/scripts/Stress.luau \ - --listen 45100 --max-clients 216 --profile-out run.folded -``` - -- `--max-clients N` raises `replication::ListenerSettings::MaximumClients`, which - is 64 by default. -- `--profile-out PATH` folds the whole run's frame graph into a `.folded` file. - It turns frame collection on with it, so it is a measurement rather than - something to leave on in a deployment. -- `Stress.luau` is a floor, one spawn and `Players.MaxPlayers = 512` - bare on - purpose, so what is measured is replication rather than scenery. - -### Reading the graphs - -Artefacts land in `.cache/stress/`: - -| File | What it is | -|---|---| -| `