Skip to content

Official Codebase of 3DCodeVerse

Python

graphics lab + docs: a dev lab per effect module, the library's docs, D97

gaoypengdc50bee97cfd
diff --git a/harness/README.md b/harness/README.md
index 7e73b857..82a48001 100644
--- a/harness/README.md
+++ b/harness/README.md
@@ -94,3 +94,6 @@ Docs: `docs/INSTALL.md` (install / prerequisites / doctor troubleshooting) ·
`docs/ARCHITECTURE.md` (design + what a run does) · `docs/INTERFACES.md`
(signatures) · `docs/RUNBOOK.md` (operate / extend) · `docs/DECISIONS.md` (ADRs) ·
`eval/docs/EVAL.md` (evaluation protocol + judge calibration) · `CLAUDE.md` (working rules).
+
+Graphics library: [integration and scope](docs/GRAPHICS_LIBRARY.md) ·
+[executable Graphics Lab](examples/graphics_lab/README.md).
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 99898ab1..de1f3bf2 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -167,7 +167,8 @@ codeverse3d/
gate and eval all use; the pure replay helpers), rubrics.py + rubrics/*.yaml (defect checklists, the wire
schema, caps and scoring), prompt_builder.py (image prep, montages, the
judge messages), vlm_judge.py (+ the reference/likeness judges),
- pairwise.py. No Judge Protocol: a judge is
+ pairwise.py, cinematic.py (optional review of authored offline frames).
+ No Judge Protocol: a judge is
duck-typed `.judge(JudgeInput) -> Judgment`
reference.py reference GROUNDING — give the pipeline a picture of what it is building:
synthesis, THE plausibility gate that makes a synthesized
@@ -334,10 +335,10 @@ summary:
* **scene_threejs**: `src/scene.js` `createScene({THREE, renderer, loaders}) → {scene, cameras, update(t,dt)}`;
`src/env.js`, `src/zones/*.js`, `src/assets/*.js`, `src/shaders/*.js`; GLBs at
`public/assets/<name>.glb`. The harness assembles `scene.js` deterministically.
- Plus the harness-owned, read-only **effect library** `src/lib/*.js` — 44 modules
- (~24k lines; the starter's other `.js` files are the example scene), shipped into every
- workspace by BOTH skeleton paths and listed in `HARNESS_OWNED_SRC` so agent writes to it
- are reverted (D51). The want → call table the prompts carry is `prompts/scene_threejs/effects_catalog.md`.
+ Plus the harness-owned, read-only **effect library** `src/lib/*.js` (the starter's other
+ `.js` files are the example scene), shipped into every workspace by BOTH skeleton paths and
+ listed in `HARNESS_OWNED_SRC` so agent writes to it are reverted (D51, D97). The want → call
+ table the prompts carry is `prompts/scene_threejs/effects_catalog.md`.
* **glsl_shader**: `src/shader.frag` (+ optional `src/common.glsl`,
`src/buffer_a.frag` for feedback; the harness-owned, read-only `src/recipes.glsl`
is pasted above them when the track seeded recipes) — the agent never writes
diff --git a/harness/docs/DECISIONS.md b/harness/docs/DECISIONS.md
index a75c4eda..eed7390c 100644
--- a/harness/docs/DECISIONS.md
+++ b/harness/docs/DECISIONS.md
@@ -996,6 +996,22 @@ Pointers: EVAL, PAPER_WRITING = `eval/docs/*.md`; COST, RUNBOOK, ARCHITECTURE, I
`tests/scene_runtime` 25.6k → 6.0k lines — the effect library is one shared import/catalog check and
one grouped GPU compile plus its named-bug regressions (17 of 17 mutations still caught).
+* **D97 Natural-element effects, one ownership rule, and the graphics lab (2026-09-23).** Fourteen
+ modules join `starter/src/lib/` as source (D51): fire / firefield / smoke / cloudvolume (bounded ray
+ marches over baked 3D noise — prescribed transport, not simulation), ocean / stream / waterfall / ice,
+ meadow / tree / rock / sand / paving, and `lifecycle.js`: `snapshotResources` + `attachDisposal` are the
+ one rule every factory disposes by (construction-owned geometry, materials, instance buffers released
+ once; textures and caller additions borrowed). `shader.js` gained `clonePatchedMaterial`,
+ `withRendererState`, alpha/normal/transmission hooks and inverse-transpose normals; finish patches now
+ change roughness per pixel under their own mask, not the material's. Scenes may load
+ `src/shaders/*.{vert,frag,glsl}` as text (audited by `shader_report`). Named bugs: three r182 compiles
+ `PCFSoftShadowMap` as BASIC (the renderer uses `PCFShadowMap`); the census missed shader-instanced
+ geometry; GlHost doubled a relative out dir. Tests follow D96 (a BUILD row + a GPU group each). The
+ catalog and planner say the effects are zone code, never assets, with no limits stated (D93).
+ `judges/cinematic.review_frames` + `cinematic_v1` review offline stills and are wired into NO run path
+ (no track, CLI, select or eval calls them). `examples/graphics_lab/` is a dev lab (one scene per
+ module, captures tied to source hashes); its `output/` is ignored and none of its media is committed.
+
## Rejected / deferred
* A versioned `Spec`/`RunRecord`/`RunState` load-normaliser (rejected 2026-08-30: of the seven
diff --git a/harness/docs/GRAPHICS_LIBRARY.md b/harness/docs/GRAPHICS_LIBRARY.md
new file mode 100644
index 00000000..4924d748
--- /dev/null
+++ b/harness/docs/GRAPHICS_LIBRARY.md
@@ -0,0 +1,143 @@
+# Graphics libraries and the scene authoring surface
+
+The harness already supplied reusable graphics code before the natural-element
+extension. There are two distinct authoring paths:
+
+| Track | Agent-facing reusable code | Execution |
+| --- | --- | --- |
+| `scene` / `scene_threejs` | `src/lib/*.js`, copied from `codeverse3d/languages/scene_threejs/starter/src/lib/`; factories and shader patches indexed in `codeverse3d/prompts/scene_threejs/effects_catalog.md` | Three.js WebGL scene host, authored cameras, absolute-time scene update, shared post chain |
+| `graphics` / `glsl_shader` | Selected cookbook functions and dependencies seeded into harness-owned `src/recipes.glsl` by `tracks/graphics.py` | Fragment shader frames and motion probes through the graphics runtime |
+| `graphics` / `opengl_python` | Raw moderngl and GLSL with cookbook guidance | Python-driven OpenGL passes; no Three.js object library |
+
+The scene library is the right place for reusable objects that coexist in a
+Three.js world. Imports from the shipped tree are explicitly allowed under the
+raw-language contract. The harness freezes those files against agent edits;
+the agent composes them from its own scene, zone and environment files.
+The dedicated standalone asset-generation stage still permits only Three.js
+imports. Instantiate shipped effects in zone/environment code instead of planning
+duplicate flame, water-ribbon or grass-patch assets. The scene planner now states
+this distinction explicitly; the first live trials exposed that ambiguity.
+
+The initial audit found 44 scene library modules, including procedural
+materials, noise, shader composition, grass, reflective water, sky, weather,
+terrain, foliage, buildings and placement helpers. This shares its lineage
+with a separate reference project outside this repository.
+That reference has additional modules, but it is not a drop-in replacement:
+the harness has its own renderer, lifecycle and effect budget, and D74 records
+the deliberate removal of eight unused effects. Copying every reference
+module back would undo that decision.
+
+The first natural-element extension added six modules, expanding the original
+44-module library to 50:
+
+| Module | What it adds | Material limitation |
+| --- | --- | --- |
+| `fire.js` | Local volumetric flames, animated illumination, embers, wax candles with pools, drips and wicks | Transparent-volume ordering requires care; no combustion simulation |
+| `ocean.js` | A directional Gerstner spectrum, sampled height/normal, filtered reflection and crest foam | Reflection uses a mean plane; no breaking-wave fluid solver |
+| `stream.js` | A descending curved channel, refracted stone bed, flowing ripples, obstacle wakes and optional bank reflections | Opaque-scene screen-space refraction; approximate caustics and mean-grade reflection; no fluid/solid coupling |
+| `sand.js` | Seeded dunes, filtered wind ripples, grain detail and moving windborne grains | Dune shape is static; no granular erosion simulation |
+| `rock.js` | Closed fracture-plane rock geometry, strata, minerals, moisture and moss | Procedural geometry rather than scanned geological assets |
+| `meadow.js` | Multiple leaf growth forms, habitat/age variation, optional seed heads, coherent wind and thin-leaf lighting | Density and shadow resolution must suit the viewing distance |
+
+Every new factory returns a Three.js object with `userData.update(t, dt)` and
+`userData.dispose()`. `t` is absolute seconds; update each effect once from the
+zone or scene. Sampling APIs operate in the object's local coordinates. The
+factory owns its internal resources; externally attached props retain their
+own lifecycle. Individual module JSDoc specifies dimensions, options and limits.
+
+The extension reuses existing `noise.js`, `shader.js`, material and lighting
+helpers. The shared renderer owns tone mapping and postprocessing; examples
+do not replace the renderer or change its global settings. A separately
+verified Three r182 shadow-filter compatibility fix is recorded in D97.
+
+See [Graphics Lab](../examples/graphics_lab/README.md) for runnable studies,
+stills, deterministic H.264 capture, a live viewer and browser validation.
+The hand-composed studies and actual model-generated trials are kept separate,
+so a curated demonstration is never presented as an autonomous agent result.
+
+The second refinement replaces the stream's alpha overlay with Three's physical
+transmission path (IOR 1.333). `waterColor` now specifies volume absorption over
+`attenuationDistance` metres, rather than painted surface colour. Opaque objects
+under the water are refracted; transparent objects and offscreen geometry are
+outside that screen-space source. `reflectionSize: 0` is the default; a value of
+256–2048 adds one planar capture of the banks, and must not be combined with
+another water/Reflector capture. The built-in transmission pass has its own
+rendering cost even with bank reflections disabled.
+
+Graphics Lab's `compare.py` retains immutable baseline workspaces and replaces
+exactly one module per comparison. Its before/after manifest records source
+hashes, identical cameras and time, and real GPU metrics. Scene dressing in the
+main gallery is separate from that controlled library comparison.
+
+The subsequent full-library review is tracked in [the development record](GRAPHICS_ROADMAP.md).
+It includes explicit resource ownership, transformed normal/placement fixes,
+point-light shadow silhouettes, patch-preserving material clones and local
+physical surface response. Shader-material clones also retain borrowed texture
+samplers, including live render targets, and static batches retain source uniform
+controls. Added capabilities with inspected GPU compositions include
+structural trees, self-shadowed cloud volumes and closed fractured ice. `tree.js`
+provides connected oak/birch/willow and shrub architecture with individual leaves,
+wind and shadow deformation. Default trees are roughly one million triangles;
+use their leaf budget and actual census results for each composition. A bounded
+`leafSegments` option reduces distant leaf geometry while keeping the seeded
+placement, count, colour and woody structure unchanged. Species defaults retain
+the close-view silhouette; four segments suit unresolved background leaves. `cloudvolume.js`
+provides a bounded density field with internal sun attenuation, not terrain
+shadows or fluid dynamics. `ice.js` builds closed floes with real gaps, local
+surface queries and approximate face-dependent optical paths.
+
+`waterfall.js` adds a weir/free-fall sheet with conserved flow thickness,
+advected surface detail and existing impact spray. Its origin is receiving
+water level, lip at `[0,height,0]`, with flow toward +Z. The caller supplies
+the upstream surface, backing/cliff and pool. The CPU query and actual GPU
+position/thickness are checked independently. The composed stone/woodland weir
+study uses one 512-pixel downstream reflection capture.
+
+`paving.js` adds foreground cobbles and rectangular setts as closed bevelled
+geometry with recessed joints. Its exact local height query includes both stone
+tops and the joint bed, so props can be seated correctly. It uses two meshes and
+a bounded stone count; the material-only cobble preset remains useful at distance.
+This is procedural paving rather than photogrammetric stone.
+
+`smoke.js` adds `makeSmoke` and `makeSteam`: seeded, rising volume density with
+wind, expansion, dilution, Beer extinction and directional/point illumination.
+The emitter is at local y=0; density queries use local coordinates and optical
+extinction uses world metres, including nonuniform object scale. Both return a
+Mesh with absolute-time update and owned disposal. In ordinary depth mode smoke
+and cloud volumes test their first contributing density sample, so an opaque
+object behind visible density no longer incorrectly erases the entire volume.
+Neither volume integrates scene depth to truncate density at embedded opaque
+objects; logarithmic depth retains the proxy-box fallback. No collision solver,
+scene-shadow reception or shadow casting is implied. The smoke study includes
+tea and charcoal examples with captured source hashes and six-second films.
+
+The GLSL authoring surface also has executable SDF, volume-transport and direct
+GGX regressions. Three composed recipe studies and their ordered 144-frame
+films are built with `examples/graphics_lab/build_recipes.py --video`. These
+are authored examples, with source/recipe hashes, rather than model outputs.
+
+Standalone `.vert`, `.frag` and `.glsl` files also work inside a Three.js scene.
+Load their text using `THREE.FileLoader` and a module-relative `new URL(...)`
+inside async `createScene`; use the resulting strings in `ShaderMaterial` or
+`RawShaderMaterial`. JavaScript still owns object construction, uniforms and
+updates. The browser does not support a raw `.frag` ES module import or a bundler
+`?raw` suffix here. Arbitrary GLSL helper files must be loaded and joined explicitly;
+Three's `#include <chunk>` resolves its own shader chunks, not filesystem paths.
+See the [scene contract](../codeverse3d/prompts/scene_threejs/contract.md) for the
+loading pattern and GLSL ES conventions. Synchronous asset builders retain their
+existing contract; perform loading in the scene factory before returning.
+
+The source writer, snapshots and candidate promotion preserve these shader
+files. Shader preflight includes them in source reports and maps GPU compiler
+errors to their original file and line. Cross-file uniform declarations and
+bindings are checked after material assembly, avoiding JavaScript-only assumptions
+about standalone GLSL. Graphics Lab stages and hashes all three shader suffixes
+alongside scenes and library modules, including capture and transfer packages.
+Desktop OpenGL host code requires a browser/WebGL adaptation; shader-text support
+does not make native OpenGL programs directly executable in Three.js.
+
+The maintenance checkpoint on September 23 passed **2,890 offline tests** and
+Ruff, before the subsequent large-fire and external-shader additions. This is
+behavioral/runtime evidence, not a claim that every procedural effect is
+photorealistic. Final integration results are recorded separately in the
+[development record](GRAPHICS_ROADMAP.md).
diff --git a/harness/docs/GRAPHICS_ROADMAP.md b/harness/docs/GRAPHICS_ROADMAP.md
new file mode 100644
index 00000000..56b7b081
--- /dev/null
+++ b/harness/docs/GRAPHICS_ROADMAP.md
@@ -0,0 +1,120 @@
+# Graphics effects development record — September 23, 2026
+
+## Objective and scope
+
+The user requested a thorough review and refinement of the existing graphics
+effects, plus useful new effects, allowing seven hours of sustained development.
+Work began around 07:27 UTC. This record separates completed verification
+checkpoints from work still awaiting final integration.
+
+The review covers all 50 existing Three.js library modules, their agent-facing
+catalog, lifecycle and composition contracts, rendered appearance and runtime
+behavior. It also checks the separate GLSL graphics cookbook/recipe surface and
+OpenGL authoring guidance. Existing upload packages remain immutable; new
+gallery revisions and transfer packages use distinct artifacts.
+
+Every existing module needs an explicit disposition: improve with evidence,
+retain with justification, or supersede while preserving a documented caller
+path. Passing compilation alone does not establish visual quality. New effects
+must fill a meaningful gap, remain usable by scene authors, and have inspected
+GPU cases plus appropriate behavioral validation.
+
+## Review ownership
+
+| Family | Existing modules | Evidence record |
+| --- | --- | --- |
+| Weather, water and atmospheric light | accumulation, atmosphere, caustics, celestial, clouds, damp, godrays, rain, sky, submerged, veils, water, watermist, waterside, wetground | `graphics_audit_weather.md` |
+| Living scenes and animation | canopy, cloth, dapple, figure, fire, flock, flowers, foliage_shade, grass, meadow, smalllife, woodland | `graphics_audit_life.md` |
+| Built environment and surfaces | aging, building, finish, materials, neon, roadway, rock, sand, signage, strata, surface_wear, terrain, terrain_shade, urban, windows | `graphics_audit_surfaces.md` |
+| Shared code and recent water | environment, instancing, merge, noise, ocean, place, shader, stream | `graphics_audit_core.md` |
+
+The complete baseline source, original hashes and export inventory are retained
+in `examples/graphics_lab/output/seven-hour/`. The inventory contains 50 rows;
+reviews must not silently omit older effects because recent showcase modules
+already have stronger tests.
+
+## Work sequence
+
+1. Inspect each module and its tests; render representative factory/material
+ combinations and identify visual, numerical and ownership defects.
+2. Correct substantive existing defects and improve effect appearance, with
+ fixed-camera evidence where appearance changes. Keep shared rendering
+ behavior stable unless a separately demonstrated renderer defect requires it.
+3. Add distinct missing capabilities identified by that review. Use bounded
+ algorithms, absolute simulation time, seeded construction, documented local
+ coordinates and owned-resource disposal. Do not duplicate an existing effect
+ under a new name merely to increase the library count.
+4. Integrate agent guidance, inspect composition cases and exercise the library
+ through independent coding-agent cases where useful. Preserve source/model
+ provenance and distinguish authored demonstrations from model output.
+5. Run relevant regression checks, real GPU rendering, animation and browser
+ controls; inspect code/video correspondence and English-only example text.
+ Record limitations and performance costs, then audit the full objective.
+
+## Maintenance checkpoint
+
+All 50 original modules have an explicit, evidence-backed disposition: 47 received
+visual, behavioral or ownership corrections; three were retained with stated
+justification. The original source/hash baseline remains unchanged. Six new visual
+modules (tree, cloud volume, ice, smoke, waterfall and paving) and one resource
+ownership module have inspected cases and focused tests.
+
+The complete offline suite passed **2,890 tests** in 196.94 seconds, with one
+unrelated Pillow deprecation warning. Ruff also passed. Retained logs are
+`/tmp/graphics-seven-hour/offline-maintenance-checkpoint.log` and
+`/tmp/graphics-seven-hour/maintenance-ruff.log`. These establish the maintenance
+checkpoint before the later fire-field and external-shader extension.
+
+Substantive final maintenance corrections include:
+
+- Stream, calm water and wet-floor captures use the correct transformed plane and
+ restore nested renderer state after success or exceptions. Sixteen real GPU
+ state cases pass; transformed mirror-camera error falls from 6.876 metres to
+ floating-point noise. Existing raw water/floor pixels remain bit-identical.
+- Cloud support no longer reaches the proxy box walls or wraps separated shapes
+ through the boundary. Five seeds and multiple times/cameras were inspected.
+ Wind moves internal density detail; whole-cloud translation remains explicit.
+- Tree leaf geometry can be reduced independently of seeded leaf placement and
+ woody structure. The rain composition falls from 20.7 to 12.4 million triangles
+ while retaining its foliage count and silhouette at the tested cameras.
+- Rain shelter coverage, stream/meadow finite HDR edges, true terrain sampling,
+ owned resource disposal, transformed normals and animation contact retain their
+ focused actual-GPU/behavioral evidence in the family records.
+- The revised Luna creek now matches bank geometry to its water grade and seats
+ actual pebbles. Original CLI output and later delegated refinement remain
+ separately identified in the agent-case provenance.
+
+The three GLSL recipe films have been decoded and compared with ordered source
+frames. The gallery verifier now binds source snapshots, encoded-file digests and
+three retained input PNGs; it checks complete camera plans and rejects substituted
+primary scenes, stale sources, changed video bytes and frozen animation. Pixel
+change is not an aesthetic score.
+
+## User-requested extension after maintenance
+
+The subsequent request specifically adds campfire, large open fire and burning-house
+visual cases, and asks whether Three.js can consume independent GLSL files. A real
+GPU audit found that scaling the original fire by ten preserves almost the same
+image structure and motion; it also integrates density behind embedded opaque
+walls. A bounded shared multi-emitter field with optional explicit opaque-depth
+termination is in development. Existing candle and small-fire behavior is retained.
+
+Independent `.vert`, `.frag` and `.glsl` loading already works in the scene runtime,
+writer, snapshots and candidate promotion. Guidance now documents asynchronous
+local FileLoader loading; standalone asset builders remain synchronous. Shader
+preflight now maps external compile errors to their original file and line.
+Thirteen existing/new shader diagnostics tests pass, including real GPU valid and
+broken external shaders. Gallery staging, capture, verification and transfer
+packaging now preserve those shader files and retained input frames; twenty
+build/media/package regressions pass. An actual external-shader material study is
+being authored alongside the two fire compositions.
+
+## Final integration still pending
+
+Freeze the final library and complete gallery registry, render the authored cameras
+and films into a new output directory, inspect them, run the full browser control
+and strict decoded-media checks, then repeat the complete offline regression.
+Refresh the inventory and final evidence record from that exact source snapshot.
+Prior packages, comparison baselines and published media stay immutable. Passing
+checks does not imply fluid/combustion simulation, recursive transparent transport
+or photorealism; remaining effect-specific limitations stay documented.
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 58a60a7b..8908bb31 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -259,10 +259,30 @@ BuildResult.error_type spellings (languages/_common.py): MISSING_ENTRY = "Missin
| `CadQueryRuntime` | `src/model.py` | trailing selector on the stack → parent solid exported + warning (ExportError when no solid exists); helper-module errors map to `src/<file>.py:line`; object.glb/stl/step |
| `ThreeJsRuntime` | `src/object.js`, `src/parts/*.js` | **Δ export as authored** (census `placement_offset`); InstancedMesh baked to `<Name>_<i>` meshes (`instanced_meshes_baked`); exported `selfcheck(THREE, root)` is called (throw → SelfCheckError); NaN geometry errors name mesh/part → routed to `src/parts/<snake>.js` |
| `UrdfBlenderRuntime` | `src/model.py`, `src/robot.urdf` | object.glb (Y-up, node=link, joint extras), meshes/<link>.glb (raw Z-up link frames); link name `world` is reserved (lint ERROR + UrdfError); robot GLB root gets `__root` suffix on name clash; the build collides the REST pose only (RestPenetration > 5 mm, D17) — every pose is the round's `joint_sweep` gate — and writes no articulation.json / census.articulation (Δ 2026-09-22) |
-| `SceneThreeJsRuntime` | `src/scene.js`, `src/zones/*.js`, `src/assets/*.js`, `src/env.js`, `src/shaders/*.js` | glb_path=None; ok iff `spatial.probes.run_probe(ws, *, compile=True, timeout_s=None) -> (scene_probe, shader_preflight, census)` (one `probe_scene.mjs --compile` boot; `probe_scene` is the same call without `compile`) passes both; both reports ride `BuildResult.gates`, and the `shader_probe` tool reports the same call |
+| `SceneThreeJsRuntime` | `src/scene.js`, `src/zones/*.js`, `src/assets/*.js`, `src/env.js`, `src/shaders/*.{js,vert,frag,glsl}` | glb_path=None; local shader text loads inside async createScene; ok iff `spatial.probes.run_probe(ws, *, compile=True, timeout_s=None) -> (scene_probe, shader_preflight, census)` (one `probe_scene.mjs --compile` boot; `probe_scene` is the same call without `compile`) passes both; both reports ride `BuildResult.gates`, and the `shader_probe` tool reports the same call |
| `GlslShaderRuntime` | `src/shader.frag`, `src/common.glsl`, `src/buffer_a.frag` (+ the harness-owned `src/recipes.glsl` when seeded) | harness owns `#version`/uniforms/`out` (wrap.HEADER: u_time/u_resolution/u_mouse/u_frame/u_prev/u_noise + iTime/iChannel* aliases); `wrap.compose(shader, common, recipes_src=…)` pastes header < recipes < common < shader; build renders judge frames via GlHost; compile errors → GlslCompileError at mapped src file:line (recipes.glsl included); lint ERROR `redefines_recipe` when an agent file defines a recipes.glsl name; artifacts frames/, frames_sheet.png, preview.gif, metrics.json |
| `OpenGLPythonRuntime` | `src/program.py`, `src/*.glsl` | `setup(ctx,w,h)->state` + `render(ctx,state,t,frame,fbo)` run in a moderngl subprocess (`wrappers/run_gl.py`); exceptions map to src/program.py:line, in-string GLSL errors carry both line numbers |
+**Scene effect ownership and shader composition.** The agent imports the frozen
+`src/lib/` modules from zone/environment code. Object effects expose
+`userData.update(t, dt)` with absolute seconds; older `tick(t)` aliases remain
+compatible. Call one update path once per frame. Factories with
+`userData.dispose()` capture construction-owned resources, including instance
+buffers and custom shadow materials; later caller additions and borrowed
+materials/textures retain their owner's lifetime. `lifecycle.snapshotResources`
+excludes textures by default, and `attachDisposal(root, resources)` releases an
+explicit set once, attempting all cleanup before reporting aggregate errors.
+
+`shader.patchStandard(material, opts)` composes registered patches, including
+`alphaBody` before alpha testing, `normalBody` after normal maps and
+`transmissionBody` after Physical-material optical maps but before refraction.
+`clonePatchedMaterial(material, {shareUniforms:false})` reconstructs registered
+patches and independently copies typed uniforms while borrowing textures;
+ShaderMaterial/RawShaderMaterial uniforms follow the same rule.
+`shareUniforms:true` retains the source map for externally controlled static
+batches. `shadowLike` supplies both displaced depth and point-distance materials.
+External unregistered shader wrappers must be reapplied by their owner.
+
Wrappers are standalone (never import codeverse3d). The three python build wrappers live
together in `languages/wrappers/` — `run_bpy.py`, `run_bpy_links.py` (Blender's python 3.11),
`run_cq.py` — beside the sibling modules they import from their own directory:
diff --git a/harness/docs/graphics_audit_core.md b/harness/docs/graphics_audit_core.md
new file mode 100644
index 00000000..667e308d
--- /dev/null
+++ b/harness/docs/graphics_audit_core.md
@@ -0,0 +1,213 @@
+# Shared graphics, water and runtime audit
+
+> Historical working notes from the development snapshot (2026-09-23). The per-module test files
+> and case counts cited below were folded into `tests/scene_runtime/lib/test_library.py` when the
+> library landed on main (D96, D97); `/tmp/...` evidence paths are from that session and are not kept.
+
+This is the integration audit for the eight original modules assigned to the
+core pass, with the later shared-runtime regressions and new capabilities recorded
+separately. The authoritative module ledger is
+[`inventory.json`](../examples/graphics_lab/output/seven-hour/inventory.json).
+Its 50 historical source hashes all match the untouched
+[`baseline/src/lib`](../examples/graphics_lab/output/seven-hour/baseline/src/lib/).
+At this checkpoint, 47 original modules changed; `caustics.js`, `finish.js` and
+`ocean.js` were retained unchanged. Retention is an explicit disposition, not an
+omission. There are seven additional modules: six visual capabilities and one
+ownership helper. They are not counted among the original 50. The subsequently
+requested `firefield.js` extension is still under development at this ledger
+checkpoint and is excluded from the seven accepted additions below.
+
+The [weather](graphics_audit_weather.md), [life](graphics_audit_life.md) and
+[surface](graphics_audit_surfaces.md) ledgers explain the other 42 original
+modules. The inventory gives each module's actual named exports, baseline and
+current SHA-256, disposition, tests, concrete evidence and remaining limits.
+Current hashes describe the recorded checkpoint, not a promise that concurrent
+integration has stopped. The bounded cloud refinement has been accepted; final
+combined gallery capture and the later fire extension remain separate work.
+
+## Original core modules
+
+| Module | Final disposition, concrete evidence and limits |
+| --- | --- |
+| `shader.js` | **Corrected shared behavior and ownership.** Surface normals now use the inverse transpose, including mirrored transforms; local directions use the full reciprocal basis under composed shear. Sixteen model/instance combinations are compared to CPU references on the GPU. Displaced point-light distance shadows now accompany depth shadows, with shared alpha silhouettes. Normal and transmission hooks preserve patch order. Depth-pass guards compose existing callbacks and restore authored draw ranges. Typed material cloning preserves borrowed samplers, control sharing and registered patches. The shared synchronous `withRendererState` scope now restores nested capture state on success and failure. See `test_shader_geometry.py` and the detailed regression table below. Arbitrary external shader wrappers and host postprocessing remain outside this helper's contract. |
+| `place.js` | **Corrected world/local placement.** The frozen valid scaled-parent fixture buried a seated base by 16.5506 m, moved it horizontally by 7.8634 m and missed the requested heading by 94.18 degrees. Seating, facing and route placement now preserve world targets; hidden ancestors cannot supply supports or obstructions. `test_spatial_ownership.py` measures resulting positions and headings. Baseline measurements are retained in `/tmp/graphics-seven-hour/baseline/core/probes.json`. These are placement heuristics, not rigid-body collision simulation. |
+| `instancing.js` | **Corrected geometry and cleanup.** A mirrored baseline box had all 12 triangles wound against its normals, and a hidden sibling was baked into the result. Prototype mirrors now reverse winding; mirrored placements use a corrected batch with positive-determinant matrices. Hidden branches are omitted. Cleanup owns copied geometry and instance buffers while borrowing prototype materials. Invalid zero/infinite spacing fails without unbounded construction. Evidence: `test_instancing.py`, `test_spatial_ownership.py` and the frozen core probes. Batching still depends on compatible prototype materials and geometry. |
+| `merge.js` | **Corrected material preservation and cleanup.** Batches previously replaced physical materials with MeshStandardMaterial, losing transmission, thickness, IOR and attenuation. Cloning now retains the material type and registered patches, with deliberately shared animation controls. Mismatch diagnostics cover optical maps/properties, and cleanup owns only output geometry/material. Existing colour baking and mirrored winding remain. `test_merge.py` and the live render-target clone/merge regression verify behavior. Merging is not a substitute for transparent-object sorting. |
+| `environment.js` | **Corrected enclosure geometry and ownership; retained background appearance.** Independently built sill/lintel strips refilled overlapping door/window openings. The enclosure now subtracts their union, checked by more than 1,500 occupancy rays in `test_room_shell.py`. Environment factories dispose their own maps and light shadow targets; caller attachments stay borrowed. `test_environment.py` and spatial ownership tests cover the contracts. The inexpensive horizon, ground continuation and mood lighting remain lighting/background tools, not volumetric weather. |
+| `noise.js` | **Corrected numerical limits and retained field appearance.** The seed-offset cache is bounded without changing deterministic values; zero octaves produces a flat field and nonfinite/overflow inputs fail clearly. Displacement refreshes existing culling bounds. `test_noise.py` and spatial ownership checks cover these changes. The established seeded ImprovedNoise field remains, avoiding changes to every dependent effect's geometry. It is a procedural field, not a measured physical distribution. |
+| `ocean.js` | **Retained unchanged after prior visual refinement.** Its existing implementation has 32 dispersive directional bands, analytic normals, filtered micro-slope roughness, directional sky reflection and bounded mean-plane reflection. The ten current tests cover inverse surface sampling, narrow shore contraction, light refresh, ownership and GPU compilation. Prior fixed-camera images are in `examples/graphics_lab/output/comparison/renders/ocean/after/`; the refined first-six package includes the film. Those visual changes predate this seven-hour pass and are not counted again. Limits remain non-overturning kinematic waves, one mean-plane reflection and no fluid solver. |
+| `stream.js` | **Corrected composed optics and reflection state; retained recent flow design.** Border fallback blends radiance rather than folding UVs. Optical rays intersect the graded bed under full world/local transforms, and optional endpoint fade supports weir joins. The reflector uses an inverse-transpose world-plane normal under scale/shear, and scoped cleanup restores renderer state on success or failure. The 15 current cases include actual refraction/border pixels, transformed optical rays, mean-plane camera geometry and GPU state restoration. The waterfall black patch was traced to upstream meadow NaNs, not repaired by hiding the sheet. Matched evidence and limits are recorded below. |
+
+## Shared regressions checked against the actual tests
+
+These are current collected cases, including parameter expansion. Counts identify
+coverage. The later planar and external-shader follow-ups have retained execution
+logs and real GPU evidence. Historical family execution results and final combined
+integration status are distinguished below.
+
+| Component and test file | Cases | Behavior demonstrated |
+| --- | ---: | --- |
+| `tests/scene_runtime/lib/test_shader_geometry.py` | 8 | Inverse-transpose normals and reciprocal directions cover 16 model/instance combinations. Depth/distance variants share deformation, time and alpha silhouettes. Callback guards support arrays, later material replacement and authored ranges. Physical transmission hooks execute after maps and survive cloning. ShaderMaterial/RawShaderMaterial clones retain ordinary and render-target texture identity while copying typed values, unless sharing is explicit. A real GPU check samples a live render target through a clone and a merged batch, including later source-uniform edits. |
+| `tests/scene_runtime/lib/test_meadow.py` | 6 | Fractional blade-height powers use a finite domain. A 3,000-blade, four-sample, half-float target with NoToneMapping is read back at two times; the failing fixture had 699 nonfinite HDR channels and the corrected fixture has zero. Other cases retain seeded geometry, motion, validation and ownership coverage. |
+| `tests/scene_runtime/lib/test_stream.py` | 15 | Actual checkerboard refraction and border-radiance tests accompany CPU/GPU flow and sampling checks. Independent ray/plane calculations cover transformed optics. Reflection camera geometry covers scale/shear. Eight renderer-state configurations cover pixel ratios 1/2, default versus post-binding target rectangles, and successful versus injected-failure capture. |
+| `tests/scene_runtime/lib/test_planar_capture.py` | 3 | Water and wet-ground addon capture cameras and projected coordinates agree with independent plane math under uniform, nonuniform, mirrored and composed transforms. Sixteen success/failure target configurations preserve renderer state. Caller-attached Mesh, Camera/inverse, Bone hierarchy and manually managed world matrices survive nested capture and return with their authored update flags; disposal preserves caller resources. The third test checks nested shared-state scopes and callback results/exceptions. |
+| `tests/scene_runtime/test_external_shaders.py` | 3 | Actual GPU loading of separate `.vert`, `.frag` and `.glsl` files succeeds; a broken raw fragment maps to its actual source line. Raw shader static auditing does not reinterpret helper text as an independent JavaScript material. |
+| `tests/scene_runtime/test_census_instances.py` | 3 | The bound `geometry._maxInstanceCount` is authoritative. An unused short instance attribute cannot reduce the actual draw count. GPU submissions with requested instance counts 8, 3 and Infinity agree with renderer statistics; pre-binding inference remains conservative. Hidden ancestors, draw-range starts and primitive type are covered. |
+| `tests/graphics/test_graphics_lab_lifecycle.py` | 1 browser test, six scenarios | Authoritative disposal, fallback ownership boundaries, fallback cleanup failure, throwing scene/renderer cleanup, invalid scene contracts and cancelled asynchronous creation all release renderer/context/canvas exactly once. Borrowed textures, cached materials and caller attachments survive. Cleanup failure cannot prevent later cleanup steps. |
+
+The shader clone repair addresses two distinct native-clone failures: ordinary
+textures were duplicated, and render-target uniforms could become null. Aliasing
+between `material.uniforms` and the library control map is preserved. Registered
+Astra patches are copied; an arbitrary caller's `onBeforeCompile` wrapper still
+requires explicit reattachment. The tests check runtime values and rendered pixels,
+not merely shader source spelling.
+
+Scene census counts visible submitted geometry. It does not multiply that count by
+shadow, reflection, transmission or postprocessing passes, and points/lines do not
+become triangle counts. Viewer fallback cleanup observes ownership boundaries;
+an explicit scene disposer remains authoritative rather than being followed by an
+unconditional resource traversal.
+
+## Waterfall composition: isolated failure and repair
+
+The stream investigation is frozen at
+`/tmp/graphics-seven-hour/stream-reflection-fix/README.md`, with before sources,
+an isolated clamp-only variant, exact final sources/tests, `comparison.jpg` and
+`sha256.json`. The matched waterfall view used a 512-pixel reflection target.
+In the fixed region x390:510, y475:525, near-black pixels fell from 793 to zero.
+
+Captured half-float transmission and reflection targets established the cause:
+multisample edge interpolation made a meadow height coordinate slightly negative;
+fractional powers generated NaNs. The falling film sampled that invalid HDR
+radiance and mip filtering spread it. Hiding the film removed propagation but left
+the bad upstream target. Clamping only the meadow power inputs removed the visible
+patch with the film, its transmission and stream reflection all enabled. This is
+supported by the separate meadow HDR regression; it is not a claim that every
+black pixel is a transmission defect.
+
+The stream's independent plane-transform repair agrees with an analytic reflected
+camera within 2.2e-9 m in its fixture; the 1e-7 tolerance permits the Float32 ribbon
+anchor. Capture restores target, cube face, mip, logical and actual viewport/scissor,
+scissor test, XR, shadow auto-update, tone mapping, clear colour/alpha and prior
+surface visibility. Post-binding rectangle overrides are retained without changing
+target metadata. A `finally` block covers errors in capture; it cannot reconstruct
+a partially rendered frame after arbitrary errors inside Three.js.
+
+The earlier border-only comparison remains at
+`/tmp/graphics-seven-hour/new/stream-edge-comparison/`: only `stream.js` changed,
+with six matched GPU frames. Sixteen transformed optical-ray fixtures agree with
+independent bed-plane intersections within 0.012 mm at these scene scales.
+The later final-b reflection evidence contains eight frames at four matched cameras
+and times 0/1.5, with no shader/console errors; all 15 stream cases passed in its
+recorded checkpoint. One mean-grade reflection and screen-space transmission remain
+approximations, without recursive transparent transport or hydraulic collisions.
+
+## Addon planar capture maintenance follow-up
+
+`/tmp/graphics-seven-hour/planar-capture-review/README.md` freezes the Water and
+wet-ground transform/state repair. Stock addon rotation extraction cannot represent
+the inverse-transpose normal under shear/nonuniform scale. A temporary rigid plane
+frame supplies the correct reflected camera, while each addon retains its own
+projection convention: Reflector's matrix is remapped to actual mesh-local geometry;
+Water's matrix projects world positions and is not remapped. Identity-scene RGBA
+readback stayed bit-identical in 1,228,800 channels. Thirty-two matched full-post
+frames cover water, wet ground, rain and cloud scenes with no compile/console errors;
+the retained repeated-baseline controls quantify minor postprocessing variation.
+
+The shared `withRendererState` guard restores target/cube face/mip, logical and
+actual viewport/scissor, scissor test, XR, shadow update, tone mapping and clear
+colour/alpha. Foreign override/material passes and capture re-entry are skipped.
+The addon mesh's real world matrix and update flags are restored after capture.
+
+Independent review then found that the nested scene update propagated the temporary
+rigid matrix to caller descendants. `/tmp/graphics-seven-hour/planar-descendant-review/`
+retains exact before/after sources and a regression that fails both old factories.
+The final fix freezes descendant world recomputation for the capture and restores
+both authored update flags in `finally`. Mesh, Camera including its inverse matrix,
+Bones and manually managed transforms are checked during and after actual rendering,
+on success and injected failure. Camera/bone ownership remains with the caller.
+The relevant 48-case suite passed in 20.43 seconds; the independent reviewer also
+reproduced the fix on the GPU. Ordinary horizontal calm-water normal fields remain
+an approximation: correct reflection geometry does not imply arbitrary-orientation
+physical water shading, a multiple-reflector coordinator or recursive transport.
+
+## Seven accepted additions, kept separate from the original fifty
+
+| New module | Capability, evidence and explicit limits |
+| --- | --- |
+| `cloudvolume.js` | Bounded ray-marched clouds, self-shadowing, Beer extinction, quality tiers and a CPU density query. **Seven tests pass.** `/tmp/graphics-seven-hour/cloud-final-refinement/` is the accepted latest source and 48 matched composed/independent-seed GPU images. Stationary unequal convection towers and support prevent advected noise regrowing against proxy faces; G/B erosion noise still moves. CPU/GPU inset-boundary density falls from about 0.028 to zero for the regression. Earlier first-density depth and rounded base-fade repairs remain. This does not simulate evolving convection, truncate rays at intersecting opaque geometry, or cast terrain cloud shadows; log-depth retains the proxy fallback. |
+| `ice.js` | Closed bevelled fracture floes, fitted gaps, absorption/frost, internal air lenses and an exact top-triangle height query. Nine tests and `/tmp/graphics-seven-hour/ice-final/` provide source and three-view evidence. Optical exit distance is approximate; Three transmission does not recursively trace water or other floes. Fractures are authored, not a mechanics simulation. |
+| `paving.js` | Closed crowned/bevelled cobbles or setts, recessed joints, moisture response and triangle-based height sampling in two merged meshes. Eight tests and `/tmp/graphics-seven-hour/paving-final/` plus `paving-variants/` cover geometry and dry/wet appearance. Patches are rectangular, without arbitrary-route conformity or standing-water optics. |
+| `smoke.js` | Seeded rising smoke/steam, bounded density, CPU query, quality tiers, lighting and world-metre extinction. Six tests include nonuniform optical path scale and first-density depth testing. Frozen evidence includes `/tmp/graphics-seven-hour/new/smoke/renders-v7-dilution/` and `new/smoke-v7-films/`. These are prescribed transport/scattering fields, without fluid dynamics or scene-depth truncation; logarithmic depth keeps the proxy fallback. |
+| `tree.js` | Connected branches, petioles and leaves, species-specific forms, coherent wind and filtered bark. **Sixteen tests pass**, including finite HDR and supersampled bark for three species. `/tmp/graphics-seven-hour/tree-bark-refinement/final/` freezes the material refinement. Later opt-in `leafSegments` reduces leaf triangles while preserving wood, leaf count, placements and colours; species defaults stay unchanged. Rain V5 uses four segments for background leaves: 20,706,817 to 12,419,137 scene triangles (40.02% less), with the same 102 meshes and 490,979 instances. This is a geometry reduction, not an FPS claim. Wind is prescribed and host AO sees rest geometry. |
+| `waterfall.js` | Accelerating free-fall film with width/velocity/thickness conservation, advected breakup, local aeration and existing impact spray. Four tests compare CPU/GPU film position and thickness and cover quality, replay and ownership. Current composed evidence is `/tmp/graphics-seven-hour/waterfall-composition/final-reflective/`, with the lower stream reflector enabled at 512 pixels; the earlier `new/waterfall-v9-films/` films retain their own source versions. This is an authored sheet, not hydraulic collision simulation; its transmission sees the opaque scene and impact spray is not simulated droplets. |
+| `lifecycle.js` | **Support module, not a visual effect.** Construction-time resource snapshots and idempotent, failure-tolerant cleanup. Two direct tests and family ownership regressions verify the contract. Textures are not implicitly owned; factories must add allocated textures and other private resources explicitly. |
+
+The accepted cloud support refinement retains the final-b depth/base repairs and
+supersedes the earlier five/six-test cloud checkpoints. The later meadow HDR repair and tree bark refinement
+likewise supersede those specific life-family snapshots. Earlier immutable evidence
+remains useful but is not silently relabelled as the latest source.
+
+## Separate graphics authoring surface
+
+The GLSL cookbook is executable library content seeded into `src/recipes.glsl`.
+Its star distance function, zero-length segments, reversed smoothstep edges and
+rain-cell advection were corrected using numerical GL checks. Bounded-volume
+transport and direct GGX recipes provide explicit conventions and dependency
+seeding; they are neither a fluid simulator nor a complete path tracer.
+The OpenGL cookbook's sphere winding now agrees with its outward normals, and its
+normal/ownership guidance matches the actual setup/render host contract.
+
+Three six-second GLSL films are retained under
+`examples/graphics_lab/output/seven-hour/recipes-motion-v1/`, with source hashes,
+ordered frame verification and a recorded mean compression error of 1.03–1.48/255.
+The explicit frame order prevents lexical `f100`-before-`f10` encoding. A real
+relative-output render exposed double resolution of the GL job path; resolving
+the output directory once fixed it. These recipes and runtime fixes are additional
+work, not extra JavaScript modules in the 50-plus-seven census.
+
+The Three.js scene authoring contract now explicitly supports local shader source
+files through `FileLoader(loaders.manager)` and module-relative URLs in async
+`createScene`. Browser loading remains outside synchronous asset builders. The
+accepted `external_shader.js` study loads a `.vert`, `.frag` and `.glsl` helper,
+uses explicit GLSL3 interfaces and animates cached uniforms/transforms at absolute
+time. `/tmp/graphics-seven-hour/external-shader/` retains three camera views at
+three times, clean actual-GPU shader diagnostics, zero nonfinite HDR channels under
+4x MSAA, exact time replay and exactly-once owned-resource disposal. Its restrained
+alloy finish uses an analytic studio reflection field; it does not receive scene
+shadows/interreflection and is not a multilayer optical solver. Gallery source
+staging, hashes and portable packaging are separate integration checks.
+
+## Verification checkpoint and remaining integration
+
+The clean retained maintenance log is
+`/tmp/graphics-seven-hour/offline-maintenance-checkpoint.log`: **2,890 passed,
+one Pillow deprecation warning**, in 196.94 seconds. This is a historical clean
+maintenance checkpoint, preceding the descendant follow-up and external-shader/fire
+extensions. The earlier `/tmp/graphics-seven-hour/offline-integration-1.log`
+(2,872 passed and one documentation-map failure) remains historical evidence;
+the map defect was corrected. Neither log is relabelled as a final combined run.
+The descendant follow-up has its own retained **48 passing** relevant checks,
+cloud refinement **7**, tree detail **16**, and shader prompt coverage **53**.
+Counts overlap and must not be summed into an aggregate final-source pass claim.
+
+The prior test collection `/tmp/graphics-seven-hour/historical-final-inventory-test-collection.txt`
+recorded 742 cases across 67 files. The inventory generator is prepared to recollect
+current parameterized tests and actual exports at final source freeze. Collection
+is distinct from execution; final counts and hashes await the root integration
+checkpoint, including the in-progress `firefield.js` extension. Family snapshots
+prove their exact captured module versions, not current identity of all shared
+shader and lifecycle dependencies.
+
+Rain's accepted V5 scene is a composition change, not an isolated library comparison.
+`/tmp/graphics-seven-hour/rain-composition/REVIEW.md` and `leaf-detail-comparison.json`
+record fixed-camera appearance, six GPU frames and reduced background leaf geometry.
+The read-only V2 shelter checks remain applicable because later planting revisions
+leave roof/deck/rain/splash construction unchanged: 4,092 deck probes per camera have
+zero roof misses and all 720 splash positions avoid sheltered ground-level impacts.
+Waterfall's final reflective composition, accepted cloud support refinement and
+external shader study await combined final-gallery capture/verification with the
+remaining additions. Existing delivered packages remain immutable. Repository
+source/tests are durable references; `/tmp` evidence is local until explicitly
+included in a portable artifact. This ledger does not claim that every temporary
+capture is already packaged.
diff --git a/harness/docs/graphics_audit_life.md b/harness/docs/graphics_audit_life.md
new file mode 100644
index 00000000..fa4aeada
--- /dev/null
+++ b/harness/docs/graphics_audit_life.md
@@ -0,0 +1,100 @@
+# Living and animated graphics audit
+
+> Historical working notes from the development snapshot (2026-09-23). The per-module test files
+> and case counts cited below were folded into `tests/scene_runtime/lib/test_library.py` when the
+> library landed on main (D96, D97); `/tmp/...` evidence paths are from that session and are not kept.
+
+Audit started 2026-09-23 07:29 UTC against the current working tree. The first sections preserve the baseline assessment; implementation and validation below describe the completed changes. No shared gallery configuration was edited by this family owner.
+
+The frozen source, source hashes, probe script/results, render scenes, PNGs, runtime logs and full test output are under `/tmp/graphics-seven-hour/baseline/life`. Every case contains its own copy of the frozen library so later shared-workspace edits cannot alter the baseline. The tests completed with **148 passed in 27.93 seconds**. Compilation and structural tests pass; this does not establish realism or complete resource cleanup.
+
+The audit uses the production Three.js host and post chain at 960 × 640, times 0 and 0.7 seconds. Most scenes adapt the existing compile fixtures, adding a background or closer camera where needed. They are diagnostic scenes, not claimed polished showcases. The woodland compile fixture places cards closer than its own documented 35 m exclusion distance; `woodland_far` is the appropriate additional visual comparison. `meadow_showcase` uses the already authored meadow example for a composed reference. A sparse test fixture or missing scene ground is not attributed to a library defect.
+
+## Frozen baseline findings
+
+| Module / exports | Assessment and evidence | Priority and proposed work |
+| --- | --- | --- |
+| `canopy.js`: `makeCanopy` | Real leaf silhouettes, one instanced draw, seeded crowns and shared gusts already work. `canopy/renders/a_t0.png` shows an overly regular ellipsoid/hedge envelope, radial leaf orientation and very dark lower cards. Leaves move independently of any branch skeleton because none is supplied. FrontSide cards lose their reverse faces. Bounds expand by leaf size but do not explicitly include arbitrary wind excursion; frustum culling is disabled. No update/dispose hooks. | **High visual / medium reliability.** Add coherent leaf sprays and growth/age variation with restrained two-sided leaf lighting; make bounds account for wind. Keep crown placement and batching APIs. Add ownership lifecycle. A separate tree factory should supply actual branches rather than silently changing the canopy-only contract. |
+| `cloth.js`: `makeFlag`, `makeBanner`, `makeWheatField` | Flag attachment, travelling waves, banner folds and crop gust propagation are more developed than a generic sine deformation. The rendered flag/banner at both times are readable and do not need a solver rewrite. Wheat remains a field of bare stems and paper-thin ears. No dispose/update hooks; each wheat material owns a generated `uWheatWave` DataTexture. All displaced shadows depend on custom depth only. | **High reliability, medium visual.** Capture and dispose owned geometry, materials, shadow materials and gust texture. Preserve the existing cloth motion; improve light response with actual cloth sheen/transmission and add crop leaf/ear structure within the same draw budget. Clarify point-light shadow limitations or implement distance shadows through the shared helper. |
+| `dapple.js`: `patchDappledLight`, `patchCanopyShade` | `dapple/renders/a_t0.png` shows useful multiscale flecks, but they are an emissive lighting approximation and do not obey actual scene-light intensity or shadow visibility. Dapple normal transformation uses `mat3(modelMatrix) * normal` (and instanceMatrix) rather than inverse transpose, which gives wrong facing on non-uniformly scaled objects. Projection uses canopy height without subtracting the fragment's own elevation, so elevated receivers do not share the same projected gaps. | **High correctness.** Correct receiver normals and projected height. Add controlled light-strength/visibility behavior while preserving the deliberately approximate canopy-shade mode. Verify a tilted, non-uniformly scaled receiver and receivers at multiple elevations. Avoid replacing this with another arbitrary noise pattern. |
+| `figure.js`: `figure`, `sit`, `walk`, `carry` | Seated placement, joints and materials are well tested, but the person is visibly a segmented mannequin at close range (`figure/renders/face_t0.png`); do not claim realistic humans. At speed 1.2 m/s, the lowest shoe penetrates ground by **5.44 cm** during the sampled cycle. `walk(...,{speed:0})` still changes hip angle by 0.0234 rad between t=0 and .4. Cadence arithmetic alone does not produce foot contact. Own geometry and borrowed globally cached materials are mixed. | **High motion / medium lifecycle.** Correct zero-speed behavior and stance/swing contact, add deterministic foot-clearance tests. Improve visible neck/limb junctions conservatively; retain the distant-human scope. Disposal must release owned geometries while preserving material-cache and shared-eye resources and caller-held objects. |
+| `fire.js`: `makeFire`, `makeCandle` | New volumetric flame, seeded motion, candle geometry and real light remain convincing in `fire/renders/fire_t0.png`; preserve them. The existing disposer captures geometry/materials but does **not** call `InstancedMesh.dispose()` on `FireEmbers`, leaving its separate instance buffers allocated after rendering. Log-depth and intersecting transparency limits are already explicit. | **High lifecycle, justified no large visual rewrite.** Fix owned ember-instance disposal with a real disposal-event regression. A rising smoke plume would add a missing capability, but belongs in a separate emitter effect rather than changing existing fire defaults. |
+| `flock.js`: `makeFlock` | Bird/fish silhouettes and decorrelated beats read well at their intended distance (`flock/renders/sky_t0.png`). The claimed speed in metres/second is only an average: the shader advances uniform Catmull-Rom parameter, not arc length. A valid irregular five-point path requested at 9 m/s measures **0.141–21.937 m/s**. Lighting direction is manually supplied and interpreted in local axes. No lifecycle hooks beyond tick. | **High motion.** Use an arc-length lookup and derivative-aligned banking; keep a seeded shader path, one draw and absolute time. Add a CPU sampler or testable path table. Preserve documented distant-silhouette scope. Add lifecycle and transform/light-space regression. |
+| `flowers.js`: `makeFlowers`, `makeFalling` | Individual petals already have curved geometry, species-dependent profiles and seeded variation. `flowers/renders/a_t0.png` nevertheless shows many white heads on bare straight stems: missing foliage/branching and shared head attitude dominate the artificial appearance. Transparent unsorted instancing uses depthWrite, so overlapping petal edges deserve an occlusion check. Existing falling leaves/petals already fill that capability. No dispose/update hooks. | **High visual.** Add species-appropriate basal/cauline leaves, head age/openness and subtle asymmetric curvature; retain one draw and existing kinds. Evaluate alpha coverage or an opaque clipped core with physically motivated thin edges. Improve petal lighting via the shared leaf patch, not extra albedo brightening. Add lifecycle and overlap tests. |
+| `foliage_shade.js`: `patchLeafSSS`, `patchWind`, `patchRootContact` | Leaf transmission adds a view-dependent term to albedo before ordinary lighting, so it is not a shadowed incident-light scattering term; it uses a copied sun direction. `patchWind` moves vertices without correcting surface normals, and its static shadows are explicitly documented. Root contact is a useful world/local-aware material treatment and needs no ornamental rewrite. | **High lighting.** Add normal-correct wind deformation and a scene-light-driven transmission path with shadow attenuation, preserving explicit overrides and patch retuning. Keep root-contact behavior unless a regression demonstrates a problem. The patches own no material, so disposal belongs to their callers. |
+| `grass.js`: `makeGrass`, `windOf` | Efficient older field, useful for medium/far ground cover; the composed close-view role now belongs to meadow. `grass/renders/a_t0.png` is very dark with pointed, similarly shaped leaves. Its shader comment still says this host has no AO, although the host now has GTAO. Bounds cover the root footprint plus vertical height, not lateral bent blades; culling is disabled. Transmission adds light without shadow attenuation. No lifecycle disposal. | **Medium visual, high compatibility.** Preserve low-cost far-field role and windOf API. Fix conservative bounds and disposal; revisit darkness/transmitted sun against the current host, with matched front/backlight renders. Avoid making it a second expensive meadow. |
+| `meadow.js`: `makeMeadow` | Recently improved mixed growth forms, botanical age/habitat variation, rooted curved geometry, wind, shadows and sparse geometric seed culms already have matched GPU evidence. Do not undo this work or raise density as a cosmetic fix. Ownership snapshot preserves caller additions, but neither blades nor culms receive `InstancedMesh.dispose()`. | **High lifecycle, justified no major visual rewrite.** Dispose captured instances as well as geometry/materials. Add a regression with seed heads enabled and a caller-owned appended InstancedMesh. Point-light rest-pose shadows and AO limitations are explicitly documented; coordinate any shared shadow-helper improvement. |
+| `smalllife.js`: `makeInsects`, `makeReeds` | Insect kinds have distinct bounded motion, wingbeat and lighting. `smalllife_close/renders/a_t0.png` shows reeds as bare thin poles with pointed billboard heads; strap leaves are missing. An artificial underwater positional offset also moves the submerged root, despite the rooted contract, and can duplicate actual stream refraction. Scene-light refresh depends on tick count. No disposal/update hooks. | **High reed visual / medium reliability.** Add curved strap leaves and rounded/tapered heads, rooted below-water motion, and optional rather than baked-in refraction distortion. Preserve insect batching; improve deterministic relighting/update semantics and lifecycle. More insect species alone would be lower value. |
+| `woodland.js`: `patchBark`, `makeImposters` | Bark already has distinct species-dependent ridges and weathering. Distant cards are explicitly unsuitable inside ~35 m; the compile fixture violates that rule, so its close result is not evidence to replace them with full trees. Even in `woodland_far/renders/a_t0.png`, a continuous pale rim and repeated rounded crowns remain obvious. No lifecycle on the imposter group. | **Medium visual/reliability.** Reduce continuous halo, increase coherent crown silhouette variation, validate light space under allowed parent transforms and add disposal. Keep their far-field performance role. Near trees should be a new geometry-based factory. |
+
+## Reproducible defects and validation gaps
+
+`probes.json` records the lifecycle inventory, the flock speed measurement and the shoe-height probe; the exact executable script is `src/audit_probe.mjs`. Fire and meadow both report one owned InstancedMesh and zero instance-disposal events in the minimal probes. Installed Three r182 `WebGLObjects.js` removes instanceMatrix/instanceColor buffers in its InstancedMesh dispose listener, independently of BufferGeometry disposal.
+
+Most older factory tests are strong on seeded attributes, shader strings, counts and compilation. New tests should verify the physical or lifecycle behavior being changed: disposal of owned buffers and textures exactly once; caller-resource survival; finite-difference normals; light/shadow response; actual speed and foot contact; same-time rewind. Replacing one asserted shader string with another is insufficient.
+
+At the frozen baseline, shared `shadowLike` supplied customDepthMaterial only. A shared customDistanceMaterial improvement could benefit several modules and should be coordinated with the owner of shader.js; independent per-module copies would duplicate sensitive Three.js shader integration. Flower alpha silhouettes also need the same cut in any new distance pass.
+
+## Proposed implementation order
+
+1. **Ownership and compatibility:** one agreed reusable ownership helper or small explicit snapshots, including textures, custom shadow materials and InstancedMesh buffers. Add update aliases without removing tick. Figure materials remain borrowed; patched materials remain caller-owned.
+2. **Measurable motion and lighting:** flock arc-length speed, figure stance contact/zero speed, dapple receiver projection/normals, wind normals and leaf transmission. Test each behavior on controlled fixtures before aesthetic tuning.
+3. **Botanical silhouette:** flower leaves/head variation, reed leaves/seedheads and canopy spray structure; inspect matched close and wide views, motion and backlighting. Keep instance/draw budgets visible.
+4. **New capability:** a seeded branch-aware `makeTree` / `makeShrub` module, with tapered branch junctions, leaf sprays located at branch tips, optional age/species presets and coherent branch wind. Existing canopy creates only a leaf cloud, and existing imposters only distant cards. This fills the missing near/mid-tree role without duplicating grass, falling particles or fog.
+
+A buoyant smoke/steam emitter is also valuable, particularly with fire/candles, but should be coordinated with the air-family work. Existing watermist and atmospheric fog are surface/region veils, not a rising turbulent plume. Prefer one well-tested emitter with emission history, bounded lifetime and scene lighting over several superficially renamed particle presets.
+
+Any approved implementation should retain these frozen cameras/sources for comparison, add composed ecological scenes where the compile fixtures are insufficient, and reserve time for integration/GPU checks rather than consuming the full seven hours on optional species.
+
+
+## Implemented changes and verification
+
+The current family source is frozen under `/tmp/graphics-seven-hour/after/life/src/lib`, with SHA-256 hashes in `source-hashes.json`. The original 15 diagnostic workspaces were rendered again with identical cameras, lights, resolution and timestamps: **34 GPU images across 17 views**, with no shader or runtime errors. `comparison-metrics.json` records image differences and motion; these values demonstrate changed pixels, not a perceptual quality score. Inspect the PNG pairs for appearance.
+
+The family suite completed with **183 tests passed in 33.10 seconds**. The final denser flock test and tree tests then completed with **24 passed in 5.71 seconds**. Ruff passed after import ordering was corrected in the new tree test. This is a family-level result, not a claim that the entire repository suite has run.
+
+| Module | Final behavior and evidence |
+| --- | --- |
+| `canopy` | Leaves now grow in coherent six-leaf sprays, with curved 24-triangle surfaces, two-sided lighting, analytic surface normals and wind-aware bounds. The existing ellipsoid-placement API remains a canopy-only abstraction; it does not pretend to contain branches. Matched `canopy/renders/a_t0.png` and `a_t0p7.png` show the changed silhouette and coherent motion. |
+| `cloth` | Flag and banner motion retained; actual physical-material cloth sheen added. Wheat gains two curved strap leaves and curved ear geometry in the same instanced draw. The generated gust DataTexture is explicitly owned and released. Existing attachment/wave and GPU tests remain green. |
+| `dapple` | Receiver elevation now changes the canopy-ray intersection correctly. Normals use the shared inverse transpose, and fleck radiance follows actual directional-light intensity and shadow visibility, with irradiance-to-diffuse-radiance division by PI. GPU tests compare translated receivers on the same light ray and light-off behavior. |
+| `figure` | Two-bone leg IK, stance and swing phases, measured shoe-vertex clearance, and compensating ankle pitch keep one foot on the ground. Zero speed restores a stable neutral pose. A high requested speed shortens the gait period instead of silently clamping travel and sliding the stance foot. Neck geometry now bridges the visible gap. Tests cover three body heights, rewind and actual stance velocity up to 4 m/s; this remains a stylized distant mannequin, not a realistic human model. |
+| `fire` | Flame and wax appearance retained. Disposal now includes captured ember InstancedMesh buffers and lights. The custom render guard preserves its mesh receiver when delegating to the shared depth-pass guard. The matched frame differs by only 0.008/255 mean RGB, while animation remains active. |
+| `flock` | A 2,048-sample arc-length DataTexture drives both shader motion and a new CPU `samplePath(t)` sampler. Centripetal interpolation avoids cusps caused by uneven waypoint spacing. The final irregular 9 m/s route measures 8.9955–9.0011 m/s over 1,600 dense samples; the regression uses 8,000 samples around the full period. Lighting normals now reach world space correctly. |
+| `flowers` | Six species-scaled basal/cauline leaves replace bare stalks. Petals use opaque alpha clipping with consistent directional and point-shadow silhouettes, eliminating unsorted translucent overlap. Corrected petal/boss normal orientation prevents black sunlit heads. Transmission preserves flower pigment instead of applying green-leaf variation. A real GPU test verifies sunlit white petals remain bright. |
+| `foliage_shade` | Transmission is shadowed incident radiance, following the scene directional light unless an explicit direction overrides it. Wind uses the analytic deformation Jacobian to update normals; a finite-difference GPU reference agrees within one degree. `patchRootContact` was retained because no defect justified changing its useful behavior. Material patches borrow their inputs and never install ownership disposal. |
+| `grass` | Low-cost medium/far blades remain eight triangles each. Root occlusion and fill were adjusted against the current renderer, transmission obeys shadows, and conservative bounds include bent blades. It remains distinct from the richer close-view meadow. |
+| `meadow` | The existing recent botanical, age, habitat and shape variation was preserved. Captured blades, seed culms and custom shadow resources now dispose completely, including instance buffers. Directional and point-light deformation share the improved global shadow helper. |
+| `smalllife` | Reeds now include four curved strap leaves and shorter, rounded seed heads with extra longitudinal samples around their shoulders. Underwater optical distortion is opt-in and vanishes at the root. Insects refresh scene-light intensity on every update, so lighting and rewind no longer depend on frame count. Close reed matched images show the largest structural change. |
+| `woodland` | Crown silhouettes have seeded lean/shape differences, porous foliage edges and interior gaps, filtered fine breakup and reduced continuous rim brightness. Opaque clipping removes partial-alpha coverage halos between unsorted cards. World normals use the shared inverse transpose. The documented limit now emphasizes crowns about 60 screen pixels or smaller: the older 35 m guideline depended on a 512 px image and was not resolution-independent. Existing bark patch retained; the new tree factory supplies true near wood. |
+
+All object factories expose both `userData.update(t)` and the compatible `tick(t)` alias, plus captured, idempotent disposal. The lifecycle regression covers 15 factories, original resources removed from the returned hierarchy, subsequently appended borrowed meshes and textures, and shared figure material caches. Ownership uses the new shared `lifecycle.js`, authored by the integration owner. Shared `shadowLike` now supplies depth and point-distance materials; flower cuts are shared between passes. The integration owner also corrected world normals, world-to-local directions and mirrored/nonuniform/sheared transforms in `shader.js`. Those shared fixes are dependencies, not duplicated implementations in this family.
+
+### Measurement precision
+
+The initial shoe probe reported a conservative transformed bounding-box penetration of 5.44 cm. A later **exact vertex** probe on the frozen source measured 3.364 cm of actual shoe penetration and up to 2.208 cm with both feet above ground. The same exact probe on the new source reports ground error below 3e-16 m and a maximum swing lift of 11.18 cm. These are procedural fixture measurements, not motion-capture validation. The scripts/results are `/tmp/graphics-seven-hour/life_measure.mjs`, `baseline-foot-vertices.json`, and `after/life/probes.json`.
+
+### Explicit geometry cost
+
+The frozen baseline host census counted `InstancedMesh` correctly but undercounted `InstancedBufferGeometry.instanceCount`. The integrated runtime now counts both, using the bound active-attribute capacity when available. The older-effect budget below includes the geometry instance multiplier; historical render metrics remain unchanged:
+
+| Effect | Base triangles per instance, before → after | Draw impact |
+| --- | ---: | --- |
+| Canopy leaf | 6 → 24 | One instanced mesh retained; 4,000 leaves = 96,000 triangles. |
+| Wheat stalk/ear/leaves | 14 → 38 | One instanced mesh retained; cap 70,000 means up to 2.66 million triangles. |
+| Default daisy plant | 86 → 230 | One instanced mesh retained, including its new foliage. |
+| Reed stem/head/leaves | 24 → 272 | One instanced mesh retained; choose density for close stands deliberately. |
+| Grass blade | 8 → 8 | No density increase or extra blade draw. |
+| Imposter card | 2 → 2 | Porosity and lighting are shader changes. Crossed trees use two cards. |
+
+## New connected tree and shrub library
+
+`tree.js` exports `makeTree(opts)` and `makeShrub(opts)`. Oak, birch and willow presets have connected primary limbs, secondary branches, twigs, fine shoots, real petioles and individually instanced species-shaped leaves. Primary radius follows its tapered parent's cross-section. Variable curvature, apical continuation, branch collars and buttress roots replace equal-weight repeated Y forks. Bark has procedural plate/fissure color and a filtered continuous height gradient; no generated bitmap or model was used. Leaf age/autumn variation, scene-lit transmission and coherent rooted wind are included.
+
+The API uses nominal `height` and `crownRadius`, seeded `leafDensity`, `leafSize`, `maxLeaves`, `autumn`, colors, shadows and the existing wind vocabulary. `maxLeaves` thins the entire crown without stripping later-created branches. `userData.bounds` gives the actual local envelope, `branches` exposes parent/attachment/sample information, `leafAttachments` locates botanical anchors, and `sampleWind(point,t)` samples the wood deformation. These are deterministic absolute-time operations.
+
+Each factory uses two geometry draws, one if bare, excluding shadow passes. Default oak is **961,224 triangles / 15,540 leaves**, birch **1,130,544 / 14,504**, willow **954,060 / 17,765**, and shrub **734,010 / 11,700**. This is a near/mid asset; leaf density/cap should be reduced for background use. The composed `examples/graphics_lab/scenes/tree.js` contains three species, a shrub, meadow, rock and a small projected distant treeline. Its independently counted total is **2,771,713 triangles and 14 geometry draws**. The frozen older census reports 918 fewer triangles because it misses the far cards' instance multiplier; the integrated runtime corrects that count.
+
+Final source and hashes are frozen in `/tmp/graphics-seven-hour/new/tree/final`; renders at 1280 × 800 and t=0/.7 are in `final/renders`. The identical woodland/branches cameras were retained through v1–v11 iterations, so branch refinements are reviewable. Final GPU tests cover fog, directional plus point shadows, nested nonuniform transforms, actual pixel motion and exact time rewind. Structural tests verify branch and petiole attachment, whole-crown cap distribution, outward wood winding, bounds, seeded equality, invalid options and borrowed-resource survival.
+
+Remaining limits are explicit: wind is a coherent deformation field rather than a dynamic beam solver; the host AO sees real tree/meadow geometry in its rest pose; standalone `patchWind` cannot install moving shadow materials on meshes it does not own; imposters remain distant cards; the figure remains a mannequin; fire retains its documented transparent-intersection and logarithmic-depth limits. None of the images is claimed to establish universal photorealism.
diff --git a/harness/docs/graphics_audit_surfaces.md b/harness/docs/graphics_audit_surfaces.md
new file mode 100644
index 00000000..c9c299b8
--- /dev/null
+++ b/harness/docs/graphics_audit_surfaces.md
@@ -0,0 +1,174 @@
+# Graphics library audit: surfaces and built environments
+
+> Historical working notes from the development snapshot (2026-09-23). The per-module test files
+> and case counts cited below were folded into `tests/scene_runtime/lib/test_library.py` when the
+> library landed on main (D96, D97); `/tmp/...` evidence paths are from that session and are not kept.
+
+Audit date: 2026-09-23, starting at approximately 07:27 UTC. This is a read-only assessment of the current worktree, including its uncommitted refinements. No shipped module, gallery source, video or delivered package was changed during this phase.
+
+## Evidence and scope
+
+All 15 assigned modules and their exports/tests were inspected. The focused suite passed **185 tests in 13.10 seconds**:
+
+```bash
+python -m pytest tests/scene_runtime/lib/test_{aging,building,finish,materials,neon,roadway,rock,sand,signage,strata,surface_wear,terrain,terrain_shade,urban,windows}.py -q -n 2 -m 'not live'
+```
+
+The frozen source and evidence directory is `/tmp/graphics-seven-hour/baseline/surfaces/`:
+
+- `src/lib/`: complete baseline library snapshot; `source_hashes.json` records every module digest.
+- `src/scene.js`: material palette, metallic weathering and combined terrain/road study.
+- `renders/material_close_t0.png`, `material_palette_t0.png`, `metal_weathering_t0.png`, `terrain_road_t0.png`: real 1440 × 810 GPU frames.
+- `architecture/src/scene.js` and `architecture/renders/`: cottage, block, tower, window interiors, curtain wall, billboard and power-line study; three 1440 × 810 views.
+- `finish/` and `neon/`: staged GPU examples derived from existing test fixtures. The neon staging moves the tubes in front of the wall; the original compile fixture hides them behind it. This fixture correction does not change library code.
+- `reproductions.json`: numerical option, patch-cloning and surface-sampling failures described below.
+
+The production host ran on the RTX 5090 Laptop GPU with its normal post-processing chain. Material/terrain, architecture and finish renders reported zero console/shader errors. Neon also renders at t=0 and t=1. Images were visually inspected; passing shader tests is not treated as proof of realism. Initial fixture imports through an external symlink were rejected by the workspace server; copying the frozen libraries into those workspaces resolved that staging issue.
+
+## Highest-value corrections
+
+### P1: weathering must change the local BRDF, not the entire material
+
+`aging.js:126,267,385`, `surface_wear.js:217`, `roadway.js:208,413,533` and `strata.js:396` retain whole-material `composeRoughness` adjustments. Several comments still describe per-pixel roughness/metalness as unreachable. Those hooks now exist in `shader.js:726,732`, and `shader.js:825` explicitly recommends them for partial coverage.
+
+Reproduction: applying full rust to metalness 1 / roughness 0.2 leaves metalness at **1** and changes roughness everywhere to **0.32**. Setting the live `uRustAmt` uniform to zero leaves roughness at **0.32**. A clean region therefore loses its original finish, an oxide patch continues reflecting as metal, and animating coverage does not restore the original physical response. The GPU weathering frame shows this limitation on identical cylinders.
+
+Fix: use the same spatial mask for colour, roughness, metalness and bounded surface-normal relief. Preserve clean substrate values exactly; rust and dust should become dielectrics only under their masks. Add final-frame comparisons under a moving specular highlight and a uniform-zero regression. Existing tests which assert global roughness multiplication encode the old limitation and must be deliberately replaced, not blindly preserved.
+
+### P1: wrong transformed normals affect several whole families
+
+`shader.js:777` (`worldBody`) transforms a normal with `modelMatrix` and `instanceMatrix`, rather than their inverse transpose. Direct copies also occur in `roadway.js:71`, `neon.js:454` and `urban.js:71`. Position transforms are correctly included; the problem is specifically normals under nonuniform scale.
+
+For a 45-degree normal and scale `[4,1,1]`, the helper produces approximately `[0.970,0.243,0]` while the correct result is `[0.243,0.970,0]`. That reverses the interpretation of a nearly horizontal surface into a steep slope. Snow, dust, erosion, triplanar weights, edge wear and spill lighting can all be affected.
+
+Fix centrally with a shared normal-transform helper, including instances. Verify GPU equivalence between scaling geometry in advance and applying the equivalent object/instance transform. Coordinate this with the shared-shader owner; fixing only one material family leaves contradictory surface masks.
+
+### P1: material names currently promise structures they do not generate
+
+`materials.js:253–300` makes brick, cobble, fabric, granite and most other presets from the same generic value-noise texture builder. Only palette, noise scale, streak strength and scalar PBR values distinguish them. The close GPU palette confirms that brick has no courses/mortar, cobble has no individual stones, and fabric has no woven structure. These are coherent noise swatches, not reusable close-view material models.
+
+Fix selected existing factories before adding parallel aliases: periodic masonry courses and recessed mortar; irregular cobble cells with physically scaled joints; filtered warp/weft normal and roughness structure; multi-scale wood grain and pores. Keep caching and deterministic variation, with explicit metre scale and an opt-out for generic distant materials. Use close and grazing renders, plus seam/scale tests.
+
+### P1: seating functions disagree with their actual meshes
+
+`terrain.js:55–69` returns the continuous field while rendering a triangulated approximation. `terrain.js:253` similarly returns analytic cliff depth instead of the rendered triangle intersection. The current tests establish agreement at vertices, which does not establish agreement between vertices.
+
+Measured with raycasts at 200 deterministic positions:
+
+| Configuration | Maximum absolute error | Mean absolute error |
+| --- | ---: | ---: |
+| Ground: size 100, relief 6, scale 12, 8 segments | 2.677 m | 0.834 m |
+| Same ground, 32 segments | 0.899 m | 0.205 m |
+| Same ground, 128 segments | 0.166 m | 0.017 m |
+| Cliff: length 20, height 8, relief 2 | 0.783 m | Not aggregated |
+
+Fix with barycentric interpolation of the actual grid triangles, while retaining the analytic field privately for construction. `sand.js:123` already implements the appropriate pattern and its current contract should be preserved. A normal sampler would also let props sit flush with inclined surfaces.
+
+### P1/P2: material option and composition defects
+
+- **Confirmed option bug:** `materials.js:241–248` unconditionally restores `bumpMap` when `repeat != 1`, overriding `bump: 0`. The reproduction returns `bumpZero=true` and `bumpZeroRepeat=false`.
+- **Confirmed composition loss:** `materials.js:379` (`tint`) clones materials without preserving `onBeforeCompile`; a previously patched material loses its procedural shader. `weather()` has the same clone path for shared materials. `windows.js:379` knowingly clears an existing shared material's patch chain before adding windows. Decide on one supported clone-before-patch or patch-aware-clone contract, then test actual compiled output. Do not silently advertise arbitrary chaining through these mutators.
+- **Sharp-edge limitation:** `surface_wear.js:238` estimates curvature from interpolated normal derivatives. Hard BoxGeometry faces have constant normals, so the effect cannot reliably discover their geometric edges. A bevel/curvature attribute or an explicit edge-distance input is needed for architectural edge chipping; a larger strength parameter is not a remedy.
+
+## Per-module disposition
+
+Priorities: P1 fixes materially incorrect behaviour or a major reusable realism gap; P2 is a bounded enhancement; keep means retain the working capability while addressing shared fixes.
+
+| Module and exports | Current evidence / limitations | Disposition |
+| --- | --- | --- |
+| `aging.js`: `patchDripStains`, `patchRust`, `patchDust` | 11 tests; gravity-oriented, seeded, multi-tone masks are already implemented. GPU rust is a metallic stain; local mask does not control BRDF. Live strength does not undo global roughness. | **P1:** local dielectric/roughness/normal masks. Preserve spatial logic and explicit sill `from`. |
+| `building.js`: `block`, `casement`, `cottage`, `tower`, `roofClutter`, `cityFabric` | 34 tests cover real openings, reveals, glazing, anchoring, dormers, budgets and district layout. GPU cottage/block geometry reads clearly. Roof remains a smooth mottled terracotta sheet; wall structure inherits generic material shortcomings. | **P2:** tile/shingle relief and intentional construction details. Keep opening, placement and merge architecture; improve underlying materials first. |
+| `finish.js`: `patchTranslucency`, `patchIridescence` | 13 tests including real chained shader compilation. GPU thin shell lights successfully; film produces coloured interference-like regions. Iridescence is an analytic light/colour approximation, not a proper layered physical coating, and documentation recommends reducing metalness to make it visible. | **P2:** evaluate Three Physical iridescence/coating support for reflective metal, keep the current lightweight thin-transmission option. Add shadow/occluder and angular tests before stronger physical claims. |
+| `materials.js`: 16 opaque preset factories; `water`, `glass`; `noiseTexture`, `weather`, `tint` | 11 tests verify cache, colours, tiling and dielectric flags. GPU palette exposes missing material-specific structures. Repeat/bump and shader-clone defects reproduced. Glass uses alpha transparency; the water helper is a simple legacy surface. | **P1:** targeted structured materials and option/composition fixes. Preserve caching. Do not confuse legacy `water()` with the richer ocean/stream modules. |
+| `neon.js`: `makeNeonTube`, `patchNeonSpill`, `makeLightTrails` | 16 tests, tube transport frames, time-driven gas variation and depth-pass exclusions exist. Source fixture's tubes were hidden behind its wall; baseline staging corrects that. Spill has the nonuniform-normal bug. Animated factories expose legacy `tick`, not the newer `update`/owned-dispose contract. | **P1 shared normal fix; P2** lifecycle aliases and owned cleanup. Keep tube geometry and colour budgeting unless matched visible renders justify changes. |
+| `roadway.js`: `patchRoadSurface`, `patchSeamBand`, `patchTracks` | 13 tests establish lane frame, filtered grain, bounded seams and track direction. GPU road remains flat shaded lanes/streaks, with no rut/aggregate normal relief. All patches use global roughness. | **P1:** physically coupled local damp/rut/aggregate masks and normal relief; retain road-coordinate framing. Geometry displacement should be optional and bounded. |
+| `rock.js`: `makeRock`, `makeRockField` | 6 tests cover closed topology, determinism, concavity, disposal ownership and GPU pixels. Current source already includes multi-scale fractures and subdued mineral shading from the prior refinement. Some broad faces still read as processed polygons; high detail can be expensive. | **P2:** lower-cost LOD/prototypes, edge/chip hierarchy and geologically coherent fracture sets. Preserve current closed shell, size/burial and owned cleanup; do not restart with a noisy sphere. |
+| `sand.js`: `makeSandTerrain` | 5 tests; asymmetric dunes, directional analytic ripples, grains, actual-triangle height sampling and owned cleanup already exist in current source. Dunes are static, fairly coherent parallel ridges. | **Keep core. P2:** optional multi-direction dune fields and sheltered deposition, with meaningful geometry variation. No new sampling repair is needed here. |
+| `signage.js`: `loadHelvetiker`, `makeText` | 9 tests; shipped local font, extruded/bevelled geometry, darkening-only colour variation, actual glyph shadows and practical lighting. Labels rendered successfully in the material baseline. Resource lifetime remains caller-managed. | **Keep first phase. P2:** idempotent owned disposal and optional material-safe text variants if integration needs them. A font-loader rewrite or cosmetic recolouring is not justified. |
+| `strata.js`: `patchRockStrata`, `patchErosionStreaks` | 13 tests; nonperiodic beds, tilted altitude frame, fall-line erosion and anti-aliasing are implemented. GPU strata/erosion have useful colour structure but largely look painted over the coarse cliff. Erosion globally polishes the surface. | **P1/P2:** local washed-region roughness and bounded relief tied to existing masks. Keep nonperiodic stratigraphy, filtering and fall-line logic. |
+| `surface_wear.js`: `patchMicroBreakup`, `patchEdgeWear` | 11 tests including instance positions, physical curvature scale and filtering. Microbreakup is useful. Hard-face edges are not recoverable from smooth curvature derivatives; scalar polishing changes unworn areas. | **P1:** local finish/substrate response and supported curvature/edge inputs. Keep scale-aware anti-aliasing. |
+| `terrain.js`: `ground`, `cliff` | 8 tests; real displaced geometry, shared-material isolation and connected cliff ribbon already exist. Sampling mismatch reproduced. Default missing PRNG silently creates a constant lattice despite documentation saying required. Cliff strata changes can be abrupt and its base mesh has no thickness/back. | **P1:** exact triangle sampling and explicit input handling. **P2:** cliff depth/edge closure options and improved multiscale terrain; preserve authored origin. |
+| `terrain_shade.js`: `patchTriplanar`, `patchSlopeSplat` | 11 tests; UV-free world projection, slope/altitude gating, patch composition and snow opt-in work. Only albedo changes; grass, scree, rock and snow share the substrate's normal/roughness response. Shared normal-transform defect changes classification under scale. | **P1:** central transform repair and coupled per-zone physical channels. **P2:** optional texture triplets/normal blending instead of only procedural colour. |
+| `urban.js`: `patchCurtainWall`, `makePowerLines`, `makeBillboard` | 11 tests. True catenary cables, pixel-width filtering, poster texture and optional practical spill are present. GPU curtain wall looks like a flat grid with synthetic sky colours; this is a distant-facade approximation. Billboards are bright even in the day fixture with `lit:true`; current `ambient` is author-supplied. | **P1 shared normal fix; P2** richer close-facade roughness/reflection variation, lifecycle ownership, viewport updates. Keep catenary and filtered cable rendering. |
+| `windows.js`: `patchWindowInteriors`, `makeNightWindows` | 13 tests; room-box parallax, stable room hashes, occupancy, furniture/blinds and pane size gates exist. GPU window room depth is visible. Real glass thickness/refraction is not provided. Cloning shared facade material can remove earlier patches. | **P1 composition contract; otherwise keep. P2** interior atlas/room variety and optional physical foreground glazing. Avoid replacing effective far-view parallax with thousands of interior meshes. |
+
+## New capabilities with a distinct purpose
+
+1. **Fractured ice:** a closed, locally transformed mesh with seeded crack planes, frost/clear-ice masks, physical absorption/transmission and a bounded internal-scattering approximation. It fills a missing material/geometry family. Validate silhouette, topology, background distortion, thickness response and offscreen limitations.
+2. **Geometric snow caps and drifts:** complement existing `accumulation.patchSnow`, which is a surface patch, with actual overhang/ledge accumulation and a sampler. Reuse snow masks and shared wind inputs rather than adding a second colour-only snow shader. Test grounding, cap thickness, directional accumulation and disposal.
+3. **Projected surface marks:** a reusable decal API for cracks, paint loss, puddle boundaries, markings and localized stains, with metre scale, normal/roughness contribution, controlled depth bias and resource ownership. This supplies authored locality that world-noise patches cannot express. Reuse existing road tracks rather than duplicate them.
+4. **Cooling lava/crust:** a bounded animated flow surface with real crust plates or displaced lobes, emissive fissures, temporal crust formation and restrained heat shimmer. Useful after shared material channels are correct; clearly distinguish the visual approximation from fluid/thermal simulation.
+
+For this work window, structured masonry/fabric plus correct local weathering should precede adding four unrelated new modules. Fractured ice is the strongest independent new effect candidate; geometric snow is a compatible second candidate if the accumulation owner agrees.
+
+## Validation plan for the coordinated implementation
+
+- Keep these baseline workspaces fixed and render matched cameras after one library change at a time.
+- Add nonuniform object/instance scale equivalence checks to the shared normal code and direct-copy users.
+- Compare source height/face samplers against actual triangle raycasts at interior points, including low resolution.
+- Exercise roughness/metalness mask response with coverage zero/full and a moving highlight; do not merely inspect generated GLSL text.
+- Add true material structure tests: brick course dimensions/mortar, cobble boundaries, weave direction, filtering and tiling.
+- Retain all existing topology, determinism, cache, palette, authored-origin and disposal tests unless an explicitly changed contract makes a test obsolete.
+- Add final-frame tests for reused compile fixtures where geometry was previously occluded, especially neon.
+- Record construction cost, draw calls, triangles, GPU time and retained resources for any new instanced or transmissive effect. Compilation alone is not a quality verdict.
+
+No model calls were made. Implementation ownership and any shared shader/API changes require coordination with the root task before editing modules.
+
+## Coordinated implementation checkpoint: 08:10 UTC
+
+The read-only baseline above remains frozen. The authorized implementation now fixes the following existing contracts:
+
+- Rust, dust and drip deposits use their own coverage for roughness and dielectric metalness. Rust has multiscale corrosion islands and millimetre surface-gradient relief, filtered by pixel footprint. Clean substrate and live strength zero retain the original optical values.
+- Micro breakup, edge polish, road ruts, gutters, collected grit, pressed tracks, erosion runs and curtain-wall glass now modify their local roughness masks rather than the entire material. Curtain mullions keep their substrate finish.
+- Roadway, neon spill, windows and curtain walls use the shared inverse-transpose normal helper. Other world-surface patches inherit the corrected shared helper.
+- Brick has offset courses, mortar and chipped bevel height; cobble has seeded irregular stone cells and recessed sediment; fabric has alternating over/under yarn relief. The structured height and roughness map are linear data, separate from sRGB albedo. All material textures now use linear filtering and mipmaps. These remain UV materials: authors control physical tile scale through UVs/repeat; they are not geometry displacement or a replacement for foreground masonry meshes.
+- Texture repeat preserves `bump: 0` and custom bump maps. Tint, weather, ground and night-window cloning preserve registered Astra shader patches and typed independent uniforms while borrowing texture identities. Cache keys track source material version.
+- Ground and cliff placement samplers interpolate the actual rendered triangles, including off-vertex positions and transformed parents. Flat cliffs no longer produce nonfinite vertex colors.
+- Building factories, roof furniture, text, neon, light trails, power lines, billboards, terrain and cloned night-window materials expose idempotent cleanup of construction-owned resources. Cached materials, borrowed textures, supplied materials and later attachments remain alive. Animated neon/power-line/billboard helpers expose `update` alongside the existing `tick` alias.
+- Rock and sand now register their normal relief through the shared normal hook, so patch-preserving clones retain that relief too. Their closed rock topology and exact sand sampler remain intact.
+
+The 15-module test set now contains **196 tests**. The combined run passed 195 and exposed one old normal-spelling assertion in `test_terrain_shade`; updating it to the shared helper made its complete 11-test file pass. All changed Python tests pass Ruff. Tests added here cover off-vertex raycasts, zero-relief finiteness, shared resource ownership, material map registration, weave ordering, filtering, disabled/custom bumps, typed shader cloning and actual GPU optical factors.
+
+The GPU rust probe found 5,388 covered and 9,365 uncovered pixels: every covered pixel became rougher, uncovered roughness stayed at 0.2, and metalness equaled one minus coverage within one 8-bit level. Setting strength to zero restored the base factors within the same tolerance. The complete shader compiled with pre-existing bump and normal maps as well.
+
+Matched 1440 × 810 renders now live under `/tmp/graphics-seven-hour/after/surfaces/`, using the same baseline scene code and cameras. All ten frames across the palette/weathering/terrain, architecture, finish and neon studies rendered on the GPU with zero shader or console errors. These images were inspected. Masonry structure is now visible; larger architectural massing and the legacy generic wood/granite presets still have the limitations described above. The images are diagnostic fixtures, not a claim that a cube palette is a finished environment. A composed ice/shoreline study follows as the approved new capability.
+
+
+## Existing-family freeze: 09:20 UTC
+
+The coordinated surface pass is frozen for review under `/tmp/graphics-seven-hour/surfaces-final/`, with source hashes and a compact `validation.json`. It reuses the original palette, architecture, finish and visible-neon fixture scenes and cameras. All ten 1440 × 810 frames rendered on the real GPU with zero console or shader errors and were visually inspected. The complete owned test set now passes **208 tests** (199 existing-family tests and nine ice tests), and Ruff passes.
+
+Additional work after the earlier checkpoint:
+
+- `roadway.js` supplies filtered metric normal relief for aggregate, wheel ruts, seam grit, pressed tread and raised track rims. Each fine octave fades by its own wavelength. Repair masks use ordered `smoothstep` edges. The GPU regression measures perturbed normals, exact restoration at live depth zero and preservation of an existing normal map. This is normal relief; silhouettes and collision meshes remain unchanged.
+- `terrain_shade.js` filters each procedural octave by pixel footprint. Triplanar mineral shading now has `relief` in metres (default 0.002, zero disables) and `roughness` (default 0.86). Slope splats use independently configurable grass/scree/rock/snow roughness and dielectric metalness. A GPU readback verifies the actual zone values after both patches compose. Shared transformed normals remain the basis for zone classification.
+- `materials.js` adds coherent longitudinal wood grain, bent growth rings and seeded knots to weathered and painted wood, with matching linear height and roughness. Grain follows UV +V. Painted relief is smaller than weathered relief; default bump heights are 0.0015 m and 0.006 m. The structured brick/cobble/fabric/wood maps are now 512 square with mipmaps. Contrast, grain scale and streak options affect this path, and explicit external color maps do not acquire unrelated procedural mortar. Tests check weave ordering, grain anisotropy, texture seams, cache sharing, option behavior and custom map preservation.
+- `aging.js` separates corrosion islands, centimetre flakes and filtered millimetre grain; the coarse pixel-sized rust relief exposed by a close cylinder study was reduced. The original coverage, clean-substrate optics and strength-zero guarantees remain tested.
+
+Final disposition of the original 15 modules: `aging`, `building`, `materials`, `neon`, `roadway`, `rock`, `sand`, `signage`, `strata`, `surface_wear`, `terrain`, `terrain_shade`, `urban` and `windows` received the fixes above or the earlier ownership/transform/composition fixes. `finish` retains its working lightweight effects and explicitly remains an optical approximation; its matched GPU scene and complete tests passed. None of these effects is declared physically exact. The earlier per-module table retains the remaining limitations, including distant facade approximations, flat patch silhouettes and unmodelled architectural construction detail.
+
+A composed workshop study lives at `examples/graphics_lab/scenes/workshop.js` and `/tmp/graphics-seven-hour/workshop-study/`. Four close and wide GPU views expose real masonry scale, cloth, aligned board grain, worn metal, pavement and road response. Its previous structured-material snapshot remains at `/tmp/graphics-seven-hour/workshop-structure-before/`. The study revealed that a flat cobble material cannot provide foreground stone silhouettes or contact; a separately scoped geometric paving capability is approved next rather than increasing bump amplitude.
+
+## New capability: fractured freshwater ice
+
+`ice.js` exports `makeFracturedIce`. Each seeded cell is a closed, bevelled volume with a nominal local upper surface at zero, variable thickness, optional heave, a physically transmissive material, filtered frost and stress cracks, and true instanced air lenses inside the solid. Authored convex outlines are supported. `userData.sampleHeight(x,z)` queries actual Float32 upper triangles and returns null in fissures or outside; `update` is static, and disposal releases only construction-owned geometry, materials, instances and the optical texture.
+
+The shared fracture deformation runs before gaps are opened. A floe is shrunk toward a point inside its polygon visibility kernel, so neighboring outlines fit and subsequent side-ring cuts remain inward. This corrected an overlap defect that closed-manifold checks alone missed. The regression covers twelve seed/gap combinations down to 2 mm, in addition to closed topology, positive volume, determinism, transformed raycast agreement, internal-air containment, input validation, resource ownership and GPU compilation. An actual checker transmission render verifies thickness-dependent colored absorption and reduced background contrast through frost.
+
+The composed frozen-shoreline study is `examples/graphics_lab/scenes/ice.js`, staged at `/tmp/graphics-seven-hour/ice-study/`, with three fixed 1440 × 810 views. A previous visual checkpoint is preserved at `/tmp/graphics-seven-hour/ice-study-v1/`. Root independently reviewed the updated sheet, submerged objects and shoreline as suitable for integration. The pressure ridge is now visibly tilted and seated against a frost-covered lower floe and the main sheet, using actual transformed vertex contact. All three final GPU views are clean and visually inspected; the immutable source/image snapshot is `/tmp/graphics-seven-hour/ice-final/`.
+
+Limits: optical path uses local top/bottom thickness and an estimated floe width on side faces, not an exact exit intersection. Three transmission sees the opaque scene and does not recursively trace transparent water or another ice volume. The fracture network is a seeded visual model, not a mechanical fracture simulation; very small degenerate chips can be omitted. The exposed pressure slab still has a broadly flat top and geometric fracture bands, and frost distribution could gain finer directional crystal structure in a future polish pass. Large bubbles are individually instanced geometry; at the shoreline study's chosen area/density, the main ice group represents about 174,000 triangles including its air lenses, in two meshes. The complete scenic fixture, including terrain and many unique rocks, is about 805,000 triangles; its observed 130–211 FPS range on the RTX 5090 Laptop GPU is environment-specific, not a portable performance guarantee.
+
+## New capability: geometric paving
+
+`paving.js` exports `makePaving({size, stoneSize, pattern, joint, thickness, relief, seed, color, jointColor, roughness, moisture, name})`. `pattern` selects irregular cobbles or staggered rectangular setts. Units are metres; the nominal walking surface is local y=0, its underside is `-thickness`, and `relief` varies stone height and tilt. The returned named Group has two merged meshes, a static `update`, idempotent construction-owned `dispose`, and `sampleHeight(x,z)` over the exact Float32 upper triangles and recessed joint bed. Queries outside the rectangular patch return null. Requested density is bounded at 4,096 stones by making oversized patches coarser; this is foreground geometry, not a terrain streaming system.
+
+Every stone is a closed solid with trimmed corners, cut bevels, minor chipped edge variation, an intrinsic crown and restrained seeded color variation. The gap is formed by inward clipping of disjoint cells; corners and subsequent rings remain inside their stone footprint. The initial rendered version looked soft and pale, so the accepted version reduced crown/bevel width, retained cut-face normal discontinuities and used a darker mineral base. Fine normal grain fades with pixel footprint. Moisture darkens the albedo and lowers roughness together while metalness remains zero; this is a damp stone finish, not a reflective puddle layer.
+
+Matched evidence is preserved at `/tmp/graphics-seven-hour/workshop-paving-before/` and `/tmp/graphics-seven-hour/paving-final/`. The earlier rounded-stone iteration is `/tmp/graphics-seven-hour/workshop-paving-after-v1/`. The same four 1440 × 810 cameras show the material-only yard before and the real stone yard after. The only accompanying assembly correction was marking authored mounted parts as free placement: the runtime had lowered the wall sign backing by 0.251 m and one interior timber by 0.17 m. The final fixture reports zero automatic placement moves. All four final views were inspected. Dry/wet cobble/setts diagnostic panels are additionally rendered and inspected under `/tmp/graphics-seven-hour/paving-variants/`.
+
+Eight focused tests cover closed positive-volume stones, bounds, deterministic geometry/color, noncrossing footprints, exact raycast sampling through stones and joints under nested transforms, owned cleanup, bounded construction, actual GPU compilation with fog/shadows/normal maps/cloned patches, and GPU optical-channel readback. The moisture probe verifies roughness changing from approximately 0.84 to 0.30, an albedo multiplier near 0.63 and zero metallic response. A particularly useful regression exposed Three's transformed bounding-sphere underestimate under shear: direct local triangle intersection agreed with the sampler, but the world raycast skipped a real stone-edge hit. Paving uses conservative sphere radii to avoid that early cull while retaining exact bounding boxes.
+
+The workshop's 6.9 × 11 m patch contains 1,334 stones and 124,588 triangles in two meshes, using about 3.09 MB of geometry arrays. One measured Node construction took 138 ms; 10,000 height queries took 13 ms. The complete workshop rendered 225–269 FPS on the RTX 5090 Laptop GPU, with 128 draw calls and 147,128 triangles, no shader/console/update errors. These are hardware-specific observations. The final complete owned test run passes **216 tests**: 199 existing-family tests, nine ice tests and eight paving tests. Python test lint passes.
+
+Remaining limits: this is cut-stone paving with a generic procedural mineral finish, not a scan library or a geology simulator. Rectangular patches do not yet conform to arbitrary curved paths or a caller-provided heightfield, and wetness supplies no standing-water optics. The workshop is a composed material study; its simplified building envelope, flat UV brick faces and procedural rust grading remain visible and are not presented as a finished photoreal environment. The original fifteen-module audit and matched fixtures remain frozen independently of this added capability.
diff --git a/harness/docs/graphics_audit_weather.md b/harness/docs/graphics_audit_weather.md
new file mode 100644
index 00000000..7f99db4f
--- /dev/null
+++ b/harness/docs/graphics_audit_weather.md
@@ -0,0 +1,125 @@
+# Weather, water, and light effects audit
+
+> Historical working notes from the development snapshot (2026-09-23). The per-module test files
+> and case counts cited below were folded into `tests/scene_runtime/lib/test_library.py` when the
+> library landed on main (D96, D97); `/tmp/...` evidence paths are from that session and are not kept.
+
+Audit owner: water_library. Baseline captured 2026-09-23, starting 07:27 UTC. The initial findings below describe the preserved baseline. The implementation ledger at the end records subsequent changes and distinguishes completed work from the remaining proposals.
+
+## Evidence and method
+
+The source snapshot, matching test files, executable lighting probe, staged scenes, original PNG frames, and render metrics are under `/tmp/graphics-seven-hour/baseline/weather/`. The snapshot contains the complete library to make every scene reproducible. The two kinds of scenes are deliberately separated:
+
+- `fixtures/<module>` renders the module's existing shader fixture. These primarily establish compilation and basic behavior; several fixtures have black backgrounds or no environment and are unsuitable for judging final composition.
+- `representative/<case>` adds controlled daytime or night lighting, a physical sky, an environment, and useful geometry. `surface_patches` compares individual material effects on a floor, box and spheres; `cloud_sky` exposes distant cloud silhouettes; `rain_shelter` exposes rainfall around and underneath a roof; `heat_shimmer` provides a structured background.
+
+Renders use the actual production GPU host with its default postprocessing, 960 × 600, absolute times 0 and 1.5 seconds. Metrics identify the RTX 5090 Laptop GPU through ANGLE. The image `audit-contact.jpg` is an overview, not the sole evidence: individual images were also inspected. Initial staging failures from symlink restrictions and unexpanded fixture `__FOG__` tokens were corrected in temporary staging; they were not library failures. The completed renders have no console or shader errors. The 15 corresponding test files pass: **182 tests in 23.90 seconds**. This does not establish visual realism. The final evidence inventory contains **46 PNG frames across 14 staged render scenes**, with hashes in `manifest.json`.
+
+Priorities: **P1** is a clear visual or correctness defect worth addressing in this work period; **P2** is a useful improvement with a functioning existing implementation; **P3 / retain** means no immediate replacement is justified by the inspected evidence.
+
+## Module findings
+
+| Module | Public exports | Evidence and current strengths | Main limitations or defects | Priority and concrete proposal |
+|---|---|---|---|---|
+| `accumulation.js` | `patchSnow`, `patchSand` | `representative/surface_patches/renders/snow_t0.png`, `sand_t0.png`; slope, wind and curvature masks work and preserve the underlying material outside their masks. Seeded patterns and distance filtering are already present. | Snow reads as blue marbling on a flat coating; it creates no thickness or silhouette. Both effects change material-wide roughness despite local coverage. Snow thaw and sand height are anchored to the world origin, which is useful only when explicitly understood. | **P2.** Improve snow luminance and granular breakup, add masked roughness/normal treatment using existing patch hooks, and document coating-only geometry. Add a separate optional snow-cap mesh API only if geometric deposits are prioritized. |
+| `atmosphere.js` | `makeHeightFog`, `patchAerialPerspective` | `fixtures/atmosphere/renders/a_t0.png`; Beer extinction per sheet correctly avoids constant-opacity near fog. Terrain-following sheets and depth-prepass exclusion are already implemented. | Fog is 20 horizontal surfaces, not a continuous volume: oblique/inside views and intersections can reveal layers. Scene lighting is read only at construction; hidden lights are included and directional targets/parent transforms are ignored. Aerial perspective modifies albedo before lighting, so it does not represent final-radiance scattering. | **P1 correctness, P2 appearance.** Use visible world-space light directions, define refresh behavior, and retain the cheap height-fog mode. A depth-aware analytic or bounded raymarched fog option would be a genuine new capability; do not claim the existing sheets are volumetric ray integration. |
+| `caustics.js` | `patchCaustics` | `representative/surface_patches/renders/caustics_t0.png` and time 1.5; connected moving light webs cross floors and curved geometry, with Snell direction shift, depth extinction and antialiasing. This is one of the stronger existing effects. | Emissive caustics are procedural projection, independent of an actual water surface and scene occluders. They can illuminate a surface even when the source path is blocked. The pattern and hue breakup are artistic rather than a focused-ray solution. | **P3 / retain core.** Keep the useful lightweight projector, document its unoccluded/procedural scope, and consider a shadow-aware opt-in if a pool showcase demonstrates the need. Do not replace it merely to increase effect count. |
+| `celestial.js` | `makeHeatShimmer`, `makeStars`, `makeAurora` | `representative/night_sky/renders/night_t0.png` and `representative/heat_shimmer/renders/heat_t0.png`; actual framebuffer distortion exists, and seeded sky fields animate. | Aurora has conspicuously uniform narrow vertical bars and a repeated wavy curtain hem. Shimmer's framebuffer/texture are hidden in a closure with no final teardown; target dimensions are taken from drawing-buffer size rather than the active render target. A color-only distortion cannot reject foreground sampling. | **P1 lifecycle/RTT correctness; P2 aurora.** Expose owned-resource disposal, use current-target dimensions and restore GL bindings safely. Make aurora ray spacing, lengths and curtain luminosity less regular. Preserve truthful color-only distortion limitations. |
+| `clouds.js` | `cloudTexture`, `makeClouds`, `makeCirrus` | `representative/cloud_sky/renders/clouds_t0.png` and `clouds_side_t0.png`; inexpensive instanced layer, directional rim response and bounded haze. | Cumulus appear as repeated gray outlined discs; clusters do not produce convincing volume or internal shadow. Cirrus are stretched versions of the same puff, producing conspicuous horizontal parallel lines. Billboards change their apparent body with camera orientation; no true volume or light transmittance. | **P1 visual.** Reduce the uniform perimeter highlight, generate non-identical billowy density masks, and give cirrus its own filament field. Highest-value new capability: a separately named bounded cloud volume with raymarching, extinction and self-shadowing, with explicit performance tiers. |
+| `damp.js` | `patchMoss`, `patchMoisture`, `patchCrackedMud` | `representative/surface_patches/renders/moss_t0.png`, `mud_t0.png`, `shore_t0.png`; directional moss placement and a coherent moisture apron already work. | Moss is a sparse flat green coating at close range. Mud has extremely dark, relatively uniform-width graphic outlines without actual curl/normal relief. Roughness changes affect the whole material. Moisture reach is world-Y height, not distance from a shoreline. | **P2.** Add pixel-filtered micro-normal and masked roughness; reduce the uniform crack outline and derive lip normals from the existing cell border. Retain the height-based moisture API but keep its meaning explicit. |
+| `godrays.js` | `makeGodRays` | `fixtures/godrays/renders/a_t0.png`; several beams read as solid illuminated tubes. Shaft/pool/mote intensity budgets and depth-prepass exclusion already exist. | Confirmed source-space mismatch: `vN` uses `normalMatrix` (view space) but `eye` is `cameraPosition - vW` (world space) before `astraFacing`. No scene occlusion clips a beam; a floor pool assumes the local ground plane. Geometry is a shell with approximate chord weighting, not a scattering volume. | **P1 correctness and visual.** Correct the coordinate space first and compare identical views. Then soften/unstructure the beam cross section and expose an optional authored blocker/length constraint; a separate shadow-aware volume is larger work. |
+| `rain.js` | `makeRain`, `splashTexture`, `makeSplashes`, `wetten`, `makePuddle` | `representative/rain_shelter/renders/rain_shelter_t0.png`, `under_roof_t0.png`; streaks, surface-oriented splash atlases, and real animated puddle geometry are available. Splash placement already raycasts caller-provided static surfaces. | Falling streaks do not stop at roofs/terrain; impact phases are independent of the visible falling drops. Impact positions stay baked when receiving objects move. Rain uses world camera coordinates inside a model-space vertex path. `makePuddle` updates every vertex and recomputes normals on CPU; amplitude zero divides color calculation by zero (executable probe: all 2,352 color components become nonfinite). | **P1 finite/transform correctness; P2 coherence.** Fix zero-amplitude and coordinate contracts. A valuable new rain-field API can couple deterministic trajectories to a static terrain/roof height map and synchronize impact births; retain the cheaper existing layers. Bound moving-collider support honestly. |
+| `sky.js` | `SKY_GRADE`, `nightAmount`, `afterglowAmount`, `lowSunAmount`, `skyRadiance`, `makeSky` | Day `cloud_sky`, night `night_sky`, and existing CPU radiance tests; the graded physical sky is a sound base and shares conventions with `sunRig`. | Creation clones a direction and derives twilight uniforms once: changing a rig later does not update the dome, and changing only `sunPosition` leaves derived twilight terms stale. Dome/environment mismatch is possible when custom sky parameters are used without rebaking the environment. | **P3 / retain appearance; P2 API.** Add an explicit update-sun setter that recomputes all derived terms, plus clear instructions for environment refresh. A wholesale atmospheric-scattering rewrite is lower value than cloud/fog repairs in this time budget. |
+| `submerged.js` | `patchUnderwater`, `makeRainRings`, `patchThinIce` | `representative/surface_patches/renders/caustics_t0.png`, `ice_t0.png`; depth- and view-path extinction, procedural rings, and branching ice cracks are implemented. | Underwater extinction partly edits albedo and adds emissive veiling, without refracted scene depth. Ice looks like bright painted fractures on every shape; no interface thickness/refraction or change of silhouette. Rain rings are color overlays rather than displacement/reflection-normal changes. | **P2.** Preserve the useful absorption patch, add masked normal/roughness for ice, and offer ring normals to appropriate water materials. A real shallow-water transmission API already exists in `stream.js`; avoid duplicating it under another name. |
+| `veils.js` | `makeRainVeil`, `makeSnowfall`, `makeMotes` | `fixtures/veils/renders/a_t0.png`; deterministic snow tumble/drift and a separate distant-rain layer exist. | Rain curtain visibly exposes a straight rectangular lower edge and a regular diagonal comb. Lighting traversal includes lights below hidden ancestors; the 15-frame cache and early return when no lights remain leave stale illumination. Snowfall is not missing, but terrain/roof collision and accumulation coupling are. | **P1 veil and lighting.** Fade every card boundary, break up filament spacing, and fix visibility/reset behavior with tests. Keep snowfall/motes unless composed close views reveal further problems. Geometry-aware precipitation is more useful than a second snowfall constructor. |
+| `water.js` | `makeWaterNormals`, `BROADBAND_EXTENT_M`, `makeOcean` | `fixtures/water/renders/graze_t0.png`; inexpensive normal-animated planar water with real RTT reflections remains useful for calm pools/ponds. | Lights are sampled only once. Executable probe records `keyColor.r=1.2732395` both before and after removing the light. Hidden ancestors are ignored. `_oceans` is process-global and never decremented, causing misleading cross-scene warnings. No owned-resource disposal contract. The plane has no wave geometry; Phong glints and scrolling normal/color fields are not the newer ocean model. | **P1 lifecycle/light correctness; P3 retain visual niche.** Repair dynamic scene reading and resource ownership without replacing the API. Direct displaced-sea users to the already improved `ocean.js`; do not make legacy `makeOcean` silently become a heavy ocean simulator. |
+| `watermist.js` | `makeWaterMist`, `makeSpray` | `fixtures/watermist/renders/a_t0.png`; broad drifting mist, ballistic spray trajectories, and terrain/flow options already exist. | Mist cards can merge into a milky solid bank with no depth-aware soft intersections; source color/lighting are authored rather than live scene irradiance. Spray is deterministic visual ballistics without fluid collision. No returned disposal helper. | **P2.** Add owned-resource teardown, soften card/ground intersections within available information, and tune density under a composed waterfall or stream. A spray solver is not necessary to improve the useful visual effect. |
+| `waterside.js` | `patchShoreWet`, `patchShoreFoam`, `patchShallowWater` | `representative/surface_patches/renders/shore_t0.png`, `shallow_t0.png`; composable waterline wetting and explicit shallow-color grading exist. | Foam can appear as pale vertical stripes on curved shore objects. Wet roughness applies globally. Shallow water reduces an arbitrary `bedAt` callback to a single best-fit plane, then adds noise: channels and local shoals cannot be represented. Color grading alone supplies no transparency or refraction. | **P2.** Use local wet masks for roughness, less directional foam breakup, and an optional sampled height texture for nonlinear bed depth. Preserve current planar fallback and describe it accurately. |
+| `wetground.js` | `makeMirrorFloor` | `fixtures/wetground/renders/a_t0.png`; real reflected object and a rough dirt overlay establish a useful wet-ground base. | Reflection blur is a fixed five-tap vertical screen-space smear; ripple field is static. World normal uses `mat3(modelMatrix)` rather than inverse transpose. Reflection and generated maps have no owned disposal entry point. A second reflector conflicts with other RTT water surfaces. | **P1 ownership/normal correctness; P2 appearance.** Add teardown and correct normals; improve roughness-dependent filtering and optional time-driven rain ripples. Preserve the documented one-reflector constraint unless shared runtime recursion is deliberately addressed. |
+
+## Bounded priorities for the seven-hour work period
+
+1. Repair clear correctness and ownership defects first: hidden/removed light handling, godray coordinate mismatch, zero-amplitude puddles, framebuffer lifetime and active-target sizing. Add behavioral regressions rather than tests that only search shader strings.
+2. Improve the conspicuous existing cloud and rain-veil appearance against the preserved views. Their silhouettes are larger realism failures than missing tiny details elsewhere.
+3. Add one substantial **cloud volume** capability with a stable local-coordinate box, deterministic noise, Beer extinction, sun transmittance, a bounded ray budget and owned-resource teardown. Keep the current distant-cloud option for cheap background use. Explicitly state that this is prescribed density, not weather simulation.
+4. If the time budget permits, add **surface-aware rainfall** with a static height field and synchronized impacts. Height-field support handles terrain and roofs with a single highest surface per XZ; overhang interiors and moving geometry require stronger collision data and should not be advertised as solved.
+5. Improve material coating realism using masked roughness and filtered normal detail where the existing geometry is already adequate. Do not spend the entire period rewriting all 15 modules, or confuse snow albedo with accumulated snow geometry.
+
+Deferred capabilities with genuine value are depth-aware participating-media lighting and geometric snow caps. Existing snowfall, spray, caustic projection, aurora, stars, rain rings, heat shimmer and puddles should not be relabeled as missing new effects.
+
+## Scope and verification limits
+
+Every assigned module's implementation and corresponding test coverage were inspected for its public API and rendering approach. Existing material patches were additionally exercised together through the real GPU host. Not every parameter combination, transform, reflection interaction or camera-inside-volume case has been exhaustively evaluated. The findings distinguish directly observed images, reproduced runtime behavior and source-derived risks. Temporary source copies and rendered baselines remain outside delivered packages and output galleries.
+
+
+## Implementation ledger — 2026-09-23, 08:58 UTC
+
+The first correctness and visual pass is implemented in source. The baseline folder remains immutable. `weather-refine/existing-matched-v2/` contains the same 14 scene sources/cameras, 960 × 600 dimensions, and absolute times 0 and 1.5: **46 after frames, no shader or console errors**. Only the assigned module files and shared `shader.js`/`lifecycle.js` repairs were replaced in those staged workspaces. `comparison.jpg` places selected original/after views beside one another. Shared normal/depth-pass fixes therefore contribute to these comparisons; they are not evidence for an individual material patch in isolation.
+
+| Module | Implemented change | Behavioral evidence and remaining scope |
+|---|---|---|
+| `accumulation` | Snow/sand roughness and metalness now follow their existing local coverage masks; the authored substrate properties stay intact. | GPU reads of actual `roughnessFactor` distinguish uncovered vertical faces from covered upward faces. Snow remains a color/material coating without geometric thickness; its blue marbling is not yet redesigned. |
+| `atmosphere` | Visible world-space directional-light probing refreshes on rendering; removed/hidden keys reset, authored pins remain respected. Added explicit refresh hook and owned disposal. | Tests change sun parent visibility/removal and target direction after construction. Height fog remains a finite sheet approximation and aerial perspective still operates inside the material patch. |
+| `caustics` | Core retained after inspection. | Existing moving projection remains useful; scene occlusion and water-derived focused rays are not implemented. |
+| `celestial` | Heat shimmer sizes its framebuffer copy from the active render target, restores GL bindings in `finally`, and releases owned GL framebuffer/texture. All factories own disposal. | Stubbed GL tests cover the target-size mismatch, throwing blit and exact cleanup counts. Stars and aurora appearance are retained in this pass; aurora's regular bars remain an open visual item. |
+| `clouds` | Replaced one repeated puff with an eight-variant density/normal atlas, removed the uniform bright ring, and gave cirrus a separate curved filament field. Card edges are transparent; camera/sun basis handles transformed parents. | Matched `cloud_sky` views show the former gray outlined discs replaced by softer lit masses. Public `cloudTexture` preserves white RGB/alpha contract. These are inexpensive distant billboards, not a substitute for the new cloud volume. |
+| `damp` | Moss, moisture and cracked mud apply roughness locally; opaque coatings suppress metalness only where covered. Wetting already polished substrate cannot increase its roughness. | GPU coverage tests verify dry substrate and polished wet surfaces. Moss/cracks remain shader detail without geometric tufting/curling. |
+| `godrays` | Facing attenuation now compares world-space view and normal vectors; owned disposal added. | Identical fixtures lose the incorrect hard-sided strips. Beams are still authored shell volumes without scene occluder integration. |
+| `rain` | Zero-amplitude puddles stay finite. Rain camera/field coordinates now agree under parents. Added an optional roof/terrain shelter atlas; all factories capture owned resources. | Atlas tests cover roofs, ground, transformed parents, camera movement, cache reuse, explicit refresh, hidden/moved source meshes, and caller ownership. GPU pixels verify that a roof cuts the rain field off. Detailed atlas contract follows below. |
+| `sky` | `setSunDirection` refreshes sun position and every derived night/afterglow/low-sun uniform atomically; sky handle and mesh own disposal. | Setter validation and day/night transitions are covered. It updates the dome only; caller-owned scene lights and baked environment still require their own update. |
+| `submerged` | Rain ring factory owns disposal. | Existing absorption and thin-ice patch behavior retained; no new refraction or water-depth buffer is claimed. |
+| `veils` | Rain fades at the lower boundary and has less regular filament spacing. Lighting reads visible objects, resets after removal, and uses a frame-bounded cache. Billboards/camera distance use the correct local basis. | Matched fixture visibly removes the straight clipped lower edge and comb. Hidden-ancestor/removal and transformed-camera tests pass. Snowfall remains visual precipitation without roof collision/accumulation. |
+| `water` | Live visible lighting resets removed contributions; no process-global water-count warning. Owns generated normals, geometry/material and the addon's private reflection target through a narrowly scoped render hook. | Actual GPU render/dispose cycles return texture counts to baseline and restore the renderer method identity. Caller-provided normal textures remain borrowed. This API remains planar calm water; displaced oceans use `ocean.js`. |
+| `watermist` | Owned disposal plus world-facing cards under rotated/nonuniformly scaled/sheared parents; world light/view vectors no longer mix with local density/ballistics. | GPU derivative-normal readback verifies both mist and spray planes under nested transforms. Gravity, flow and height callbacks are local; rotating a spray group rotates its local gravity. No depth-aware intersection or droplet collision solver. |
+| `waterside` | Wet roughness follows the actual wet mask, preserving dry regions of a shared material. | GPU dry/wet samples verify the different finishes. Shore foam and the planar approximation to `bedAt` are unchanged in this pass. |
+| `wetground` | Correct inverse-transpose world normal; explicit disposal of its reflector target, generated maps, geometry and materials. | Lifecycle tests retain caller-added children. Fixed reflection blur and static ripple limitation remain; no shared multiple-reflector integration is claimed. |
+
+All moving factories that previously exposed only `userData.tick(t)` now also expose the identical `userData.update(t)` function: height fog; stars, aurora and shimmer; godrays; rain veil, snowfall and motes; water mist and spray. Lifecycle tests call the actual factory APIs and verify shader time, disposal idempotency and protection of caller-appended children. Patch functions operate on caller-owned materials and do not take ownership of them.
+
+### New bounded cloud volume
+
+`cloudvolume.js` exports `makeCloudVolume(options)`. It returns a local, centered `THREE.Mesh` with `userData.update(t)`, `sampleDensity(x,y,z,t)`, `setSunDirection(direction)` and `dispose()`.
+
+- `size: [x,y,z]` uses local metres; default `[600,180,360]`. `wind: [x,z]` uses local metres/second and absolute time. `seed` controls a periodic 80³ RGBA density texture (2,048,000 bytes before driver allocation).
+- `coverage` and `detail` range from 0 to 1; `density` is extinction per world metre. The local-to-world path metric preserves optical thickness under nonuniform scale and composed shear.
+- `quality: 'low' | 'balanced' | 'high'` selects 40/6, 72/10 or 112/16 view/sun integration steps without changing the underlying field. Secondary sun integration supplies self-shadowing. Beer transmittance accumulates front to back; a bounded multiple-scattering approximation lifts dense interiors.
+- Lighting follows the strongest visible directional light and ambient/hemisphere/environment fill. Hidden/removed lights reset. `sunDirection` pins a world-space direction; the setter supports changes without rebaking density.
+- This is prescribed animated density, not a weather/fluid simulation. It has ordinary transparent-object sorting, no terrain cloud-shadow projection, no scene-shadow-map sampling, no temporal reconstruction, and no scene-depth-aware termination inside its bounds. Opaque geometry wholly in front works through depth testing; opaque geometry intersecting the box can reject the whole cloud fragment. Use separate distant sky volumes.
+
+`examples/graphics_lab/scenes/cloud_volume.js` composes three cloud volumes over a reflected mountain lake. Frozen final source and images are in `weather-refine/cloudvolume-final/`: lake, close cloud, and camera-inside views at 0 and 7 seconds, 1200 × 750, production postprocessing, zero shader/console errors. `cloudvolume-fractal-a/` preserves the earlier density experiment; the selected field replaces visibly smooth ellipsoid clusters with eroded multiscale structure. Tier comparisons use the exact same close camera at `cloudvolume-quality-{low,balanced,high}/`. Two-second host throughput samples were approximately 813/658/519 FPS on the RTX 5090 Laptop GPU; these are scene/device-specific short measurements, not guaranteed performance or mobile budgets.
+
+Five module tests check seeded density bytes, absolute-time replay, CPU/GPU texture sampling agreement, boundary behavior, transformed camera/light transport, hidden/removed lights, all three actual GPU programs, camera-inside rendering, foreground geometry, pixel motion/replay, and GPU 3D-texture cleanup. Exact replay compares rendered bytes, not merely uniform values.
+
+### Optional bounded rain shelter atlas
+
+`makeRain({surfaces, heightAt, groundY, shelterResolution, shelterUpdateDistance, ...})` retains its existing lightweight path when no surfaces/height callback are supplied. `surfaces` are borrowed `Object3D` roots; `heightAt(x,z)` returns a local height or `null`. `groundY` supplies an optional flat local cutoff even without an atlas.
+
+The atlas records the highest receiving height at each local XZ texel. It follows the camera when `follow` is enabled and covers the rain radius plus an update margin. Resolution is bounded to 8–64 per side (default 32): each rebuild uses at most resolution² downward ray queries, whose cost still depends on supplied mesh complexity. It rebuilds initially, after sufficient camera movement, after effect-transform changes, or on the next draw after `userData.refreshShelter()`. Moving, modifying or hiding a source mesh requires that explicit refresh. `userData.shelter` exposes bounds, texel size and rebuild count; `sampleShelterHeight(x,z)` reports cached local height or `null` outside/unbuilt coverage.
+
+The leading edge of each rain streak disappears at the highest roof/ground height. This is a vertical height-field approximation: it does not solve wind entering laterally under eaves, layered overhang interiors, moving-body collisions, or synchronization of visible drops with independently phased splash sprites. Narrow roofs can be missed between texels. The factory disposes its atlas but never source geometry/materials.
+
+`rain-shelter-matched/` preserves the original roof case with only the opt-in shelter configuration added, at its original camera/dimensions/times. `rain-shelter-composed-v2/` is a separate wet courtyard demonstration with a pitched shelter, dry deck and surface splashes. Roof/ground/camera behavior has both CPU and actual GPU tests. The composed deck exposed small regular dark postprocessing dots: they remain with `receiveShadow=false`, remain after both rain and splash objects are removed, and remain without the reflector; they disappear with `--no-post`. Those isolated copies are `rain-shelter-no-shadow`, `rain-shelter-no-effects` and `rain-shelter-no-floor`. This is a shared postprocessing investigation, not evidence that precipitation leaks into the depth pass; the runtime owner has the reproducer.
+
+### Verification and remaining work
+
+The first complete assigned suite passed **200 tests in 8.33 seconds** before the additional cloud pixel and transformed-mist tests. Subsequent focused checks passed all 5 cloud tests, all 16 mist/lifecycle tests, and all 24 damp/waterside/GPU-finish tests. Final integration should rerun the complete suite against the shared renderer and library state. All evidence above was captured through the actual GPU host; tests are supporting evidence, not a replacement for image inspection.
+
+Unimplemented proposals remain unimplemented: geometric snow accumulation; aurora ray irregularity; filtered moss/crack normals; nonlinear shallow-bed sampling; scene-depth-aware cloud/fog intersections; geometry-aware snowfall; synchronized rain-impact births. No claim of comprehensive physical simulation is made. All generated source, comments, example labels and this report are English. Published galleries and delivered packages were left unchanged.
+
+Primary references for the bounded volume design are Guerrilla Games' [Nubis](https://www.guerrilla-games.com/read/nubis-realtime-volumetric-cloudscapes-in-a-nutshell) and [Nubis Evolved](https://www.guerrilla-games.com/read/nubis-evolved), and NVIDIA's [Volume Rendering Techniques](https://developer.nvidia.com/gpugems/gpugems/part-vi-beyond-triangles/chapter-39-volume-rendering-techniques). They motivate density/erosion and transmittance integration; this small implementation does not claim their production feature set.
+
+
+## Second visual pass and final snapshot
+
+The subsequent visual pass changes the items explicitly left open in the first ledger:
+
+- **Snow:** default albedo is nearly neutral, its tonal modulation is narrower, and deep deposits become opaque. Blue shadow color now comes primarily from scene illumination rather than large blue albedo patches. A filtered 0.9 mm height signal perturbs the lit normal without changing geometry. A real GPU albedo test verifies neutrality, adequate brightness and resolved tonal variation.
+- **Aurora:** jittered Gaussian strands replace the hard, evenly spaced strokes. Each strand has its own brightness and upper extent, broader folds modulate the curtain, and the lower boundary fades unevenly. The folded normal uses the shared inverse transpose under parent transforms. This remains a luminous ribbon approximation, not a charged-particle simulation.
+- **Shore foam:** world-anchored triplanar noise replaces projection onto a spatially changing tangent. On a centered sphere the former coordinates collapsed one axis, producing repeated stripe fans. The new field retains variation around the full curved shore; a GPU sampling regression measures that variation. Filtering reduces unresolved bubble detail.
+- **Moss and mud:** filtered local height signals supply small moss/lichen relief and curled mud-lip shading. Narrower mud cracks reduce the thick graphic outlines, with less baked highlight color now that actual normals respond to light. `amount: 0` also removes moss's formerly unmasked damp-rim darkening. These remain surface coatings without silhouette changes.
+
+The final assigned suite passes **203 tests in 8.76 seconds**. It includes all 15 original modules, new cloud volumes, factory lifecycle, transformed particle geometry, and local PBR finish checks. No shader/console errors were observed in the final rendering pass.
+
+`/tmp/graphics-seven-hour/weather-refine/source-final-a/` freezes the complete dependency library plus owned tests and the two new examples. `existing-matched-final/` is the final 46-frame baseline replay at identical cameras, dimensions and times, using one frozen source snapshot throughout; both folders carry SHA-256 inventories. The earlier `existing-matched-v2`, `detail-before`, `detail-v2-night_sky`, and `detail-v4-surface_patches` folders remain available to separate the first and second visual passes. The original baseline stays unchanged.
+
+Still deferred: geometric snow accumulation; nonlinear shallow-bed sampling; scene-depth-aware cloud/fog intersections; geometry-aware snowfall; synchronized individual rain-impact births. The cloud/shelter composed scenes remain separate from the matched fixture evidence. Shared renderer investigations and later root integration should preserve these snapshots rather than overwrite them.
diff --git a/harness/examples/graphics_lab/.gitignore b/harness/examples/graphics_lab/.gitignore
new file mode 100644
index 00000000..fd6aad7f
--- /dev/null
+++ b/harness/examples/graphics_lab/.gitignore
@@ -0,0 +1,2 @@
+output/
+__pycache__/
diff --git a/harness/examples/graphics_lab/README.md b/harness/examples/graphics_lab/README.md
new file mode 100644
index 00000000..8eda97f6
--- /dev/null
+++ b/harness/examples/graphics_lab/README.md
@@ -0,0 +1,189 @@
+# Graphics Lab
+
+See [validation results and actual model trials](VALIDATION.md) for measured
+checks, rendered artifacts and remaining limitations.
+
+Sixteen executable studies of fire, water, terrain, vegetation,
+atmosphere, worked materials and independent shader files, plus three GPT-6 Luna cases.
+All images and films come from Three.js scene code;
+there are no prerendered backgrounds or generated image assets.
+
+From the `harness/` directory:
+
+```bash
+python examples/graphics_lab/build.py --out /tmp/graphics-lab-v2 --render --video
+python examples/graphics_lab/verify_media.py --out /tmp/graphics-lab-v2
+node examples/graphics_lab/check.mjs --out /tmp/graphics-lab-v2
+node examples/graphics_lab/serve.mjs --out /tmp/graphics-lab-v2
+```
+
+Open the loopback URL printed by the server. The gallery offers H.264 films,
+full-resolution stills, and live orbit controls with authored camera presets,
+pause and time scrubbing. Everything, including Three.js, is served locally.
+Opening `index.html` as a `file:` URL does not load browser ES modules; use the
+server. The default output is `examples/graphics_lab/output/` (git-ignored).
+
+`--case fire` selects one case to render again; the gallery still includes all
+nineteen entries. Repeat `--case` to select several cases. `--width 1920 --height 1080`
+increases capture resolution. `--seconds 6
+--fps 24` controls the film. Video export requires ffmpeg, either on PATH or
+provided by an installed `imageio-ffmpeg` package. No installation happens
+automatically. Stills and live exploration need only the harness runtime.
+
+Each scene lives in `scenes/` and implements the normal
+`createScene({THREE, renderer, loaders}) -> {scene, cameras, update}` contract.
+The builder stages self-contained workspaces in `<out>/cases/`, using a byte
+snapshot of the current shipped `src/lib` modules and all registered scenes.
+Independent `.vert`, `.frag` and `.glsl` files under `shaders/` are copied into
+every workspace and the published `src/shaders/`, with a separate shader digest
+map in the manifest. Their relative paths are preserved. Shader byte changes
+receive the same stale-media protection as scene and library changes.
+It checks that every scene exists before writing anything. Stills use `runtime_js/render_scene.mjs`;
+films use the same scene host, deterministic absolute simulation times and
+the same ACES/GTAO/bloom/grade chain. `renders/<case>/metrics.json` and
+`<case>.capture.json` record actual execution and renderer information.
+`verify_media.py` checks every published/staged source hash, primary scene identity,
+encoded-file digest and capture record. It decodes every frame, verifies frame
+counts/rates, and compares retained encoding inputs at three times with the
+decoded film, including motion where the input frames measurably change. The
+first frame also matches its authored-camera still. `capture-plan.json`, when
+present, specifies the complete required film/scene/camera set including extras.
+Reports and motion contact sheets go in `media-verification/`; pixel change is
+not a realism score. Historical captures without input frames/digests require
+`--allow-legacy` and are explicitly identified as weaker evidence.
+
+Use a fresh `--out` directory whenever scene or shared library sources change.
+Once an output contains media, staging verifies its existing manifest, published
+source files, staged workspaces and available capture-time hashes before writing.
+A mismatch is refused, including changes to an unselected scene: the builder
+cannot attach today's code to yesterday's film. An unchanged-source incremental
+run remains supported, for example:
+
+```bash
+python examples/graphics_lab/build.py --out /tmp/graphics-lab-v2 --case fire --render --video
+```
+
+Staging without `--render` or `--video` creates source workspaces only. A directory
+without media may be refreshed freely. Older capture records without source
+hashes can only be checked against their retained source manifest; they do not
+gain retrospective capture provenance. These checks cover scene/library bytes,
+not runtime host revisions. Keep the runtime revision with an archival release.
+Existing packages and controlled-comparison snapshots are left untouched.
+
+The manual order is fire, ocean, stream, sand, rocks, meadow, tree, cloud volume,
+smoke, ice, waterfall, rain shelter, workshop, campfire/bonfire, structural fire and
+external GLSL material. Agent entries A1-A3 are candle
+courtyard, coastal creek and garden workbench. The first six retain their original
+order and remain the source-and-video package selection. `overview.jpg` uses
+three columns and as many rows as the available manual previews require; missing
+previews and agent entries are omitted from that contact sheet.
+
+The scenes demonstrate realtime approximations, not a combustion, fluid or
+granular physics solver. Ocean reflections use a mean plane; stream refraction
+samples the opaque scene and cannot see transparent or offscreen objects; overlapping
+transparent fire/glass volumes need careful placement. Sand dunes are static
+terrain with animated windborne grains. See each module's JSDoc for limits.
+
+## Library entry points
+
+| Module | Factory | Principal options |
+| --- | --- | --- |
+| `fire.js` | `makeFire`, `makeCandle` | radius, height, seed, quality; candle wax, wick and drips |
+| `firefield.js` | `makeFireField` | emitters, wind, smoke, embers, lighting, occluders, depthResolution, quality |
+| `ocean.js` | `makeOceanSurface` | width/depth, waveHeight, wavelength, windDirection, shoreline |
+| `stream.js` | `makeStream` | descending path points, width/depth, speed, obstacles, attenuationDistance, reflectionSize, caustics |
+| `sand.js` | `makeSandTerrain` | size, duneHeight/duneSpacing, windDirection, rippleSpacing |
+| `rock.js` | `makeRock`, `makeRockField` | type, size, seed, moisture, weathering |
+| `meadow.js` | `makeMeadow` | size, density, height, heightAt, mask, diversity, seedHeads, wind, shadows |
+| `tree.js` | `makeTree`, `makeShrub` | species, height, crownRadius, leafDensity, maxLeaves, leafSegments, autumn, wind |
+| `cloudvolume.js` | `makeCloudVolume` | size, coverage, density, wind, sunDirection, quality, seed |
+| `smoke.js` | `makeSmoke`, `makeSteam` | height, radius, spread, riseSpeed, wind, density, quality, seed |
+| `ice.js` | `makeFracturedIce` | size, thickness, crackDensity, gap, frost, bubbles, heave, seed |
+| `waterfall.js` | `makeWaterfall` | width, height, speed, thickness, breakup, foam, spray, quality |
+| `paving.js` | `makePaving` | size, stoneSize, pattern, joint, thickness, relief, moisture, seed |
+
+The listed factories return Three.js objects with `userData.update(t, dt)` and
+`userData.dispose()`. Coordinates and dimensions are local metres; move the
+returned object as a whole. Drive absolute seconds once per frame. Rock is
+static; its update hook is intentionally a no-op. Terrain and water sampling
+methods return local positions/heights, as documented in the source.
+
+For an existing terrain, pass `ground: false` to `makeMeadow`, and give it the
+same `heightAt` function that built the terrain. Grass shadows need a tight
+sun frustum and sufficient resolution for centimetre-wide leaves. The runtime
+uses `PCFShadowMap`, the filtered shadow type supported by the installed Three.
+
+Background reading for the wind architecture:
+[GPU Gems, Rendering Countless Blades of Waving Grass](https://developer.nvidia.com/gpugems/gpugems/part-i-natural-effects/chapter-7-rendering-countless-blades-waving-grass).
+The implemented meadow uses actual curved leaf geometry, per-leaf phases and
+shared travelling gusts; it does not copy the chapter's texture-card geometry.
+
+Stream optics use [Three's physical transmission](https://threejs.org/docs/pages/MeshPhysicalMaterial.html),
+with IOR 1.333 and depth-dependent Beer attenuation. `waterColor` describes the
+absorption colour over `attenuationDistance` metres (default 3). Optional
+`reflectionSize: 256..2048` adds bank reflections; default 0 uses the environment
+map only. Use at most one planar reflector in a scene. The brook study enables
+1024-pixel bank reflections. Bed caustics are a bounded ripple-curvature
+approximation applied to direct lighting, not a fluid or photon simulation.
+
+## Controlled refinement comparison
+
+The retained `output/refinement-baseline/<case>/src` workspaces preserve the first
+revision. Historical comparison images and their snapshots remain independent
+of the expanded gallery. To produce a new comparison, use a separate output and
+a baseline whose shared dependencies support the module revision being compared:
+
+```bash
+python examples/graphics_lab/compare.py --baseline /path/to/compatible-baseline --out /tmp/graphics-lab-comparison
+python examples/graphics_lab/build.py --out /tmp/graphics-lab-comparison
+```
+
+`<out>/comparison.html` provides before/after sliders for ocean, stream, rock and
+meadow. Each pair changes exactly one library module; cameras, lighting, scene
+source, simulation time and other libraries are byte-identical. Source hashes
+and render metrics are linked from the page. The main gallery additionally
+contains revised scene dressing. The ignored baseline/output artifacts must be
+retained to reproduce this historical comparison on another machine. The browser
+checker reads the comparison manifest and verifies its actual image pairs and
+slider count; it does not assume a fixed number of comparisons.
+
+## Transfer a source-and-video snapshot
+
+After rendering the gallery, package its first six library studies:
+
+```bash
+python examples/graphics_lab/package.py --out /tmp/graphics-lab-v2 --name my_six_studies
+```
+
+The script creates an offline video page, six scene modules, their shared
+library and external shaders, videos, previews, capture metadata and a verified ZIP
+in `<out>/packages`. When available, it checks encoded movie digests and bundles
+the retained input PNGs at their original package-relative paths.
+It validates published and capture-time source hashes, checks archive integrity
+and refuses existing package names. The runtime and npm dependencies are not
+bundled. See [REFINEMENT.md](REFINEMENT.md) for retained revision packages.
+
+## Validation
+
+The module-specific tests in `tests/scene_runtime/lib/`
+cover relevant determinism, topology, sampling, transforms, lifecycle, actual
+GPU compilation, and selected final-render animation checks. The shadow-filter
+regression test inspects the linked GPU shader so a deprecated enum cannot
+silently revert filtering to basic shadows again. Gallery staging regressions in
+`tests/graphics/test_graphics_lab_build.py` cover stale-media refusal, unchanged
+incremental builds and missing-scene preflight. Visual review of rendered
+frames remains necessary; a green compile test is not an aesthetic verdict.
+
+`check.mjs` opens the staged gallery in the real GPU browser, decodes each
+available film, opens every live scene, switches every authored camera, checks
+pause and time scrubbing, reopens the live tab, and cancels a pending boot.
+It writes `browser-check.json`, `gallery.png` and each `<case>.live.png`.
+Run it after building the output. All example UI, code and documentation must
+remain in English.
+
+Actual model-generated case runs are stored separately in `output/agent_runs/`.
+Their source, prompts, telemetry and renders distinguish agent-produced scenes
+from these hand-composed library studies.
+The three retained Luna modules live in `agent_cases/`; their provenance and
+review history are documented there. Gallery entries A1-A3 identify them as
+model cases. All sixteen numbered scenes are manually developed studies.
diff --git a/harness/examples/graphics_lab/REFINEMENT.md b/harness/examples/graphics_lab/REFINEMENT.md
new file mode 100644
index 00000000..afd1c536
--- /dev/null
+++ b/harness/examples/graphics_lab/REFINEMENT.md
@@ -0,0 +1,112 @@
+# Graphics Lab refinement — 2026-09-23
+
+This pass responds to visual review of the first gallery, especially water that
+looked like a coloured sheet, repeated ocean ridges, regular bank stones and
+uniform grass. It changes the shipped library itself as well as selected scene
+composition. All assets remain procedural code; no generated image backgrounds
+or photographic texture downloads were added.
+
+## Water
+
+The ocean uses 32 directional gravity-wave bands normalized to significant
+height Hs, per-fragment analytic slopes, filtered small ripples, dielectric
+Fresnel/GGX and roughness-aware reflections. Visible equirectangular sky radiance
+and reflected scene objects are handled separately. Debug renders caught and
+removed dark trough hatches and purple foam. The ocean study keeps its original
+cameras but extends the sea to 1.8 km and uses a longer-period sea state; these
+scene changes are excluded from the controlled library comparison.
+
+The stream now uses Three's physical transmission at IOR 1.333. Colour describes
+absorption through the graded water column, rather than alpha paint over the
+bed. Eleven directional ripple bands replace the regular warped sine pattern.
+Stone wakes have shorter, less continuous foam; cobbles sit flatter in the bed.
+Direct bed light receives a bounded caustic approximation from the same moving
+surface. Optional planar bank reflection is off by default and enabled at 1024
+pixels in the brook study. Unsupported offscreen transmission fades smoothly
+to the unshifted sample instead of stretching the final screen row.
+
+An independent review also found a curved-channel normal error: the old basis
+ignored the derivative of the lateral path offset. CPU and GPU now use the
+offset surface derivatives. Regression cases cover tighter bends, nonzero grade
+and changing channel width; sampled normals agree with independent position
+differences within 0.15 degrees.
+
+The stream remains a kinematic surface. Refraction samples opaque screen-space
+geometry, and bank reflection approximates the channel with a mean grade. It
+does not solve water/solid collisions, refraction of transparent objects,
+overturning breakers or photon transport.
+
+## Rock and meadow
+
+Rock geometry retains fracture edges, independently oriented chipped corners,
+recessed sandstone bedding and selective edge wear. Mineral and alteration
+detail uses filtered 3D shading. Stream-sized granite was checked separately
+because its low-detail silhouettes revealed problems hidden by the hero view.
+The matched rock study rises from 195,192 to 509,996 triangles; revised scene
+dressing brings the final rock study to 766,060 triangles. Close views remain
+visibly procedural rather than scanned geological assets.
+
+Meadow leaves vary by growth form, age and habitat, with arching/twisted blades,
+dry fragments and optional sparse geometric seed heads. Leaf count stays at
+193,000 in the study. The 579 seed culms add two instanced draws and approximately
+6.8% triangles (3.14 million for the complete study). Thin-leaf transmission
+obeys the actual shadow map. Seeded geometry and absolute-time updates are
+deterministic; whole-renderer PNG replay is not promised to be bit-identical.
+
+## Controlled evidence and transfer packages
+
+`compare.py` renders the retained baseline twice and changes exactly one library
+module in the second workspace. Scene source, cameras, lighting, time and other
+library modules have identical hashes. The nine camera pairs produce 18 real
+GPU stills. `output/comparison.html` exposes four representative pairs with
+sliders and links the complete hash/render manifest.
+
+The first transfer package preserves the gallery exactly as it was when
+requested: six scene modules, all 50 matching library modules, six six-second
+films, a hearth film, previews, capture records and an offline video index.
+It has 82 files and a 42.45 MiB ZIP. Its source hashes match the published gallery
+manifest and staged workspaces; all seven films decoded, and archive CRC and
+extracted-file hashes passed. Subsequent refinement packages use distinct names
+so this snapshot is never silently replaced.
+
+No new paid coding-agent runs were made in this refinement. The A1/A2 scene
+sources remain the retained Luna outputs; updated gallery rendering uses the
+current shared library. Earlier Luna/Gemini trial results remain documented in
+[VALIDATION.md](VALIDATION.md).
+
+## Automated checks
+
+**842 tests passed** across scene runtime/library behavior, Three.js rendering,
+portability and scene prompts:
+
+```bash
+C3D_CACHE_DIR=/tmp/c3d-graphics-refine-v2 python -m pytest tests/scene_runtime tests/threejs_render tests/core/test_portability.py tests/scene_prompts -q -n4
+```
+
+The new stream optics test renders a submerged coloured checkerboard twice with
+fixed geometry/time and different IOR. It checks actual displacement of colour
+boundaries, which an alpha-only overlay cannot produce. Other additions cover
+curved-channel CPU/GPU normals, reflector ownership, spectral energy and
+environment ownership, rock concavity/topology, and seeded meadow morphology.
+One existing Pillow deprecation warning remains.
+
+New video sidecars record the SHA-256 of each staged source module, and capture
+fails if those files change during rendering. Packaging validates those hashes
+when available; earlier sidecars remain explicitly marked as legacy evidence.
+
+The rebuilt gallery retains 60 stills, eight six-second films and a separate
+hearth film, all at 1280×720. All nine capture records match the final staged
+source hashes and report zero shader/console errors. Encoded ocean and stream
+frames at 0, 2 and 4 seconds were inspected for actual motion.
+
+Browser validation passed all eight scenes, 20 cameras, video decoding,
+pause/scrub/tab switching, boot cancellation and all four comparison sliders,
+with zero browser errors. Its English-source scan checked 1,695 files; the
+final expanded source/document/JSON scan checked 2,014 files, including both
+transfer packages, and found no Han characters.
+
+The separate refined transfer package is
+`output/packages/graphics_lab_first_six_refined_2026-09-23.zip`: 81 files,
+44,711,120 bytes (42.64 MiB), with published/staged/capture-time source validation
+and ZIP CRC/extracted-file hash verification. The original requested snapshot
+remains unchanged beside it.
diff --git a/harness/examples/graphics_lab/VALIDATION.md b/harness/examples/graphics_lab/VALIDATION.md
new file mode 100644
index 00000000..5360eea2
--- /dev/null
+++ b/harness/examples/graphics_lab/VALIDATION.md
@@ -0,0 +1,94 @@
+# Graphics Lab validation — 2026-09-22
+
+This records the first gallery revision. See [REFINEMENT.md](REFINEMENT.md) for
+the September 23 library refinement, current validation and transfer packages.
+
+## Implementation and integration
+
+Six new modules are in the existing shipped scene library: fire/candles, ocean,
+stream, sand, rock and meadow. The effects catalog documents their entry points,
+local coordinates and lifecycle. They use the existing Three.js runtime and
+post chain. A shared r182 shadow-filter fix switches the renderer to supported
+PCF filtering and checks the actual linked fragment program.
+
+## Automated checks
+
+- **834 passed**: scene runtime and library tests, Three.js object rendering,
+ portability and scene prompt tests. Command:
+ `C3D_CACHE_DIR=/tmp/c3d-graphics-regression python -m pytest tests/scene_runtime tests/threejs_render tests/core/test_portability.py tests/scene_prompts -q -n 4`.
+ One existing Pillow deprecation warning; no failed tests.
+- After the final planner guidance edit, **36 prompt/skeleton checks passed**:
+ `python -m pytest tests/scene_prompts tests/scene_runtime/test_skeleton.py -q -n 2`.
+- `python -m ruff check codeverse3d tests examples/graphics_lab` and
+ `git diff --check` passed.
+- The browser check opened **8 scenes and 20 authored cameras**, decoded every
+ gallery film, checked pause/scrub/tab switching and cancelled an asynchronous
+ scene boot. Zero browser errors. It scanned 1,007 example/staged source and
+ documentation files for Han characters; none were found. A final broader text
+ scan also included JSON and JSONL output. See `output/browser-check.json`.
+
+The new regressions cover meaningful failures found during development: closed
+rock topology and transformed terrain seating; stable stream downhill grade;
+narrow-stream defaults; inverse ocean sampling near a narrow shore; hidden and
+removed lighting; caller-owned resource preservation; shader compilation; and
+selected final-post image animation/detail checks. These checks do not certify
+photographic realism.
+
+## Render artifacts
+
+The retained gallery has **60 authored stills**, eight 6-second H.264 films at
+24 FPS and 1280x720, plus a separate hearth film. Captures used the NVIDIA GeForce
+RTX 5090 Laptop GPU through ANGLE/D3D12. Per-film `.capture.json` files record
+144 rendered frames and zero console/shader errors. `render_ms_mean` is capture
+instrumentation, not a certified realtime FPS benchmark.
+
+The six library studies were visually inspected and revised. Actual encoded
+frames show visible motion in fire, ocean, stream and meadow. Sand dunes and
+rocks are static geometry studies; windborne sand motion is subtle at the wide
+camera. The images are rendered from code with no generated bitmap backgrounds.
+`output/overview.jpg` is a contact sheet of actual library-study frames.
+
+## Actual coding-agent trials
+
+The retained A1/A2 examples were generated by **GPT-6 Luna through Codex CLI**.
+The initial courtyard failed to boot due to an undefined `THREE`; the initial
+creek rendered with a raised water/bed ribbon. A second model invocation received
+supervisor render feedback and produced revised source. Both revised modules
+were copied unchanged into `agent_cases/`, then rendered and browser-tested by
+the supervisor. The first invocation's local server bind was sandbox-blocked;
+the second allowed sandbox networking for the local renderer. Prompts, hashes,
+usage and review limitations are in [the case provenance](agent_cases/README.md).
+These are direct CLI usability trials, not full harness plan/judge runs.
+
+Three separate **Gemini full-pipeline runs** used `gemini-cli:gemini-3.7-flash`,
+the matching planner, and `gemini:gemini-3.1-pro-preview` as judge. Each requested
+one baseline plus one refinement with a 30-minute budget. Repeated provider
+503s occurred. Each retained one baseline and ended with `status: budget` before
+refinement completed; none passed baseline acceptance:
+
+| Trial | Baseline judge score | Gate errors | Recorded cost (USD) |
+| --- | ---: | ---: | ---: |
+| Candle alcove | 0.405 | 4 | 1.8948 |
+| Coastal cove | 0.120 | 4 | 1.6889 |
+| Spring stream | 0.278 | 8 | 1.8372 |
+
+Total recorded Gemini cost: **USD 5.4209**. These are the harness's recorded
+provider costs, excluding the separate Codex subscription sessions. Raw runs
+remain in `output/agent_runs/`; [the trial summary](agent_cases/gemini-trials.json)
+links their records. The scores are model judgments under incomplete execution,
+not a controlled comparison with Luna or evidence of the library's quality.
+
+The trials exposed a planning ambiguity: standalone asset generation permits
+only Three.js imports, while effects belong in zone/environment code. The final
+scene planner explicitly directs those calls to the owning zone and avoids
+rebuilding water/flame/grass as duplicate assets. This final prompt correction
+has offline checks; it has not been validated by another paid pipeline run.
+
+## Practical limits
+
+These are realtime procedural effects, not combustion, fluid, granular erosion
+or photographic asset reconstruction. Ocean reflection uses a mean plane;
+stream clarity is approximate; grass density and shadows require an appropriate
+budget. Close rock silhouettes, the Luna creek boundary and several large props
+still show procedural construction. The six library studies and two agent trials
+are labelled separately so curated work is not presented as autonomous output.
diff --git a/harness/examples/graphics_lab/agent_cases/README.md b/harness/examples/graphics_lab/agent_cases/README.md
new file mode 100644
index 00000000..5dbb1c3c
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/README.md
@@ -0,0 +1,65 @@
+# GPT-6 Luna usability cases
+
+The original two modules were authored by GPT-6 Luna through Codex CLI in a separate
+workspace. The model received the effects catalog, contract and shipped library
+source. It was instructed not to read or copy the six hand-authored studies.
+The retained source is copied unchanged from the second model invocation.
+
+- [Candle courtyard](luna_candle_courtyard.js)
+- [Coastal creek](luna_coastal_creek.js)
+- [Initial prompt](prompt.md), [supervisor feedback](feedback.md), [provenance](provenance.json)
+
+The initial courtyard failed to boot because a helper referenced an undefined
+`THREE`. The initial creek rendered, but its water/bed ribbon sat above the
+terrain. The supervisor rendered the drafts, inspected the images and returned
+those concrete failures to the model. In the second invocation the model fixed
+the import/scope error, revised lighting and camera framing, and rebuilt the
+creek banks from the stream sampler. Both revised scenes produced six real GPU
+views at 1280x720, times 0 and 2, with zero console or shader errors.
+
+These are usability trials, not aesthetic gold standards. The creek still has
+an overly regular water boundary and sparse sand grass, and the courtyard's
+large props and lighting remain visibly procedural. A successful render does
+not establish photographic realism. The six library studies offer more carefully
+composed views of each effect. Neither these two examples nor the
+Gemini trials constitute a controlled comparison of model quality.
+
+The original sources and CLI provenance remain unchanged. The current gallery
+uses A1 for the retained courtyard, A2 for the separately reviewed creek
+refinement below, and A3 for a new garden case. `build.py` stages and renders them
+through the same production host as the library studies, using current shipped
+library code. `check.mjs` exercises their live controls and video decoding.
+Raw CLI events and draft renders remain under `../output/agent_runs/` (ignored
+by git); hashes and prompts above preserve the retained source's provenance.
+
+The first invocation's browser attempt was blocked by its sandbox's localhost
+bind policy. The second enabled sandbox network access to use the existing
+local renderer, while retaining workspace write restrictions. No API key or new
+dependency was provisioned. The CLI's non-interactive workflow is documented in
+[official OpenAI documentation](https://learn.chatgpt.com/docs/non-interactive-mode).
+
+## Later delegated-agent cases
+
+The following work used a delegated GPT-6 Luna coding agent in this development
+session. It is not an additional vendor-CLI or harness trial, and does not establish
+relative model performance.
+
+- A2: [Refined coastal creek](luna_coastal_creek_refined.js),
+ [provenance and measurements](luna_coastal_creek_refined.provenance.json).
+ Three review iterations corrected the world/local height conversion, carved
+ the sand banks from the stream sampler, and replaced tiled pebble materials
+ with individual rocks. The final triangle-height measurement sampled 41
+ positions on each bank: maximum bank-to-base-water-grade error was 0.010613 m.
+ Nine fixed-camera GPU frames at 0, 1.5 and 3 seconds had no console, shader or
+ update errors. The original `luna_coastal_creek.js` remains available above.
+- A3: [Garden workbench](luna_garden_workbench.js),
+ [provenance](luna_garden_workbench.provenance.json).
+ Two review iterations revised the workbench and mug to real dimensions,
+ composed backlit steam, and batched repeated plants and masonry. Nine GPU views
+ passed; its recorded census is 1,161,394 triangles, 133 meshes and 14,897 instances.
+
+Both cases remain visibly procedural. The creek has a smooth, cool-looking
+water ribbon; the garden has stylized planting and terrace geometry, and its
+steam is clearest in the close view. The scene source and library hashes in each
+new gallery build bind that build's media to its own source snapshot; the earlier
+review records describe the exact earlier snapshots in their provenance files.
diff --git a/harness/examples/graphics_lab/agent_cases/feedback.md b/harness/examples/graphics_lab/agent_cases/feedback.md
new file mode 100644
index 00000000..23a20328
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/feedback.md
@@ -0,0 +1,9 @@
+Repair and polish the two scene modules already in this workspace. You are GPT-6 Luna in a SECOND independent coding pass following actual supervisor GPU render review. Keep src/lib read-only, do not read/copy any other hand-authored harness examples, and modify only this workspace. All prose/code/comments English. The supplied libraries have been refreshed to the final compatible build. The original source and renders are preserved separately in ../luna_initial/.
+
+Actual first-pass findings:
+1. Courtyard DOES NOT BOOT: ReferenceError THREE is not defined at box() line8. You alias the injected THREE as T only inside createScene, while box() uses out-of-scope global THREE. Fix all such references/imports and render it. Compose a true close candle hero (first camera), restrained warm candlelit dusk with realistic light falloff. Check candles actually sit on their tray (current tray top is above candle base), table/material/props look convincing. No clipping or floating props. Do not alter renderer or global exposure. Make sure the fire bowl has solid fuel/logs supporting its flames.
+2. Coastal creek boots but visually fails: its entire stream bed is a raised gray ribbon floating far ABOVE the sandy terrain; sand cut follows an approximate hand-coded centerline rather than the actual smooth stream, and upstream ground height never rises to match upstream water. Build the bank from actual stream.userData.sample(u,lateral,0) positions/width/tangent. Terrain must rise alongside the surface, descend below the stream bed inside the channel and make continuous organic banks, never an exposed raised ribbon. Grass is sparse and visibly rectangular; use continuous masking and enough near-camera blades. First camera should frame an attractive close creek composition with no finite terrain slab edges. Extend peripheral ground or choose better camera framing. Driftwood is upright, rotate into a plausible fallen position. Keep sunlit sand under control by choosing darker base material and lighting (no renderer changes). Replace/cover glossy gray obstacle eggs with naturally fractured wet stone at the actual wake positions if possible without changing mechanics.
+
+The previous sandbox denied a local HTTP server bind. This invocation enables sandbox network access so the existing production browser renderer can be used. Use this actual command per scene by temporarily writing src/scene.js to reexport the chosen module:
+node /home/yipeng/3dcodeverse/harness/runtime_js/render_scene.mjs --ws /home/yipeng/3dcodeverse/harness/examples/graphics_lab/output/agent_runs/luna_examples --out /home/yipeng/3dcodeverse/harness/examples/graphics_lab/output/agent_runs/luna_examples/renders/CASE --width 1280 --height 720 --times 0,2 --fps-seconds 0 --no-settle
+Do not call --help (unsupported). Render and VIEW images with your image tool, fix errors and revise composition until both examples are genuinely useful showcases. The supervisor has attached the first-pass creek screenshots showing the raised bed and empty slab. Update README.md accurately with actual successful checks and remaining limits. Finish within ten minutes if practical. No commits, no dependencies, no API calls, no unrelated work.
diff --git a/harness/examples/graphics_lab/agent_cases/gemini-trials.json b/harness/examples/graphics_lab/agent_cases/gemini-trials.json
new file mode 100644
index 00000000..8143ce14
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/gemini-trials.json
@@ -0,0 +1,45 @@
+{
+ "date": "2026-09-22",
+ "protocol": "Full scene pipeline, one baseline plus one requested refinement, 30 minute run budget. Repeated provider 503s occurred; refinement was not completed within budget. These are unsuccessful trials, not passing examples. Scores are recorded judge outputs, not an independent quality comparison. All predate the final planner guidance separating library effects from standalone assets.",
+ "trials": [
+ {
+ "case": "candle_alcove",
+ "generator": "gemini-cli:gemini-3.7-flash",
+ "planner": "gemini:gemini-3.7-flash",
+ "judge": "gemini:gemini-3.1-pro-preview",
+ "status": "budget",
+ "completed_rounds": 1,
+ "baseline_score": 0.405,
+ "baseline_passed": false,
+ "baseline_gate_errors": 4,
+ "cost_usd": 1.8948,
+ "record": "output/agent_runs/candle_alcove/record.json"
+ },
+ {
+ "case": "coastal_cove",
+ "generator": "gemini-cli:gemini-3.7-flash",
+ "planner": "gemini:gemini-3.7-flash",
+ "judge": "gemini:gemini-3.1-pro-preview",
+ "status": "budget",
+ "completed_rounds": 1,
+ "baseline_score": 0.12,
+ "baseline_passed": false,
+ "baseline_gate_errors": 4,
+ "cost_usd": 1.6889,
+ "record": "output/agent_runs/coastal_cove/record.json"
+ },
+ {
+ "case": "spring_stream",
+ "generator": "gemini-cli:gemini-3.7-flash",
+ "planner": "gemini:gemini-3.7-flash",
+ "judge": "gemini:gemini-3.1-pro-preview",
+ "status": "budget",
+ "completed_rounds": 1,
+ "baseline_score": 0.278,
+ "baseline_passed": false,
+ "baseline_gate_errors": 8,
+ "cost_usd": 1.8372,
+ "record": "output/agent_runs/spring_stream/record.json"
+ }
+ ]
+}
diff --git a/harness/examples/graphics_lab/agent_cases/luna_candle_courtyard.js b/harness/examples/graphics_lab/agent_cases/luna_candle_courtyard.js
new file mode 100644
index 00000000..d50ee630
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/luna_candle_courtyard.js
@@ -0,0 +1,131 @@
+import * as THREE from 'three';
+import { makeCandle, makeFire } from '../lib/fire.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { weatheredWood, cobble, travertine, paintedIron } from '../lib/materials.js';
+import { mulberry32 } from '../lib/noise.js';
+
+function box(name, size, material, position, parent, cast = true) {
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), material);
+ mesh.name = name; mesh.position.set(...position); mesh.castShadow = cast; mesh.receiveShadow = true;
+ parent.add(mesh); return mesh;
+}
+
+export function createScene({ THREE: T }) {
+ const scene = new T.Scene();
+ scene.background = new T.Color(0x22263a);
+ scene.fog = new T.Fog(0x373347, 17, 48);
+ const rig = sunRig({ mood: 'golden', azimuth: 232, elevation: 7, bounds: 14,
+ sunColor: 0xffb27b, fillSky: 0x8b8fc0, fillGround: 0x62504f, intensity: 1.8 });
+ scene.add(rig.sun, rig.sun.target, rig.fill);
+ if (rig.sunDisc) scene.add(rig.sunDisc);
+ scene.environment = rig.envTex;
+ makeSky(scene, { rig, exposure: 0.25, contrast: 1.2, scale: 120 });
+
+ const courtyard = new T.Group(); courtyard.name = 'CandleCourtyard'; scene.add(courtyard);
+ const stone = cobble({ color: 0x77716b, scale: 9, repeat: 1.4, variant: 0.52 });
+ const warmStone = travertine({ color: 0x9a8671, scale: 5, repeat: 1.4, variant: 0.42 });
+ const wood = weatheredWood({ color: 0x60442f, scale: 7, repeat: 1.1, variant: 0.38 });
+ const iron = paintedIron({ color: 0x343332, scale: 9, variant: 0.4 });
+
+ // A shallow paved court with a broken, individually articulated perimeter.
+ box('CourtyardPaving', [12, 0.22, 10], stone, [0, -0.11, 0], courtyard);
+ const rng = mulberry32(812);
+ for (let i = 0; i < 34; i++) {
+ const x = -5.5 + (i % 12) * 0.98 + (rng() - 0.5) * 0.1;
+ const z = -4.6 + Math.floor(i / 12) * 1.0 + (rng() - 0.5) * 0.1;
+ box(`PavingJointStone${i}`, [0.91, 0.025, 0.92], i % 4 ? warmStone : stone,
+ [x, 0.013, z], courtyard, false);
+ }
+ // Rear and side walls leave the approach open; the irregular cap stones soften the silhouette.
+ box('RearGardenWall', [12, 2.35, 0.48], warmStone, [0, 1.17, -5.15], courtyard);
+ box('LeftGardenWall', [0.48, 2.0, 8.7], stone, [-5.85, 1, -0.35], courtyard);
+ box('RightGardenWall', [0.48, 1.75, 8.7], stone, [5.85, 0.875, -0.35], courtyard);
+ for (let i = 0; i < 17; i++) {
+ const x = -5.65 + i * 0.7;
+ box(`WallCoping${i}`, [0.68, 0.18, 0.58], i % 3 ? warmStone : stone,
+ [x, 2.38 + Math.sin(i * 2.1) * 0.035, -5.12], courtyard);
+ }
+ // A low timber table, thick top, pegged legs and visible end grain rails.
+ const table = new T.Group(); table.name = 'WeatheredOakTable'; table.position.set(-0.45, 0, -0.1); courtyard.add(table);
+ box('TableTop', [1.48, 0.105, 0.78], wood, [0, 0.77, 0], table);
+ for (let i = 0; i < 5; i++) box(`TablePlank${i}`, [1.44, 0.008, 0.145], wood, [0, 0.828, -0.29 + i * 0.145], table, false);
+ for (const x of [-0.59, 0.59]) for (const z of [-0.27, 0.27]) {
+ box(`TrestleLeg${x}_${z}`, [0.095, 0.69, 0.095], wood, [x, 0.38, z], table);
+ }
+ box('TableLongApron', [1.18, 0.13, 0.08], wood, [0, 0.63, 0], table);
+ // Modest candle grouping; candle geometry is authored to real wax dimensions.
+ const candles = [];
+ const candleSpecs = [
+ [-0.34, -0.08, 0.125, 0.029, 0xe7d4ad],
+ [-0.08, 0.03, 0.158, 0.031, 0xdac59a],
+ [0.22, -0.04, 0.102, 0.027, 0xeee0c2],
+ [0.42, 0.11, 0.135, 0.028, 0xe5d1a5],
+ ];
+ candleSpecs.forEach(([x, z, h, r, color], i) => {
+ const candle = makeCandle({ radius: r, height: h, seed: 110 + i * 17, color, lit: true,
+ flameHeight: 0.047 + (i % 2) * 0.004, quality: 'high', lightIntensity: 0.48 });
+ candle.name = `BeeswaxCandle${i + 1}`; candle.position.set(x, 0.841, z); table.add(candle); candles.push(candle);
+ });
+ const tableLantern = new T.Group(); tableLantern.name = 'CandleTray'; tableLantern.position.set(0.02, 0.833, 0.1); table.add(tableLantern);
+ const tray = new T.Mesh(new T.CylinderGeometry(0.47, 0.45, 0.008, 48), iron);
+ tray.name = 'DarkIronTray'; tray.position.y = 0.004; tray.castShadow = true; tableLantern.add(tray);
+
+ // Compact, waist-low iron bowl on a stone plinth: visible coals and one restrained flame.
+ const bowl = new T.Group(); bowl.name = 'LowFireBowl'; bowl.position.set(2.25, 0, 0.75); courtyard.add(bowl);
+ const plinth = new T.Mesh(new T.CylinderGeometry(0.36, 0.42, 0.28, 12), warmStone);
+ plinth.name = 'BowlStoneFoot'; plinth.position.y = 0.14; plinth.castShadow = plinth.receiveShadow = true; bowl.add(plinth);
+ const bowlMesh = new T.Mesh(new T.LatheGeometry([
+ new T.Vector2(0.2, 0), new T.Vector2(0.39, 0.08), new T.Vector2(0.49, 0.33),
+ new T.Vector2(0.46, 0.39), new T.Vector2(0.39, 0.36), new T.Vector2(0.34, 0.20),
+ ], 48), iron);
+ bowlMesh.name = 'HammeredBrazier'; bowlMesh.position.y = 0.28; bowlMesh.castShadow = bowlMesh.receiveShadow = true; bowl.add(bowlMesh);
+ const coals = new T.Mesh(new T.CircleGeometry(0.34, 48), new T.MeshStandardMaterial({
+ color: 0x472116, emissive: 0x6d2109, emissiveIntensity: 0.7, roughness: 1 }));
+ coals.name = 'BankedCoals'; coals.rotation.x = -Math.PI / 2; coals.position.y = 0.57; bowl.add(coals);
+ const fuelMat = new T.MeshStandardMaterial({ color: 0x251913, roughness: 0.96 });
+ for (let i = 0; i < 3; i++) {
+ const log = new T.Mesh(new T.CylinderGeometry(0.055, 0.067, 0.52, 9), fuelMat);
+ log.name = `BrazierFuelLog${i + 1}`;
+ log.position.set(Math.cos(i * Math.PI / 3) * 0.07, 0.595 + i * 0.035, Math.sin(i * Math.PI / 3) * 0.07);
+ log.rotation.set(Math.PI / 2 + i * 0.36, i * 0.24, Math.PI / 2 + i * 0.16);
+ log.castShadow = true; bowl.add(log);
+ }
+ const fire = makeFire({ radius: 0.23, height: 0.48, seed: 91, quality: 'high', style: 'campfire', lightIntensity: 2.1 });
+ fire.name = 'BrazierFlame'; fire.position.y = 0.56; bowl.add(fire);
+
+ // A worn bench and earthen planters anchor the opposite edge without competing with the table.
+ const bench = new T.Group(); bench.name = 'GardenBench'; bench.position.set(0.15, 0, 2.55); courtyard.add(bench);
+ box('BenchSeat', [1.65, 0.09, 0.39], wood, [0, 0.46, 0], bench);
+ for (const x of [-0.62, 0.62]) {
+ box(`BenchLeg${x}`, [0.10, 0.43, 0.32], warmStone, [x, 0.23, 0], bench);
+ box(`BenchBackPost${x}`, [0.075, 0.92, 0.075], wood, [x, 0.87, -0.16], bench);
+ }
+ box('BenchBack', [1.55, 0.20, 0.09], wood, [0, 0.90, -0.16], bench);
+ for (const x of [-4.6, 4.55]) {
+ const pot = new T.Mesh(new T.CylinderGeometry(0.30, 0.23, 0.47, 12, 1, true),
+ new T.MeshStandardMaterial({ color: 0x7a4d3c, roughness: 0.94, side: T.DoubleSide }));
+ pot.name = 'TerracottaPlanter'; pot.position.set(x, 0.235, 3.55); pot.castShadow = true; courtyard.add(pot);
+ const soil = new T.Mesh(new T.CircleGeometry(0.235, 20), new T.MeshStandardMaterial({ color: 0x33251a, roughness: 1 }));
+ soil.name = 'PlanterSoil'; soil.rotation.x = -Math.PI / 2; soil.position.set(x, 0.47, 3.55); courtyard.add(soil);
+ for (let j = 0; j < 5; j++) {
+ const stem = new T.Mesh(new T.CylinderGeometry(0.008, 0.012, 0.42 + (j % 2) * 0.12, 5),
+ new T.MeshStandardMaterial({ color: 0x52623a, roughness: 1 }));
+ stem.name = `HerbStem${j}`; stem.position.set(x + (rng() - 0.5) * 0.25, 0.75, 3.55 + (rng() - 0.5) * 0.22); stem.rotation.z = (rng() - 0.5) * 0.4; courtyard.add(stem);
+ }
+ }
+ const fill = new T.PointLight(0xffa34d, 7, 5.5, 2); fill.name = 'BrazierBounce'; fill.position.set(2.2, 1.05, 0.75); courtyard.add(fill);
+ const candlesLight = new T.PointLight(0xffbc6a, 1.8, 2.7, 2); candlesLight.name = 'CandleClusterBounce'; candlesLight.position.set(-0.45, 1.43, -0.1); table.add(candlesLight);
+
+ const movers = [...candles, fire];
+ scene.userData.update = (t, dt) => movers.forEach((item) => item.userData.update?.(t, dt));
+ return {
+ scene,
+ cameras: [
+ { name: 'Establishing', position: [0.05, 1.58, 1.45], lookAt: [0.02, 1.04, 0.02], fov: 43 },
+ { name: 'CandleDetail', position: [-2.1, 2.0, 1.55], lookAt: [-0.32, 1.02, -0.12], fov: 43 },
+ { name: 'BrazierAndTable', position: [4.2, 2.0, 4.0], lookAt: [0.7, 0.8, 0.3], fov: 52 },
+ ],
+ update(t, dt) { scene.userData.update(t, dt); },
+ };
+}
diff --git a/harness/examples/graphics_lab/agent_cases/luna_coastal_creek.js b/harness/examples/graphics_lab/agent_cases/luna_coastal_creek.js
new file mode 100644
index 00000000..47c72aaf
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/luna_coastal_creek.js
@@ -0,0 +1,155 @@
+import { makeStream } from '../lib/stream.js';
+import { makeMeadow } from '../lib/meadow.js';
+import { makeSandTerrain } from '../lib/sand.js';
+import { makeRock } from '../lib/rock.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { mulberry32 } from '../lib/noise.js';
+import { cobble } from '../lib/materials.js';
+
+export function createScene({ THREE: T }) {
+ const scene = new T.Scene();
+ scene.background = new T.Color(0xaad0e2);
+ scene.fog = new T.Fog(0xb7d5df, 45, 120);
+ const rig = sunRig({ mood: 'day', azimuth: 226, elevation: 39, bounds: 26,
+ sunColor: 0xffedcf, fillSky: 0xb7d9ee, fillGround: 0x8d8767, intensity: 2.65 });
+ scene.add(rig.sun, rig.sun.target, rig.fill);
+ if (rig.sunDisc) scene.add(rig.sunDisc);
+ scene.environment = rig.envTex;
+ makeSky(scene, { rig, exposure: 0.23, contrast: 1.08, scale: 160 });
+
+ const land = new T.Group(); land.name = 'CoastalCreek'; scene.add(land);
+ const seed = 4207, rng = mulberry32(seed);
+ const points = [[0.25, 0.72, -12], [0.95, 0.57, -7], [0.45, 0.34, -1], [-0.72, 0.18, 5], [-0.36, 0.02, 12]];
+ const sand = makeSandTerrain({ name: 'WindblownSand', size: [40, 44], segments: 192,
+ duneHeight: 0.21, duneSpacing: 7.4, windDirection: [0.92, 0.38], rippleSpacing: 0.22,
+ grains: 80, windSpeed: 0.55, seed, color: 0xa88b62 });
+ sand.position.y = -0.12;
+ const obstacles = [ { u: 0.22, lateral: -0.5, radius: 0.16 }, { u: 0.53, lateral: 0.45, radius: 0.18 }, { u: 0.78, lateral: -0.25, radius: 0.14 } ];
+ const stream = makeStream({ name: 'CoastalCreekWater', points, width: 1.52, widthVariation: 0.13,
+ depth: 0.25, speed: 0.72, roughness: 0.34, segments: 192, widthSegments: 16,
+ stoneCount: 36, seed: seed + 1, waterColor: 0x5b9992, bedColor: 0x887d62,
+ obstacles });
+ stream.name = 'CoastalCreekWater'; land.add(stream);
+ const suppliedBed = stream.getObjectByName('StreamBed');
+ if (suppliedBed) suppliedBed.visible = false;
+ const pathSamples = Array.from({ length: 481 }, (_, i) => {
+ const u = i / 480, s = stream.userData.sample(u, 0, 0);
+ return { u, x: s.position.x, z: s.position.z, width: s.width, tx: s.tangent.x, tz: s.tangent.z };
+ });
+ const nearestPath = (x, z) => {
+ let lo = 0, hi = pathSamples.length - 1;
+ while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (pathSamples[mid].z < z) lo = mid; else hi = mid; }
+ const a = pathSamples[lo], b = pathSamples[hi];
+ const f = T.MathUtils.clamp((z - a.z) / (b.z - a.z), 0, 1);
+ const u = T.MathUtils.lerp(a.u, b.u, f), sample = stream.userData.sample(u, 0, 0);
+ const best = { x: sample.position.x, z: sample.position.z, width: sample.width,
+ tx: sample.tangent.x, tz: sample.tangent.z };
+ const dx = x - best.x, dz = z - best.z;
+ const acrossX = best.tz, acrossZ = -best.tx;
+ return { u, width: best.width, lateral: dx * acrossX + dz * acrossZ,
+ distance: Math.hypot(dx, dz), centerX: best.x, centerZ: best.z };
+ };
+ for (let i = 0; i < obstacles.length; i++) {
+ const obstacle = obstacles[i];
+ const original = stream.getObjectByName(`StreamObstacle_${i}`);
+ if (original) original.visible = false;
+ const sample = stream.userData.sample(obstacle.u, obstacle.lateral, 0);
+ const rock = makeRock({ type: 'basalt', size: [obstacle.radius * 2.5, obstacle.radius * 1.4, obstacle.radius * 2.2],
+ seed: seed + 180 + i * 19, detail: 6, moisture: 0.82 });
+ rock.name = `FracturedWetWakeStone${i + 1}`;
+ rock.position.copy(sample.position); rock.position.y -= obstacle.radius * 0.34;
+ rock.rotation.y = rng() * Math.PI * 2; land.add(rock);
+ }
+ const groundMesh = sand.children.find((child) => child.isMesh);
+ const terrain = groundMesh.geometry.attributes.position;
+ for (let i = 0; i < terrain.count; i++) {
+ const x = terrain.getX(i), z = terrain.getZ(i), base = terrain.getY(i);
+ const path = nearestPath(x, z), d = Math.abs(path.lateral) / (path.width * 0.5);
+ const waterY = stream.userData.sample(path.u, 0, 0).position.y;
+ const bedY = waterY - 0.25 * (1 - 0.55 * Math.min(1, d) ** 2) + 0.025;
+ const shelfY = Math.max(base, waterY + 0.055);
+ let y;
+ if (d <= 1.40) y = bedY;
+ else if (d < 1.82) {
+ const f = T.MathUtils.smoothstep(d, 1.40, 1.82);
+ y = T.MathUtils.lerp(bedY, shelfY, f);
+ } else if (d < 4.0) {
+ const f = T.MathUtils.smoothstep(d, 1.72, 4.0);
+ y = T.MathUtils.lerp(shelfY, base, f);
+ } else y = base;
+ terrain.setY(i, y);
+ }
+ terrain.needsUpdate = true; groundMesh.geometry.computeVertexNormals();
+ sand.userData.update(0); land.add(sand);
+
+ const plantRegions = [];
+ const grass = makeMeadow({ name: 'ContinuousCoastalGrass', size: [34, 36], height: 0.52, density: 620,
+ maxBlades: 170000, seed: seed + 20,
+ heightAt: (x, z) => sand.userData.sampleHeight(x, z),
+ mask: (x, z) => {
+ const path = nearestPath(x, z), d = Math.abs(path.lateral) / (path.width * 0.5);
+ const bank = T.MathUtils.smoothstep(d, 1.55, 2.15);
+ const windGaps = 0.76 + 0.24 * Math.sin(x * 0.55 + z * 0.31 + 1.2) * Math.sin(z * 0.47 - x * 0.28);
+ return bank * Math.max(0.28, windGaps);
+ }, wind: { direction: [0.94, 0.34], strength: 0.48, speed: 1.05 }, ground: false });
+ grass.position.y = sand.position.y; land.add(grass); plantRegions.push(grass);
+
+ // Sparse dune-edge tufts create a broken transition into the distant shore.
+ const tuftMat = new T.MeshStandardMaterial({ color: 0x8a9257, roughness: 0.92, side: T.DoubleSide });
+ for (let i = 0; i < 44; i++) {
+ const z = -12 + rng() * 24, x = (rng() - 0.5) * 18;
+ if (Math.abs(nearestPath(x, z).lateral) < 2.1) continue;
+ const h = 0.24 + rng() * 0.36;
+ const tuft = new T.Group(); tuft.name = `SeaOatTuft${i}`; tuft.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z), z); land.add(tuft);
+ for (let j = 0; j < 5; j++) {
+ const blade = new T.Mesh(new T.PlaneGeometry(0.045, h * (0.68 + rng() * 0.45)), tuftMat);
+ blade.name = 'OatBlade'; blade.position.y = h * 0.45; blade.rotation.y = j * Math.PI / 5; blade.rotation.z = (rng() - 0.5) * 0.36; tuft.add(blade);
+ }
+ }
+
+ // Fractured stones seat against the bank; none is allowed to cover the moving water ribbon.
+ const rockSpecs = [
+ [-1.65, -8.5, [0.82, 0.42, 0.66]], [2.2, -5.8, [0.72, 0.37, 0.58]],
+ [-1.72, -2.4, [0.95, 0.5, 0.72]], [1.7, 0.9, [0.8, 0.43, 0.63]],
+ [-1.85, 4.2, [0.72, 0.38, 0.56]], [1.25, 7.8, [0.92, 0.5, 0.76]],
+ [-2.0, 9.8, [0.62, 0.31, 0.52]], [3.4, -9.6, [1.15, 0.56, 0.9]],
+ ];
+ rockSpecs.forEach(([x, z, size], i) => {
+ const rock = makeRock({ type: i % 3 === 0 ? 'sandstone' : 'granite', size,
+ seed: seed + 80 + i * 13, detail: 5, moisture: 0.12 });
+ rock.name = `TideWornRock${i + 1}`;
+ rock.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z) - 0.025, z);
+ rock.rotation.y = rng() * Math.PI * 2; land.add(rock);
+ });
+
+ // A few flattened cobbles and a weathered driftwood branch on the dry upper bank.
+ const pebbleMat = cobble({ color: 0x77776e, scale: 12, variant: 0.46 });
+ for (let i = 0; i < 16; i++) {
+ const z = -10 + rng() * 20, side = i % 2 ? 1 : -1;
+ const path = nearestPath(0, z);
+ const x = path.centerX + side * (1.15 + rng() * 0.75);
+ const pebble = new T.Mesh(new T.IcosahedronGeometry(0.12 + rng() * 0.12, 1), pebbleMat);
+ pebble.name = `CreekPebble${i}`; pebble.scale.set(1.35, 0.48, 0.88);
+ pebble.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z) + 0.045, z);
+ pebble.rotation.set(0, rng() * Math.PI, (rng() - 0.5) * 0.18); pebble.castShadow = pebble.receiveShadow = true; land.add(pebble);
+ }
+ const driftwood = new T.Mesh(new T.CylinderGeometry(0.075, 0.13, 2.15, 8),
+ new T.MeshStandardMaterial({ color: 0x655540, roughness: 0.94 }));
+ driftwood.name = 'SaltBleachedDriftwood'; driftwood.position.set(-5.0, sand.position.y + sand.userData.sampleHeight(-5, -6) + 0.10, -6); driftwood.rotation.z = Math.PI / 2 + 0.14; driftwood.rotation.x = 0.08; driftwood.castShadow = true; land.add(driftwood);
+
+ scene.userData.update = (t, dt) => {
+ stream.userData.update(t, dt);
+ sand.userData.update(t, dt);
+ for (const patch of plantRegions) patch.userData.update(t, dt);
+ };
+ return {
+ scene,
+ cameras: [
+ { name: 'Establishing', position: [-3.8, 1.95, 4.3], lookAt: [-0.1, 0.49, -0.65], fov: 41 },
+ { name: 'Creekside', position: [-4.8, 2.0, 4.7], lookAt: [0.25, 0.32, 0.4], fov: 47 },
+ { name: 'WaterDetail', position: [3.7, 1.7, -2.2], lookAt: [0.1, 0.34, -3.2], fov: 44 },
+ ],
+ update(t, dt) { scene.userData.update(t, dt); },
+ };
+}
diff --git a/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.js b/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.js
new file mode 100644
index 00000000..3dd71aa4
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.js
@@ -0,0 +1,172 @@
+import { makeStream } from '../lib/stream.js';
+import { makeMeadow } from '../lib/meadow.js';
+import { makeSandTerrain } from '../lib/sand.js';
+import { makeRock } from '../lib/rock.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { mulberry32 } from '../lib/noise.js';
+
+export function createScene({ THREE: T }) {
+ const scene = new T.Scene();
+ scene.background = new T.Color(0xb8d4dc);
+ scene.fog = new T.Fog(0xb8d4dc, 62, 145);
+ const rig = sunRig({ mood: 'day', azimuth: 224, elevation: 34, bounds: 28,
+ sunColor: 0xffedcf, fillSky: 0xb7d9ee, fillGround: 0x8d8767, intensity: 2.3 });
+ scene.add(rig.sun, rig.sun.target, rig.fill);
+ if (rig.sunDisc) scene.add(rig.sunDisc);
+ scene.environment = rig.envTex;
+ makeSky(scene, { rig, exposure: 0.28, contrast: 1.04, scale: 170 });
+
+ const land = new T.Group(); land.name = 'SandyCoastalCreek'; scene.add(land);
+ const seed = 8314, rng = mulberry32(seed);
+ const points = [
+ [-1.15, 0.68, -13], [-0.4, 0.53, -8], [0.82, 0.34, -2],
+ [0.5, 0.19, 4], [-0.85, 0.055, 10], [-0.3, 0.0, 14],
+ ];
+ const stream = makeStream({ name: 'ShallowTidalCreek', points, width: 1.25,
+ widthVariation: 0.18, depth: 0.27, speed: 0.38, roughness: 0.6,
+ segments: 256, widthSegments: 24, stoneCount: 24, seed: seed + 1,
+ waterColor: 0x56877e, attenuationDistance: 0.72, bedColor: 0x947d5d,
+ obstacles: [
+ { u: 0.26, lateral: -0.43, radius: 0.13 },
+ { u: 0.57, lateral: 0.43, radius: 0.16 },
+ { u: 0.82, lateral: -0.38, radius: 0.12 },
+ ] });
+ land.add(stream);
+
+ const sand = makeSandTerrain({ name: 'LowWindWorkedDunes', size: [40, 48], segments: 512,
+ duneHeight: 0.20, duneSpacing: 10.5, windDirection: [0.94, 0.34],
+ rippleSpacing: 0.24, detailStrength: 0.82, grains: 45, windSpeed: 0.35,
+ seed, color: 0xb39a73 });
+ sand.position.y = -0.12;
+ const ground = sand.children.find((child) => child.isMesh);
+ const pos = ground.geometry.attributes.position;
+ const pathSamples = Array.from({ length: 701 }, (_, i) => {
+ const u = i / 700, s = stream.userData.sample(u, 0, 0);
+ return { u, x: s.position.x, z: s.position.z };
+ });
+ const nearest = (x, z) => {
+ // The creek runs generally north to south, so a local segment search avoids
+ // the incorrect straight-across assumption at its two broad bends.
+ let lo = 0, hi = pathSamples.length - 1;
+ while (hi - lo > 1) {
+ const mid = (lo + hi) >> 1;
+ if (pathSamples[mid].z < z) lo = mid; else hi = mid;
+ }
+ let best = pathSamples[lo], bestD = Infinity;
+ for (let i = Math.max(0, lo - 12); i <= Math.min(pathSamples.length - 1, hi + 12); i++) {
+ const p = pathSamples[i], dx = x - p.x, dz = z - p.z, d = dx * dx + dz * dz;
+ if (d < bestD) { bestD = d; best = p; }
+ }
+ const s = stream.userData.sample(best.u, 0, 0);
+ const ax = s.tangent.z, az = -s.tangent.x;
+ return { u: best.u, lateral: (x - best.x) * ax + (z - best.z) * az,
+ distance: Math.sqrt(bestD), centerX: best.x, centerZ: best.z };
+ };
+
+ // Cut a real shallow channel into the terrain. The valley floor follows the
+ // stream grade and its banks rise to the exact edges of the water ribbon.
+ for (let i = 0; i < pos.count; i++) {
+ const x = pos.getX(i), z = pos.getZ(i), duneY = pos.getY(i) + sand.position.y;
+ const path = nearest(x, z), width = stream.userData.sample(path.u, 0, 0).width;
+ const half = width * 0.5;
+ const edge = half;
+ const d = Math.abs(path.lateral) / edge;
+ const waterY = stream.userData.sample(path.u, 0, 0).position.y;
+ const bedY = waterY - 0.27 * Math.pow(1 - Math.min(d, 1), 0.72) - 0.004;
+ let y;
+ if (d <= 1) {
+ y = bedY;
+ } else if (d < 1.95) {
+ const t = T.MathUtils.smoothstep(d, 1, 1.95);
+ y = T.MathUtils.lerp(waterY, Math.max(duneY, waterY + 0.15), t);
+ } else if (d < 3.1) {
+ const t = T.MathUtils.smoothstep(d, 1.95, 3.1);
+ y = T.MathUtils.lerp(Math.max(duneY, waterY + 0.15), duneY, t);
+ } else {
+ y = duneY;
+ }
+ y += 0.012 * (1 - T.MathUtils.smoothstep(d, 1, 3.1));
+ // Geometry vertices are local to the offset sand group; all channel
+ // targets above were derived from the stream's world-space grade.
+ pos.setY(i, y - sand.position.y);
+ }
+ pos.needsUpdate = true;
+ ground.geometry.computeVertexNormals();
+ ground.geometry.computeBoundingBox();
+ ground.geometry.computeBoundingSphere();
+ sand.userData.update(0);
+ land.add(sand);
+
+ const grass = makeMeadow({ name: 'SparseSaltGrass', size: [35, 40], height: 0.34,
+ density: 205, maxBlades: 65000, seed: seed + 20,
+ heightAt: (x, z) => sand.userData.sampleHeight(x, z),
+ mask: (x, z) => {
+ const path = nearest(x, z), d = Math.abs(path.lateral) / 0.625;
+ const bank = T.MathUtils.smoothstep(d, 1.35, 2.4);
+ const gaps = 0.54 + 0.46 * Math.sin(x * 0.36 + z * 0.22 + 1.3) * Math.sin(z * 0.31 - x * 0.19);
+ return bank * Math.max(0.08, gaps);
+ }, wind: { direction: [0.94, 0.34], strength: 0.34, speed: 0.7 },
+ diversity: 0.8, dry: 0.26, ground: false });
+ grass.position.y = sand.position.y;
+ land.add(grass);
+
+ // Low, separated sea-oat clumps break the grass line on the higher dunes.
+ const oatMaterial = new T.MeshStandardMaterial({ color: 0x8b8c5a, roughness: 0.94, side: T.DoubleSide });
+ for (let i = 0; i < 56; i++) {
+ const z = -15 + rng() * 29, x = (rng() - 0.5) * 20;
+ if (nearest(x, z).distance < 2.3) continue;
+ const h = 0.23 + rng() * 0.27;
+ const tuft = new T.Group(); tuft.name = `SeaOatClump_${i}`;
+ tuft.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z), z); land.add(tuft);
+ for (let j = 0; j < 5; j++) {
+ const blade = new T.Mesh(new T.PlaneGeometry(0.038, h * (0.7 + rng() * 0.35)), oatMaterial);
+ blade.position.y = h * 0.43; blade.rotation.y = j * Math.PI / 5;
+ blade.rotation.z = (rng() - 0.5) * 0.27; tuft.add(blade);
+ }
+ }
+
+ // Small rounded stones sit on the damp edge; larger broken rocks stay above
+ // the waterline and are visibly seated in the sloping sand.
+ const rockSpecs = [
+ [-1.03, -9.1, [0.58, 0.30, 0.47]], [1.12, -5.1, [0.62, 0.32, 0.48]],
+ [-1.08, -1.4, [0.67, 0.34, 0.52]], [1.08, 2.4, [0.55, 0.29, 0.46]],
+ [-1.16, 6.8, [0.6, 0.31, 0.47]], [1.12, 9.8, [0.73, 0.37, 0.59]],
+ [2.9, -11.5, [0.92, 0.45, 0.78]], [-3.3, 5.1, [0.86, 0.44, 0.71]],
+ ];
+ rockSpecs.forEach(([x, z, size], i) => {
+ const rock = makeRock({ type: i % 3 === 0 ? 'sandstone' : 'granite', size,
+ seed: seed + 80 + i * 17, detail: 5, moisture: i < 6 ? 0.34 : 0.06, burial: 0.11 });
+ rock.name = `TideWornBankRock_${i + 1}`;
+ rock.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z) - 0.005, z);
+ rock.rotation.y = rng() * Math.PI * 2; land.add(rock);
+ });
+ for (let i = 0; i < 24; i++) {
+ const u = 0.06 + rng() * 0.88, side = i % 2 ? 1 : -1;
+ const p = stream.userData.sample(u, side, 0);
+ const offset = 0.12 + rng() * 0.22;
+ const x = p.position.x + p.tangent.z * side * offset;
+ const z = p.position.z - p.tangent.x * side * offset;
+ const sx = 0.18 + rng() * 0.20, sy = 0.10 + rng() * 0.10, sz = 0.15 + rng() * 0.21;
+ const pebble = makeRock({ type: i % 4 === 0 ? 'sandstone' : 'granite', size: [sx, sy, sz],
+ seed: seed + 300 + i * 23, detail: 2, weathering: 0.72, moisture: 0.22, burial: 0.22 });
+ pebble.name = `CreekEdgeStone_${i}`;
+ pebble.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z), z);
+ pebble.rotation.y = rng() * Math.PI * 2; land.add(pebble);
+ }
+
+ scene.userData.update = (t, dt) => {
+ stream.userData.update(t, dt);
+ sand.userData.update(t, dt);
+ grass.userData.update(t, dt);
+ };
+ return {
+ scene,
+ cameras: [
+ { name: 'DuneOverview', position: [-5.8, 3.1, 7.2], lookAt: [-0.2, 0.24, -0.6], fov: 43 },
+ { name: 'Waterline', position: [-2.8, 0.86, 2.7], lookAt: [0.05, 0.27, -2.1], fov: 47 },
+ { name: 'BendDetail', position: [2.7, 0.95, -3.0], lookAt: [0.05, 0.26, -4.8], fov: 45 },
+ ],
+ update(t, dt) { scene.userData.update(t, dt); },
+ };
+}
diff --git a/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.provenance.json b/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.provenance.json
new file mode 100644
index 00000000..c335bd03
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.provenance.json
@@ -0,0 +1,33 @@
+{
+ "model": "gpt-6-luna",
+ "authoring_channel": "delegated GPT-6 Luna refinement of the original CodexCLI Luna case; not a new harness or provider-CLI trial",
+ "review_iteration": 3,
+ "brief": "Refine the original sandy coastal creek into a plausible shallow channel with a graded bed, irregular contacting banks, proportionate dune vegetation and stones, and clear creekside cameras.",
+ "modifications": [
+ "Carved a 512-segment sand terrain channel from the stream's sampled centerline, width and grade, with the supplied stream bed retained under the water.",
+ "Converted world-space stream and bank heights into the offset sand group's local coordinates; added a small shoreline interpolation correction after measuring the actual triangle sampler.",
+ "Replaced individually cobble-textured pebble meshes with varied, individually seated makeRock stones, and retained the larger fractured bank rocks.",
+ "Rendered and reviewed the same establishing, waterline and bend-detail cameras at 0, 1.5 and 3 seconds on the real GPU."
+ ],
+ "testing": {
+ "render_command": "node --import /home/yipeng/3dcodeverse/harness/runtime_js/lib/resolve_three.mjs /home/yipeng/3dcodeverse/harness/runtime_js/render_scene.mjs --ws /tmp/graphics-seven-hour/luna-creek-refinement/staged --out /tmp/graphics-seven-hour/luna-creek-refinement/renders-v3 --times 0,1.5,3 --width 1280 --height 720 --fps-seconds 0 --no-settle --timeout-ms 180000",
+ "render_result": "9 authored-camera GPU frames rendered on ANGLE/D3D12 (NVIDIA GeForce RTX 5090 Laptop GPU); zero console errors, shader errors, update errors or host warnings.",
+ "shoreline_measurement": {
+ "method": "Sampled makeSandTerrain.userData.sampleHeight at both horizontal stream ribbon edges and compared world terrain height with makeStream.userData.sample(u, 0, 0) water grade.",
+ "samples": 82,
+ "stream_positions": 41,
+ "banks": 2,
+ "height_difference_min_m": -0.010605,
+ "height_difference_max_m": 0.010613,
+ "mean_absolute_height_difference_m": 0.005284,
+ "maximum_absolute_height_difference_m": 0.010613
+ },
+ "staging": "Isolated temporary workspace at /tmp/graphics-seven-hour/luna-creek-refinement/staged with copied shipped scene_threejs src/lib modules. Preserved v1 source and renders in /tmp/graphics-seven-hour/luna-creek-refinement/v1; final frames and metrics are in /tmp/graphics-seven-hour/luna-creek-refinement/renders-v3. The original comparison render at /tmp/graphics-seven-hour/integration-preview-1/luna_coastal_creek.png was left unchanged."
+ },
+ "library_usability_notes": [
+ "makeStream.sample(u, lateral, 0) provides the graded centerline and ribbon edge needed to shape terrain along a bend rather than along a fixed world axis.",
+ "makeSandTerrain.userData.sampleHeight interpolates the actual rendered triangles, allowing bank contact to be measured and stones and plants to be seated against the edited terrain.",
+ "The sand group is vertically offset, so world-space stream targets must be converted back into local heights before writing terrain vertices."
+ ],
+ "visual_limitations": "The result is a stylized procedural coastal creek. The shallow stream remains a smooth kinematic water ribbon and reads somewhat cool and glassy in broad views."
+}
diff --git a/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.js b/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.js
new file mode 100644
index 00000000..2fefbcfd
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.js
@@ -0,0 +1,289 @@
+import { makeSteam } from '../lib/smoke.js';
+import { makeTree } from '../lib/tree.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { weatheredWood, paintedWood, cobble, granite, terracotta, soil as soilFinish, foliage, paintedIron } from '../lib/materials.js';
+
+export function createScene({ THREE: T }) {
+ const scene = new T.Scene();
+ scene.background = new T.Color(0x9bb6bd);
+ scene.fog = new T.Fog(0xa9bdb9, 24, 62);
+ const rig = sunRig({ mood: 'day', azimuth: 218, elevation: 14, bounds: 20,
+ sunColor: 0xffc991, fillSky: 0xa7c2ce, fillGround: 0x827b69, intensity: 2.0 });
+ scene.add(rig.sun, rig.sun.target, rig.fill);
+ if (rig.sunDisc) scene.add(rig.sunDisc);
+ scene.environment = rig.envTex;
+ makeSky(scene, { rig, exposure: 0.20, contrast: 1.04, scale: 90 });
+
+ const garden = new T.Group(); garden.name = 'GardenWorkbench'; scene.add(garden);
+ const soilMat = soilFinish({ color: 0x554838, seed: 33, scale: 18, contrast: 0.42, bump: 0.025 });
+ const gravelMat = cobble({ color: 0x77766c, seed: 17, scale: 22, contrast: 0.38, bump: 0.018 });
+ const stoneMats = [
+ cobble({ color: 0x77796e, seed: 41, scale: 16, contrast: 0.32, bump: 0.018 }),
+ granite({ color: 0x85837a, seed: 62, scale: 18, contrast: 0.36, bump: 0.014 }),
+ cobble({ color: 0x686e69, seed: 83, scale: 21, contrast: 0.38, bump: 0.018 }),
+ ];
+ const mortar = new T.MeshStandardMaterial({ color: 0x403f36, roughness: 1 });
+ const wood = weatheredWood({ color: 0x927455, seed: 101, scale: 6, contrast: 0.18, bump: 0.0015 });
+ const sunWood = weatheredWood({ color: 0xa0805b, seed: 119, scale: 6, contrast: 0.20, bump: 0.0015 });
+ const oldPaint = paintedWood({ color: 0x596153, seed: 129, scale: 6, contrast: 0.15, bump: 0.001 });
+ const iron = paintedIron({ color: 0x303b39, seed: 5, scale: 10, contrast: 0.22 });
+ const clay = [0x9d6248, 0x80604a, 0xb27652].map((color, i) => terracotta({ color, seed: 212 + i, scale: 10, contrast: 0.34, bump: 0.006 }));
+ const leafDark = foliage({ color: 0x435d34, seed: 18, scale: 16, contrast: 0.35 });
+ const leafMid = foliage({ color: 0x667546, seed: 22, scale: 14, contrast: 0.34 });
+ const leafLight = foliage({ color: 0x89915b, seed: 25, scale: 17, contrast: 0.34 });
+
+ const box = (name, size, position, material, rotation = [0, 0, 0], parent = garden) => {
+ const mesh = new T.Mesh(new T.BoxGeometry(...size), material); mesh.name = name;
+ mesh.position.set(...position); mesh.rotation.set(...rotation);
+ mesh.castShadow = mesh.receiveShadow = true; parent.add(mesh); return mesh;
+ };
+
+ // A single, gently uneven garden bed anchors every planted object and the path.
+ const earth = new T.Mesh(new T.PlaneGeometry(14, 16, 64, 64), soilMat);
+ earth.name = 'GardenSoil'; earth.rotation.x = -Math.PI / 2; earth.position.set(0, -0.008, -0.15);
+ earth.receiveShadow = true; garden.add(earth);
+ const gravel = new T.Mesh(new T.PlaneGeometry(2.35, 8.4), gravelMat);
+ gravel.name = 'LooseGravelWorkPath'; gravel.rotation.x = -Math.PI / 2; gravel.position.set(0.0, 0.003, 2.2);
+ gravel.receiveShadow = true; garden.add(gravel);
+
+ // Three distinct retaining walls support successive planted shelves. Small irregular gaps read as dry laid joints.
+ const wallZ = [-4.25, -2.75, -1.22], deckY = [0.31, 0.49, 0.67];
+ for (let row = 0; row < wallZ.length; row++) {
+ const top = deckY[row], front = wallZ[row], bedDepth = 1.25;
+ box(`MortarCourse_${row}`, [9.65, 0.025, 0.42], [0, top - 0.29, front], mortar);
+ const courses = stoneMats.map(() => []);
+ let x = -4.78, i = 0;
+ while (x < 4.72) {
+ const width = Math.min(0.54 + ((i * 7 + row * 3) % 5) * 0.105, 4.76 - x);
+ const h = 0.31 + 0.035 * Math.sin(i * 1.71 + row * 0.9);
+ const depth = 0.38 + 0.025 * ((i + row) % 3);
+ const materialIndex = (i + row * 2) % stoneMats.length;
+ const rotation = [0.008 * Math.sin(i + row), 0.014 * Math.sin(i * 2.3 + row), 0.01 * Math.cos(i * 1.4)];
+ courses[materialIndex].push({ size: [width - 0.014, h, depth], position: [x + width / 2, top - h / 2, front], rotation });
+ x += width; i++;
+ }
+ const blockGeometry = new T.BoxGeometry(1, 1, 1);
+ for (let materialIndex = 0; materialIndex < courses.length; materialIndex++) {
+ const blocks = courses[materialIndex];
+ if (!blocks.length) continue;
+ const batch = new T.InstancedMesh(blockGeometry, stoneMats[materialIndex], blocks.length);
+ batch.name = `DryStoneCourse_${row}_${materialIndex}`;
+ const dummy = new T.Object3D();
+ for (let j = 0; j < blocks.length; j++) {
+ const block = blocks[j]; dummy.position.set(...block.position); dummy.rotation.set(...block.rotation);
+ dummy.scale.set(...block.size); dummy.updateMatrix(); batch.setMatrixAt(j, dummy.matrix);
+ }
+ batch.instanceMatrix.needsUpdate = true; batch.castShadow = batch.receiveShadow = true; garden.add(batch);
+ }
+ const shelf = new T.Mesh(new T.BoxGeometry(9.45, 0.11, bedDepth), soilMat);
+ shelf.name = `RaisedSoilShelf_${row}`; shelf.position.set(0, top - 0.055, front - 0.82);
+ shelf.receiveShadow = true; garden.add(shelf);
+ }
+
+ // A weather-softened fence is a useful garden boundary and gives the steam a dark, legible backdrop.
+ const fenceZ = -1.48, fenceBottom = 0.91;
+ for (const x of [-1.55, 0, 1.55]) box('FencePost', [0.085, 1.23, 0.085], [x, fenceBottom + 0.615, fenceZ], wood, [0, 0, (x === 0 ? 0.008 : -0.012)]);
+ for (const y of [1.05, 1.73]) box('FenceRail', [3.12, 0.065, 0.07], [0, y, fenceZ + 0.012], oldPaint);
+ for (let i = 0; i < 14; i++) {
+ const x = -1.43 + i * 0.22;
+ const h = 0.83 + 0.10 * Math.sin(i * 1.76) + 0.06 * Math.sin(i * 0.67 + 1);
+ const slat = box(`WeatheredPicket_${i}`, [0.126, h, 0.044], [x, fenceBottom + h / 2 + 0.025, fenceZ + 0.065], oldPaint,
+ [0, 0.008 * Math.sin(i * 2), 0.012 * Math.sin(i * 1.43)]);
+ slat.geometry.translate(0, -0.025, 0);
+ }
+ // Two climbing stems and instanced paired leaves soften the trellis silhouette.
+ const vineGeometry = new T.SphereGeometry(1, 8, 6);
+ const vineDark = new T.InstancedMesh(vineGeometry, leafDark, 16); vineDark.name = 'FenceVineLeavesDark';
+ const vineMid = new T.InstancedMesh(vineGeometry, leafMid, 8); vineMid.name = 'FenceVineLeavesMid';
+ let vineDarkIndex = 0, vineMidIndex = 0; const vineDummy = new T.Object3D();
+ for (let vine = 0; vine < 2; vine++) {
+ const baseX = vine === 0 ? -0.88 : 0.92;
+ const points = Array.from({ length: 7 }, (_, i) => new T.Vector3(
+ baseX + 0.095 * Math.sin(i * 0.91 + vine), 0.94 + i * 0.145, fenceZ + 0.112));
+ const stem = new T.Mesh(new T.TubeGeometry(new T.CatmullRomCurve3(points), 24, 0.006, 5, false),
+ new T.MeshStandardMaterial({ color: 0x53613e, roughness: 0.96 }));
+ stem.name = `FenceVineStem_${vine}`; garden.add(stem);
+ for (let i = 1; i < 7; i++) for (const side of [-1, 1]) {
+ vineDummy.position.set(points[i].x + side * 0.075, points[i].y + side * 0.022, fenceZ + 0.115);
+ vineDummy.rotation.set(0, side * 0.45, side * (0.40 + 0.08 * (i % 2)));
+ vineDummy.scale.set(0.047 * 0.48, 0.047 * 1.22, 0.047 * 0.23); vineDummy.updateMatrix();
+ if (i % 3) vineDark.setMatrixAt(vineDarkIndex++, vineDummy.matrix); else vineMid.setMatrixAt(vineMidIndex++, vineDummy.matrix);
+ }
+ }
+ vineDark.instanceMatrix.needsUpdate = true; vineMid.instanceMatrix.needsUpdate = true; garden.add(vineDark, vineMid);
+
+ const birch = makeTree({ name: 'FramingBirch', species: 'birch', height: 6.1, crownRadius: 2.55,
+ seed: 3206, leafDensity: 1.0, leafSize: 0.09, maxLeaves: 16000,
+ wind: { dir: [0.92, 0.38], strength: 0.32, speed: 0.7 }, shadows: true });
+ birch.position.set(-5.25, 0, -1.45); garden.add(birch);
+
+ // Bench proportions follow an ordinary potting bench: 1.45 m wide, 0.54 m deep, 0.85 m to the top.
+ const tableZ = 1.18, topY = 0.85;
+ const topBoards = [
+ { z: tableZ - 0.17, width: 0.18 }, { z: tableZ + 0.015, width: 0.18 }, { z: tableZ + 0.20, width: 0.16 },
+ ];
+ topBoards.forEach(({ z, width }, i) => box(`BenchtopPlank_${i}`, [1.45, 0.048, width], [0, topY, z], i === 1 ? sunWood : wood));
+ for (const x of [-0.62, 0.62]) {
+ for (const z of [tableZ - 0.20, tableZ + 0.20]) box('BenchLeg', [0.058, 0.79, 0.058], [x, 0.435, z], wood);
+ box('BenchApron', [0.07, 0.13, 0.43], [x, 0.73, tableZ], oldPaint);
+ }
+ box('BenchFrontStretcher', [1.16, 0.064, 0.06], [0, 0.34, tableZ + 0.19], wood);
+ box('LowerSlattedShelf', [1.27, 0.034, 0.43], [0, 0.40, tableZ], sunWood);
+ for (let i = 0; i < 6; i++) {
+ const bolt = new T.Mesh(new T.CylinderGeometry(0.008, 0.008, 0.008, 10), iron);
+ bolt.name = 'BenchJoineryPin'; bolt.rotation.x = Math.PI / 2;
+ bolt.position.set(i < 3 ? -0.62 : 0.62, 0.78 - (i % 3) * 0.04, tableZ + 0.239); garden.add(bolt);
+ }
+ // Soil smudges and small cut marks make the top feel used rather than newly assembled.
+ const workDust = new T.Mesh(new T.CircleGeometry(0.095, 24), soilMat);
+ workDust.name = 'PottingSoilSmudge'; workDust.rotation.x = -Math.PI / 2; workDust.scale.set(1.55, 0.56, 1);
+ workDust.position.set(-0.38, topY + 0.025, tableZ - 0.12); garden.add(workDust);
+ for (let i = 0; i < 4; i++) {
+ const scratch = new T.Mesh(new T.BoxGeometry(0.0015, 0.0008, 0.038 + i * 0.006), mortar);
+ scratch.name = 'BenchWearMark'; scratch.position.set(-0.2 + i * 0.06, topY + 0.025, tableZ + 0.01); scratch.rotation.y = 0.28; garden.add(scratch);
+ }
+
+ // Small hand trowel laid on the bench, scaled to a real 22 cm garden tool.
+ const trowel = new T.Group(); trowel.name = 'GardenTrowel'; trowel.position.set(-0.43, topY + 0.026, tableZ + 0.10); trowel.rotation.y = -0.66; garden.add(trowel);
+ const handle = new T.Mesh(new T.CapsuleGeometry(0.012, 0.105, 4, 8), wood);
+ handle.name = 'TrowelHandle'; handle.rotation.z = Math.PI / 2; handle.position.x = -0.066; handle.castShadow = true; trowel.add(handle);
+ const blade = new T.Mesh(new T.SphereGeometry(0.048, 12, 8), paintedIron({ color: 0x78817c, seed: 74, scale: 15, roughness: 0.53, metalness: 0.34 }));
+ blade.name = 'TrowelBlade'; blade.scale.set(1.25, 0.16, 0.72); blade.position.x = 0.08; blade.castShadow = true; trowel.add(blade);
+
+ // A handmade mug: about 9 cm across and 9.5 cm tall, with a thin rolled rim and a dark tea surface.
+ const mug = new T.Group(); mug.name = 'MorningMug'; mug.position.set(0.28, topY + 0.024, tableZ - 0.08); garden.add(mug);
+ const cupProfile = [[0, 0], [0.026, 0], [0.038, 0.006], [0.043, 0.018], [0.046, 0.078],
+ [0.045, 0.092], [0.039, 0.092], [0.038, 0.078], [0.034, 0.019], [0, 0.014]];
+ const cup = new T.Mesh(new T.LatheGeometry(cupProfile.map(p => new T.Vector2(...p)), 48),
+ new T.MeshStandardMaterial({ color: 0xb6b19d, roughness: 0.24, metalness: 0.01 }));
+ cup.name = 'CeramicCup'; cup.castShadow = cup.receiveShadow = true; mug.add(cup);
+ const lip = new T.Mesh(new T.TorusGeometry(0.0423, 0.0023, 8, 40), new T.MeshStandardMaterial({ color: 0xd2cdbd, roughness: 0.21 }));
+ lip.name = 'GlazedRolledRim'; lip.rotation.x = Math.PI / 2; lip.position.y = 0.089; mug.add(lip);
+ const cupHandle = new T.Mesh(new T.TorusGeometry(0.027, 0.006, 12, 28, Math.PI * 1.72), cup.material);
+ cupHandle.name = 'CupHandle'; cupHandle.rotation.z = Math.PI * 0.82; cupHandle.position.set(0.047, 0.048, 0); mug.add(cupHandle);
+ const tea = new T.Mesh(new T.CircleGeometry(0.036, 32), new T.MeshStandardMaterial({ color: 0x39271b, roughness: 0.19 }));
+ tea.name = 'TeaSurface'; tea.rotation.x = -Math.PI / 2; tea.position.y = 0.079; mug.add(tea);
+ const steam = makeSteam({ name: 'MugSteam', height: 0.38, radius: 0.040, spread: 0.20,
+ riseSpeed: 0.16, wind: [0.030, -0.010], density: 13.0, turbulence: 0.50,
+ dissipation: 1.1, color: 0xf0f0e7, anisotropy: 0.56, quality: 'high', seed: 52 });
+ steam.name = 'MugSteam'; steam.position.set(0.28, topY + 0.024 + 0.094, tableZ - 0.08); garden.add(steam);
+ const steamRimLight = new T.PointLight(0xffcc93, 0.8, 0.9, 2);
+ steamRimLight.name = 'SteamBacklight'; steamRimLight.intensity = 14.0; steamRimLight.distance = 4.0; steamRimLight.position.set(0.31, 1.43, -0.88); garden.add(steamRimLight);
+
+
+ // Tapered handmade pots, some planted and some recently emptied. Their spacing follows the actual shelves.
+ const addPot = (name, x, y, z, radius, height, material, plantName = null, type = 0) => {
+ const group = new T.Group(); group.name = name; group.position.set(x, y, z); garden.add(group);
+ const profile = [[radius * 0.58, 0], [radius * 0.77, 0.006], [radius * 0.94, height * 0.83],
+ [radius, height], [radius * 0.82, height], [radius * 0.75, height * 0.82], [radius * 0.62, 0.018], [0, 0.015]];
+ const vessel = new T.Mesh(new T.LatheGeometry(profile.map(p => new T.Vector2(...p)), 28), material);
+ vessel.name = 'ThrownClayPot'; vessel.castShadow = vessel.receiveShadow = true; group.add(vessel);
+ const dirt = new T.Mesh(new T.CircleGeometry(radius * 0.74, 24), soilMat);
+ dirt.name = 'VisiblePottingSoil'; dirt.rotation.x = -Math.PI / 2; dirt.position.y = height * 0.81; group.add(dirt);
+ if (plantName) addHerb(plantName, radius, height, type);
+ function addHerb(herbName, potRadius, potHeight, variety) {
+ const herbs = new T.Group(); herbs.name = herbName; herbs.position.y = potHeight * 0.78; group.add(herbs);
+ const count = variety === 2 ? 9 : 6;
+ const stemGeo = new T.CylinderGeometry(0.003, 0.004, 1, 5);
+ const stemMat = new T.MeshStandardMaterial({ color: 0x596541, roughness: 0.94 });
+ const stems = new T.InstancedMesh(stemGeo, stemMat, count); stems.name = 'HerbStems';
+ const leafRadius = variety === 2 ? 0.026 : 0.034;
+ const leafGeo = new T.SphereGeometry(1, 7, 5);
+ const leafMat = variety === 2 ? leafLight : (variety === 1 ? leafMid : leafDark);
+ const leafCount = count * (variety === 2 ? 2 : 1);
+ const leaves = new T.InstancedMesh(leafGeo, leafMat, leafCount); leaves.name = 'HerbLeaves';
+ const dummy = new T.Object3D(); let leafIndex = 0;
+ for (let i = 0; i < count; i++) {
+ const angle = i * 2.39996 + variety * 0.57;
+ const h = (variety === 1 ? 0.18 : 0.22) + (i % 3) * 0.045;
+ dummy.position.set(Math.cos(angle) * potRadius * 0.23, h * 0.49, Math.sin(angle) * potRadius * 0.23);
+ dummy.rotation.set(Math.sin(angle) * 0.19, 0, Math.cos(angle) * 0.19); dummy.scale.set(1, h, 1); dummy.updateMatrix(); stems.setMatrixAt(i, dummy.matrix);
+ const leafY = h * 0.80, leafX = Math.cos(angle) * potRadius * 0.43, leafZ = Math.sin(angle) * potRadius * 0.43;
+ dummy.position.set(leafX, leafY, leafZ); dummy.rotation.set(0, -angle, Math.cos(angle) * 0.36);
+ dummy.scale.set(leafRadius * (variety === 2 ? 0.62 : 0.48), leafRadius * (variety === 2 ? 1.5 : 0.8), leafRadius * 0.34);
+ dummy.updateMatrix(); leaves.setMatrixAt(leafIndex++, dummy.matrix);
+ if (variety === 2) {
+ dummy.position.x += Math.cos(angle + 0.35) * 0.025; dummy.position.y -= 0.04; dummy.rotation.y += 1.0;
+ dummy.updateMatrix(); leaves.setMatrixAt(leafIndex++, dummy.matrix);
+ }
+ }
+ stems.instanceMatrix.needsUpdate = true; leaves.instanceMatrix.needsUpdate = true;
+ herbs.add(stems, leaves);
+ }
+ return group;
+ };
+ const shelves = [
+ { y: deckY[0], z: -5.05, plants: [[-3.8, 0.22, 0.20, 0], [-1.8, 0.17, 0.19, 1], [1.7, 0.25, 0.23, 2], [3.55, 0.18, 0.19, 0]] },
+ { y: deckY[1], z: -3.5, plants: [[-3.4, 0.20, 0.23, 1], [-0.9, 0.26, 0.22, 2], [2.6, 0.18, 0.20, 0]] },
+ { y: deckY[2], z: -1.97, plants: [[-3.7, 0.23, 0.20, 0], [-1.55, 0.16, 0.17, 1], [0.55, 0.21, 0.20, 2], [3.45, 0.18, 0.19, 1]] },
+ ];
+ shelves.forEach((shelf, row) => shelf.plants.forEach(([x, r, h, variety], i) => {
+ const z = shelf.z + ((i % 2) ? 0.19 : -0.08);
+ addPot(`TerracePot_${row}_${i}`, x, shelf.y, z, r, h, clay[(row + i) % clay.length], `GardenHerb_${row}_${i}`, variety);
+ }));
+ // A compact rosemary mound sits just behind the mug, giving the low steam a darker, living backdrop.
+ const rosemary = new T.Group(); rosemary.name = 'RearTerraceRosemary'; rosemary.position.set(-1.37, deckY[2], -1.98); garden.add(rosemary);
+ const rosemaryStem = new T.Mesh(new T.CylinderGeometry(0.014, 0.021, 0.22, 7), new T.MeshStandardMaterial({ color: 0x5a4935, roughness: 0.95 }));
+ rosemaryStem.name = 'RosemaryMainStem'; rosemaryStem.position.y = 0.11; rosemary.add(rosemaryStem);
+ const rosemaryGeometry = new T.SphereGeometry(1, 8, 6);
+ const rosemaryDark = new T.InstancedMesh(rosemaryGeometry, leafDark, 27); rosemaryDark.name = 'RosemaryNeedlesDark';
+ const rosemaryLight = new T.InstancedMesh(rosemaryGeometry, leafLight, 7); rosemaryLight.name = 'RosemaryNeedlesLight';
+ const rosemaryDummy = new T.Object3D(); let rosemaryDarkIndex = 0, rosemaryLightIndex = 0;
+ for (let i = 0; i < 34; i++) {
+ const branch = i % 6, side = Math.floor(i / 6), angle = branch * (Math.PI * 2 / 6) + side * 0.31;
+ const height = 0.075 + (i % 5) * 0.024, radius = 0.042 + side * 0.018;
+ rosemaryDummy.position.set(Math.cos(angle) * radius, height, Math.sin(angle) * radius);
+ rosemaryDummy.rotation.set(Math.sin(angle) * 0.58, -angle, Math.cos(angle) * 0.58);
+ rosemaryDummy.scale.set(0.042 * 0.26, 0.042 * 1.38, 0.042 * 0.22); rosemaryDummy.updateMatrix();
+ if (i % 5 === 0) rosemaryLight.setMatrixAt(rosemaryLightIndex++, rosemaryDummy.matrix);
+ else rosemaryDark.setMatrixAt(rosemaryDarkIndex++, rosemaryDummy.matrix);
+ }
+ rosemaryDark.instanceMatrix.needsUpdate = true; rosemaryLight.instanceMatrix.needsUpdate = true;
+ rosemary.add(rosemaryDark, rosemaryLight);
+ // Shallow seedling flats and an empty pot make the bench look mid-task; a second small pot sits on the lower shelf.
+ const tray = box('SeedlingTray', [0.28, 0.025, 0.18], [-0.48, topY + 0.027, tableZ - 0.13], oldPaint, [0, -0.11, 0]);
+ const seedlingPlugs = new T.InstancedMesh(new T.SphereGeometry(0.018, 7, 5), leafMid, 5);
+ seedlingPlugs.name = 'SeedlingPlugs'; const seedlingDummy = new T.Object3D();
+ for (let i = 0; i < 5; i++) {
+ seedlingDummy.position.set(-0.58 + (i % 3) * 0.075, topY + 0.055, tableZ - 0.18 + Math.floor(i / 3) * 0.075);
+ seedlingDummy.scale.set(1, 1.7, 1); seedlingDummy.updateMatrix(); seedlingPlugs.setMatrixAt(i, seedlingDummy.matrix);
+ }
+ seedlingPlugs.instanceMatrix.needsUpdate = true; garden.add(seedlingPlugs);
+ addPot('LowerShelfHerbPot', -0.36, 0.417, tableZ, 0.074, 0.082, clay[1], 'SparePottedHerb', 1);
+ addPot('EmptyBenchPot', -0.34, topY + 0.024, tableZ + 0.205, 0.052, 0.067, clay[2], null, 0);
+
+ // Irregular local stone treads curve through the gravel toward the workbench.
+ const pavers = [
+ [-0.76, 5.7, 0.66, 0.44, -0.10], [0.22, 4.95, 0.72, 0.46, 0.05], [-0.32, 4.12, 0.62, 0.43, -0.16],
+ [0.57, 3.33, 0.74, 0.48, 0.13], [0.12, 2.54, 0.58, 0.42, -0.08],
+ ];
+ const treadGeometry = new T.BoxGeometry(1, 1, 1);
+ const treadBatches = stoneMats.map((material) => new T.InstancedMesh(treadGeometry, material, 2));
+ const treadIndices = [0, 0, 0]; const treadDummy = new T.Object3D();
+ pavers.forEach(([x, z, w, d, yaw], i) => {
+ const materialIndex = i % 3, batch = treadBatches[materialIndex], index = treadIndices[materialIndex]++;
+ treadDummy.position.set(x, 0.03, z); treadDummy.rotation.set(i % 2 ? 0.018 : -0.012, yaw, 0);
+ treadDummy.scale.set(w, 0.075, d); treadDummy.updateMatrix(); batch.setMatrixAt(index, treadDummy.matrix);
+ });
+ treadBatches.forEach((batch, i) => { batch.count = treadIndices[i]; batch.name = `GardenTreads_${i}`; batch.instanceMatrix.needsUpdate = true; batch.castShadow = batch.receiveShadow = true; garden.add(batch); });
+ const pebbleGeometry = new T.DodecahedronGeometry(0.045, 0);
+ const pebbleBatches = stoneMats.map((material) => new T.InstancedMesh(pebbleGeometry, material, 3));
+ for (let i = 0; i < 9; i++) {
+ const materialIndex = i % 3, batch = pebbleBatches[materialIndex], index = Math.floor(i / 3);
+ treadDummy.position.set(-1.42 + (i % 3) * 0.16, 0.018, 1.2 + i * 0.42);
+ treadDummy.rotation.set(0, i * 0.6, 0); treadDummy.scale.set(1.3, 0.54, 0.9); treadDummy.updateMatrix(); batch.setMatrixAt(index, treadDummy.matrix);
+ }
+ pebbleBatches.forEach((batch, i) => { batch.name = `PathEdgePebbles_${i}`; batch.instanceMatrix.needsUpdate = true; batch.castShadow = batch.receiveShadow = true; garden.add(batch); });
+
+ const animated = [birch, steam];
+ return {
+ scene,
+ cameras: [
+ { name: 'WorkbenchGarden', position: [4.6, 2.95, 6.4], lookAt: [0, 1.02, -1.9], fov: 43 },
+ { name: 'SteamAndCup', position: [0.82, 1.18, 2.10], lookAt: [0.23, 1.02, 1.03], fov: 38 },
+ { name: 'BirchTerrace', position: [-5.8, 2.85, 5.4], lookAt: [-0.8, 1.05, -2.25], fov: 45 },
+ ],
+ update(t) { for (const item of animated) item.userData.update(t); },
+ };
+}
diff --git a/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.provenance.json b/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.provenance.json
new file mode 100644
index 00000000..2325174a
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.provenance.json
@@ -0,0 +1,22 @@
+{
+ "model": "gpt-6-luna",
+ "authoring_channel": "delegated coding agent; not vendor CLI or harness run",
+ "review_iteration": 2,
+ "brief": "Early-morning garden workbench with a ceramic mug giving off subtle backlit steam, a birch framing one side, a planted stone terrace and restrained natural materials. Prioritize a convincing scene and readable motion over a feature grid.",
+ "modifications": [
+ "Rebuilt the bench and mug to real dimensions (about 1.45 m by 0.54 m and 0.85 m high; mug about 9 cm wide), with weathered wood and procedural stone, soil, clay and foliage materials.",
+ "Varied the planted pots and terrace stone courses, added mortar gaps and small joinery and wear details, and reframed the close view to keep the steam near the cup against garden structure.",
+ "Rendered successive review iterations, inspected the wide and close views, and tuned the steam volume and backlight for visible motion while preserving the small mug scale.",
+ "Batched repeated plants, stones and small path details with InstancedMesh after census review to keep the scene compact."
+ ],
+ "testing": {
+ "command": "node runtime_js/render_scene.mjs --ws /tmp/graphics-seven-hour/luna-workbench --out /tmp/graphics-seven-hour/luna-workbench/renders/final --times 0,1.5,3 --width 1280 --height 720 --fps-seconds 0 --no-settle",
+ "result": "9 authored-camera GPU frames rendered; zero console errors, shader errors, update errors or host warnings. Scene census: 1,161,394 triangles, 133 meshes, 14,897 instances and 40 materials.",
+ "staging": "Temporary workspace contains a copy of this scene and a frozen copy of the shipped scene_threejs src/lib modules."
+ },
+ "library_usability_notes": [
+ "At real cup scale, makeSteam is a soft, low-contrast volume against an open dawn sky; the close view, dark garden backing and tuned local backlight are needed to make its motion apparent.",
+ "The steam volume has no opaque-scene depth integration, so avoid intersecting geometry and overlapping transparent volumes."
+ ],
+ "visual_limitations": "The scene remains a stylized procedural garden. The steam reads as a soft, backlit wisp in the close view and is subtle in the wide establishing shot."
+}
diff --git a/harness/examples/graphics_lab/agent_cases/prompt.md b/harness/examples/graphics_lab/agent_cases/prompt.md
new file mode 100644
index 00000000..4155fa83
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/prompt.md
@@ -0,0 +1,8 @@
+You are an independent coding agent testing a Three.js procedural graphics library. Work only in this workspace. Read effects_catalog.md, contract.md, and actual src/lib module JSDoc before using any factory. Do not read or copy the other hand-authored examples in the parent harness. Keep the supplied src/lib read-only. All generated code, names, comments and prose must be English.
+
+Create TWO complete scene modules at src/scenes/luna_candle_courtyard.js and src/scenes/luna_coastal_creek.js, importing library modules from ../lib/. Each exports createScene({THREE,renderer,loaders}) and returns {scene,cameras:[{name,position,lookAt,fov}],update(t,dt)}. Do not modify renderer settings or postprocessing. Update each moving factory once per frame via userData.update(t,dt). Dimensions in metres, seeded variations, no external assets, images or Blender.
+
+1. An intimate stone courtyard at dusk. A weathered wood table has a small group of realistically sized beeswax candles using makeCandle. Nearby is a restrained fire bowl using makeFire. Detailed believable materials and props, clear close and wide cameras. Candle flames and warm light should have a beautiful photographic composition, not giant featureless primitive props.
+2. A bright coastal creek through windblown grass, sand and weathered rocks. Use makeStream, makeMeadow, makeSandTerrain and makeRock, optionally a distant ocean only if it serves the composition. Carve terrain below the channel, align slopes, seat props correctly, avoid water/terrain clipping. Two clear cameras, natural material and organic detail. Do not leave a giant empty plane or rectangular grass slabs.
+
+Use the supplied material/noise/shader/environment helpers as appropriate. Prioritize a polished functioning result. You may render/debug by temporarily writing src/scene.js reexporting each module, then running node /home/yipeng/3dcodeverse/harness/runtime_js/render_scene.mjs --ws YOUR_WORKSPACE --out YOUR_WORKSPACE/renders/CASE --width 1280 --height 720 --times 0,2 --fps-seconds 0 --no-settle. Read render_scene.mjs --help if needed. Inspect the images if your tools permit it, fix runtime failures. Do not modify any other workspace/library. Finish with a concise English README.md describing actual checks, library integration issues and visual limitations. No API calls, commits, new dependencies, or unrelated work. The supervising agent will check and integrate your final source. Aim to finish within ten minutes.
diff --git a/harness/examples/graphics_lab/agent_cases/provenance.json b/harness/examples/graphics_lab/agent_cases/provenance.json
new file mode 100644
index 00000000..319ae8c5
--- /dev/null
+++ b/harness/examples/graphics_lab/agent_cases/provenance.json
@@ -0,0 +1,93 @@
+{
+ "date": "2026-09-22",
+ "requested_model": "gpt-6-luna",
+ "runner": "Codex CLI, independent workspace",
+ "generation_invocations": 2,
+ "protocol": "Initial generation, then supervisor render feedback and model revision. Source copied unchanged from the second invocation. Not a controlled model comparison or a full harness plan/judge run.",
+ "sources": {
+ "luna_candle_courtyard": {
+ "initial_sha256": "c62775a3569f11d0c4658b90fec1fe70af26d3b9cfc9265fe77dd0fe8cc99f79",
+ "retained_sha256": "9e1e6b611fc209edeab03276b8a01b9388a2ffcf8e38c9f5b487ec8b9331cf12"
+ },
+ "luna_coastal_creek": {
+ "initial_sha256": "61843dd04d9ba23e782649d03959f89d5c8fbba75e49f7104e19ed7fba918556",
+ "retained_sha256": "8ba3e6647b91d4c240dedce45535e23bdc4d8bee514811ab7b9905366e234b91"
+ }
+ },
+ "turns": [
+ {
+ "log": "../output/agent_runs/luna_examples/session.jsonl",
+ "completed": true,
+ "usage": {
+ "input_tokens": 1080500,
+ "cached_input_tokens": 986624,
+ "cache_write_input_tokens": 0,
+ "output_tokens": 14554,
+ "reasoning_output_tokens": 4980
+ }
+ },
+ {
+ "log": "../output/agent_runs/luna_examples/repair-session.jsonl",
+ "completed": true,
+ "usage": {
+ "input_tokens": 3313742,
+ "cached_input_tokens": 3207168,
+ "cache_write_input_tokens": 0,
+ "output_tokens": 24471,
+ "reasoning_output_tokens": 12910
+ }
+ }
+ ],
+ "library_sha256": {
+ "accumulation.js": "6fdb4449f75132cf6d8e557cea657f4295ba1c08c5a3db17ce8985a6300219e7",
+ "aging.js": "b5a0f5e7136c94da8723d66dc3ddb692882c28d7e752cd2aa4fbc9681b58d0b7",
+ "atmosphere.js": "4659d8aebe8d4e75373c2f55ed3877b17ec3e5d2c0db124c87ad4f65c97a3dba",
+ "building.js": "42080b46ca6eb64aba20fa0f477f26939fc06415ddb61030d30ba24342c825ee",
+ "canopy.js": "c4bc1791fa38ca5e884af5edb4b6a61b083ef308ab317cd005e97d0e61e0a91a",
+ "caustics.js": "b8852853776234032b0c1014bbdc0eb0d56e57f34c6ec627349c2bbdea3fe3f7",
+ "celestial.js": "7b7260fe1ec6890c6e698f01aba206af71f189af84643c986d9c700e54da98a9",
+ "cloth.js": "e4be1bcba5586d418168e76b9e74c4dad7dd90fbd0dfeda77ab78b45ad4eede1",
+ "clouds.js": "9e3efd36f28990174e068e4fcb8fa1c268e023eec3af67a8b976bd8f924e7a56",
+ "damp.js": "fe71562b9f824eeca83d410f07db5283170c75ec57b708e37a1a712dff051486",
+ "dapple.js": "353acf08b1a2124243d709d8c5cc8482186cef36636def2311fec28fb43675f7",
+ "environment.js": "5b5c25d028a2f742290c159840dcd3f4292dc8b7b82dbd73b8ab7e1756855569",
+ "figure.js": "bfeafc699c5e386ff19d0040f2e5598d7653842d2509a0bccee013c2eb527950",
+ "finish.js": "f5b8b6937b1da011c64490195f3fdc668d1f5ad658a2c59421f2e764ec16e8ce",
+ "fire.js": "45401761623fe1414063f9c01da1440bec513d20356767230c08f608c414195a",
+ "flock.js": "920d1e40acf6d8af0515e63fa2854aa302d6048404a7d6d87db579608b40e570",
+ "flowers.js": "9784465dfbbcd4491694fac3b4bdbe07a3e31b2891f37e605da15d309cb7f3b0",
+ "foliage_shade.js": "2c4ad45539b733ca8999f5a3d3907218dadd91e7712db8960ea700766153efc0",
+ "godrays.js": "984078c965f076f9c9bb59ff79eca788f850a288b6581328af01b0cd140a84a3",
+ "grass.js": "c79a971e71ff09da06e260cf8457d2e75dab3b4365032835e350bbaae884c675",
+ "instancing.js": "3056ec2877b4f8812898bc9c30aac5cf5cf54284c03ebdd5cca3794ce7a32edf",
+ "materials.js": "3c7039f63c4796b61154a9cd157460261300f68494622d806dc580d88795837d",
+ "meadow.js": "2ab3ed685cbfd4e844437e522f198ca7a6db05a58dc277866cdd2f030935a181",
+ "merge.js": "c479e78422290ee35fac831c2496ef9d5d1c6f6f0287be5aa294cdda6cb386cd",
+ "neon.js": "d57a0dafe22dc1bce8084c6b9633ea311239bc1a0ff86a9c15f16309362b5bad",
+ "noise.js": "150a5a5edf06e8653cdd8e74a7fc42ba83c6453a2a846760162b8abdcf90467d",
+ "ocean.js": "3edf78fd18f7dcb1707ffe2ae9757adab75f1f8627dfbacf010b5319085751e2",
+ "place.js": "e1c97ebcbf14e3a04fb3acb6ffdca971ca37f39c7a66c888f6823b8b7202f021",
+ "rain.js": "2bf395659cf79b0860cfb94f85e5980922cec8136500e0c28a5f2d3007e2e63e",
+ "roadway.js": "48a2c033970cce211bb0958df6ed0f9f7ab0c232f20ac49c52f1ec400551c060",
+ "rock.js": "2f2b35c43194badc105f0e1eb82b4307e22f5204be1765570bbc398df65f777c",
+ "sand.js": "6ecc57b46b0b0b155985210499939e4897d03fc213b726ddba442b8a696c153a",
+ "shader.js": "607004c07cd91b6346eda6cb28b2467ca8bb08dddd646f2208741e0827c75adb",
+ "signage.js": "031f70ec0420a543a64a4febe34278299c9d34ea2891434965b3a557e9020b15",
+ "sky.js": "0729b4ea803907ca3e4ba22a8a4e16d7a8d7492df63a2c65dd22788e58af4f97",
+ "smalllife.js": "d52b561ac2636333d00ac011d67d4d1388f59204755cc7556b0ca8c3b64e97d8",
+ "strata.js": "aa208ab62bf40d13342448028949368aaa2e5e3b2c8a98ede34f222f4e7bd71a",
+ "stream.js": "0e476fab53c1df925a559f591223b600b7081502308ba52c9dd5b595a21b31bf",
+ "submerged.js": "71b7cc71e8832f03fc105c5162176b372c2e52342315866f34610b6abee5b860",
+ "surface_wear.js": "b24d869fb40f31eff402c68886949e1c2c05f3e876d75a01fbd238eb930f6912",
+ "terrain.js": "20607158f9286b2c802ec54ad3611a17d39456a6b7b0f19e944e3531f8172a68",
+ "terrain_shade.js": "4708709264744d610d643aac56023c386075b54a8a77816d6ef713b84c560e77",
+ "urban.js": "d6b76b6616b53a88350e581606d59f9edce93c764086e3e37fbe93eb4641aa51",
+ "veils.js": "f9b1ae68d5b510019f6e1779b48098d99ff9443f75c7558f14296bedc3f98597",
+ "water.js": "ef35be78ea5e943706c4e0988bdb0fa77d9706a270bfc5655d88cf4834f26309",
+ "watermist.js": "b25fa071ff4ce8e422bd0fe60e8a897d0078d26db3da2106a92038438e608372",
+ "waterside.js": "2911a46298f6fc7d040ea0e5f8a5b5a179287aad41179d1d3e825b94ee8b2b8c",
+ "wetground.js": "6f2a68381f005e43b6390287efb7bff76d9d107f0c82df5d1d0c61bb59d0d7f0",
+ "windows.js": "7f6806b81d028e8d50cd63cc8e7a7dd33ef7f0185c1c08556c561c6c2694dee8",
+ "woodland.js": "8278f9dcedf878cf7a5e78aa4a61e2146624a1fccbfafadb6e9bb9395a803862"
+ }
+}
diff --git a/harness/examples/graphics_lab/build.py b/harness/examples/graphics_lab/build.py
new file mode 100644
index 00000000..7918bf51
--- /dev/null
+++ b/harness/examples/graphics_lab/build.py
@@ -0,0 +1,266 @@
+"""Stage reproducible effect cases and optionally render stills and animation.
+
+From harness/: python examples/graphics_lab/build.py --render --video
+The default output is ignored by git. No provider calls or external downloads.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+HARNESS = HERE.parents[1]
+LIB = HARNESS / "codeverse3d/languages/scene_threejs/starter/src/lib"
+SHADER_SUFFIXES = {".glsl", ".vert", ".frag"}
+SOURCE_SUFFIXES = {".js", ".mjs", *SHADER_SUFFIXES}
+CASES = (
+ ("fire", "01", "Fire & candlelight", "Volumetric flames · Wax and embers", "flame"),
+ ("ocean", "02", "Open water", "Displaced waves · Reflections and whitecaps", "water"),
+ ("stream", "03", "A moving stream", "Shallow water · Flow over a stone bed", "water"),
+ ("sand", "04", "Wind over sand", "Sculpted dunes · Ripples and fine grains", "earth"),
+ ("rocks", "05", "Stone studies", "Fractured surfaces · Layers and weathering", "earth"),
+ ("meadow", "06", "The living meadow", "Folded blades · Wind and transmitted light", "life"),
+ ("tree", "07", "A woodland edge", "Connected branches · Living leaves and bark", "life"),
+ ("cloud_volume", "08", "Clouds in depth", "Volumetric light · Evolving cloud banks", "air"),
+ ("smoke", "09", "Smoke & steam", "Rising plumes · Light through suspended density", "air"),
+ ("ice", "10", "Frozen water", "Transmitted light · Frost and trapped detail", "water"),
+ ("waterfall", "11", "The falling sheet", "Accelerating flow · Spray and impact foam", "water"),
+ ("rain_shelter", "12", "Shelter from rain", "Rainfall · Wet surfaces and reflected light", "weather"),
+ ("workshop", "13", "The material workshop", "Worked surfaces · Light and weathering", "materials"),
+ ("campfire", "14", "Fire in the clearing", "Campfire and bonfire · Char, embers and rising smoke", "flame"),
+ ("structural_fire", "15", "Fire through a structure", "Window and roof flames · Opaque-depth intersections", "flame"),
+ ("external_shader", "16", "Light on alloy", "External GLSL · An animated material study", "shader study"),
+ ("luna_candle_courtyard", "A1", "Candle courtyard", "GPT-6 Luna · Independent agent case", "agent study"),
+ ("luna_coastal_creek_refined", "A2", "Coastal creek", "GPT-6 Luna · Reviewed agent refinement", "agent study"),
+ ("luna_garden_workbench", "A3", "Garden workbench", "GPT-6 Luna · Independent agent case", "agent study"),
+)
+
+
+def digest(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def source_hashes(root: Path, suffixes: set[str] = SOURCE_SUFFIXES) -> dict[str, str]:
+ return {p.relative_to(root).as_posix(): digest(p.read_bytes())
+ for p in sorted(root.rglob("*")) if p.is_file() and p.suffix in suffixes}
+
+
+def workspace_hashes(case: dict, library: dict[str, str],
+ shaders: dict[str, str] | None = None) -> dict[str, str]:
+ key = case["id"]
+ wrapper = f"export {{createScene}} from './scenes/{key}.js';\n"
+ return {**{f"lib/{name}": value for name, value in library.items()},
+ **{f"shaders/{name}": value for name, value in (shaders or {}).items()},
+ f"scenes/{key}.js": case["scene_sha256"], "scene.js": digest(wrapper.encode())}
+
+
+def has_media(out: Path) -> bool:
+ """Comparisons/packages carry their own snapshots and are not restaged here."""
+ if not out.is_dir():
+ return False
+ suffixes = {".png", ".jpg", ".jpeg", ".webp", ".mp4", ".webm"}
+ return any(p.is_file() and (p.suffix.lower() in suffixes or p.name.endswith(".capture.json"))
+ for p in out.iterdir()) or any(p.is_file() for p in (out / "renders").rglob("*"))
+
+
+def guard_media(out: Path, manifest: dict) -> None:
+ """Reject changed or already inconsistent sources before touching old media."""
+ if not has_media(out):
+ return
+
+ def stale(reason: str) -> None:
+ raise ValueError(f"Refusing stale source/media mixture in {out}: {reason}. "
+ "Choose a new --out directory for changed sources and render/capture there; "
+ "unchanged incremental --case runs remain supported.")
+
+ published = out / "manifest.json"
+ if not published.is_file():
+ stale("existing media has no source manifest")
+ try:
+ previous = json.loads(published.read_text(encoding="utf-8"))
+ old_cases = previous["cases"]
+ old_library = previous["library_sha256"]
+ if (not isinstance(old_cases, list) or not all(isinstance(case, dict) for case in old_cases)
+ or not isinstance(old_library, dict)):
+ raise ValueError("invalid manifest shape")
+ except (ValueError, KeyError, TypeError) as exc:
+ stale(f"the previous manifest cannot be verified ({exc})")
+ if old_library != manifest["library_sha256"]:
+ stale("shared library contents changed")
+ shaders = manifest.get("shader_sha256", {})
+ if previous.get("shader_sha256", {}) != shaders:
+ stale("external shader contents changed")
+ current = {case["id"]: case for case in manifest["cases"]}
+ for old in old_cases:
+ key = old.get("id")
+ if key not in current or old.get("scene_sha256") != current[key]["scene_sha256"]:
+ stale(f"scene {key!r} changed or was removed")
+ # Also catch an output previously corrupted by an unsafe restage. Do not
+ # silently repair its code while leaving its old video in place.
+ expected_library = manifest["library_sha256"]
+ actual_library = {p.name: digest(p.read_bytes()) for p in (out / "src/lib").glob("*.js")}
+ if actual_library != expected_library:
+ stale("published library files disagree with their manifest")
+ if source_hashes(out / "src/shaders", SHADER_SUFFIXES) != shaders:
+ stale("published shader files disagree with their manifest")
+ for old in old_cases:
+ key = old["id"]
+ scene = out / "src/scenes" / f"{key}.js"
+ if not scene.is_file() or digest(scene.read_bytes()) != current[key]["scene_sha256"]:
+ stale(f"published scene {key!r} disagrees with its manifest")
+ workspace = out / "cases" / key / "src"
+ if workspace.is_dir():
+ actual = source_hashes(workspace)
+ if actual != workspace_hashes(current[key], expected_library, shaders):
+ stale(f"staged workspace {key!r} disagrees with published sources")
+ expected_workspaces = [workspace_hashes(case, expected_library, shaders) for case in current.values()]
+ for sidecar in out.glob("*.capture.json"):
+ try:
+ capture = json.loads(sidecar.read_text(encoding="utf-8"))
+ except (ValueError, OSError) as exc:
+ stale(f"capture record {sidecar.name} cannot be read ({exc})")
+ if not isinstance(capture, dict):
+ stale(f"capture record {sidecar.name} is not an object")
+ if "source_sha256" in capture and capture["source_sha256"] not in expected_workspaces:
+ stale(f"capture-time sources in {sidecar.name} disagree with current sources")
+
+
+def write_source_tree(root: Path, files: dict[str, bytes]) -> None:
+ """Replace generated source only, removing obsolete staged modules as well."""
+ if root.exists():
+ shutil.rmtree(root)
+ root.mkdir(parents=True)
+ for relative, data in files.items():
+ path = root / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+
+
+def stage(out: Path, selected: list[str]) -> list[dict]:
+ unknown = set(selected) - {case[0] for case in CASES}
+ if unknown:
+ raise ValueError(f"Unknown showcase cases: {', '.join(sorted(unknown))}")
+ # Read a complete snapshot before any output mutation. Concurrent source
+ # edits cannot make copied workspaces disagree with the recorded hashes.
+ library_files = {p.name: p.read_bytes() for p in sorted(LIB.glob("*.js"))}
+ if not library_files:
+ raise FileNotFoundError(f"Showcase library missing or empty: {LIB}")
+ library_hashes = {name: digest(data) for name, data in library_files.items()}
+ shader_root = HERE / "shaders"
+ shader_files = {p.relative_to(shader_root).as_posix(): p.read_bytes()
+ for p in sorted(shader_root.rglob("*"))
+ if p.is_file() and p.suffix in SHADER_SUFFIXES}
+ shader_hashes = {name: digest(data) for name, data in shader_files.items()}
+ cases, sources = [], {}
+ for key, number, title, subtitle, kind in CASES:
+ source = HERE / ("agent_cases" if number.startswith("A") else "scenes") / f"{key}.js"
+ if not source.is_file():
+ raise FileNotFoundError(f"Showcase scene missing: {source}")
+ sources[key] = source.read_bytes()
+ cases.append({"id": key, "number": number, "title": title, "subtitle": subtitle,
+ "kind": kind, "module": f"./src/scenes/{key}.js",
+ "scene_sha256": digest(sources[key]),
+ "source_kind": "agent" if number.startswith("A") else "library_study"})
+ assets = {name: (HERE / name).read_bytes() for name in ("index.html", "viewer.js", "viewer.css")}
+ manifest = {"cases": cases, "library_sha256": library_hashes, "shader_sha256": shader_hashes}
+ guard_media(out, manifest)
+ shared = {**{f"lib/{name}": data for name, data in library_files.items()},
+ **{f"shaders/{name}": data for name, data in shader_files.items()}}
+ write_source_tree(out / "src", {**shared, **{f"scenes/{key}.js": data for key, data in sources.items()}})
+ for case in cases:
+ key = case["id"]
+ write_source_tree(out / "cases" / key / "src", {
+ **shared, f"scenes/{key}.js": sources[key],
+ "scene.js": f"export {{createScene}} from './scenes/{key}.js';\n".encode(),
+ })
+ for name, data in assets.items():
+ (out / name).write_bytes(data)
+ if (out / "comparison.html").is_file():
+ index = out / "index.html"
+ index.write_text(index.read_text().replace('<!--COMPARISON_LINK-->',
+ '<p><a href="./comparison.html">Compare library refinements ↗</a></p>'))
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False))
+ return [case for case in cases if not selected or case["id"] in selected]
+
+
+def overview(out: Path) -> None:
+ """A contact sheet of available manual studies, using actual rendered frames."""
+ from PIL import Image, ImageDraw, ImageFont
+
+ studies = [case for case in CASES if case[4] != "agent study"
+ and (out / f"{case[0]}.png").is_file()]
+ if not studies:
+ return
+ rows = (len(studies) + 2) // 3
+ sheet = Image.new("RGB", (1920, rows * 404), (17, 22, 25))
+ draw = ImageDraw.Draw(sheet)
+ try:
+ font = ImageFont.truetype("DejaVuSans.ttf", 24)
+ except OSError:
+ font = ImageFont.load_default()
+ for i, (key, number, title, _, _) in enumerate(studies):
+ x, y = (i % 3) * 640, (i // 3) * 404
+ with Image.open(out / f"{key}.png") as frame:
+ sheet.paste(frame.convert("RGB").resize((640, 360), Image.Resampling.LANCZOS), (x, y))
+ draw.text((x + 14, y + 370), f"{number} {title}", font=font, fill=(230, 235, 228))
+ sheet.save(out / "overview.jpg", quality=94)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--out", type=Path, default=HERE / "output")
+ parser.add_argument("--case", action="append", choices=[c[0] for c in CASES], default=[])
+ parser.add_argument("--render", action="store_true")
+ parser.add_argument("--video", action="store_true")
+ parser.add_argument("--width", type=int, default=1280)
+ parser.add_argument("--height", type=int, default=720)
+ parser.add_argument("--seconds", type=float, default=6)
+ parser.add_argument("--fps", type=int, default=24)
+ args = parser.parse_args()
+ out = args.out.resolve()
+ try:
+ cases = stage(out, args.case)
+ except (ValueError, FileNotFoundError) as exc:
+ parser.error(str(exc))
+ ffmpeg = None
+ if args.video:
+ ffmpeg = shutil.which("ffmpeg")
+ if not ffmpeg:
+ try:
+ import imageio_ffmpeg
+ ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
+ except ImportError as exc:
+ raise SystemExit("Video export needs ffmpeg on PATH or imageio-ffmpeg installed") from exc
+ for case in cases:
+ key = case["id"]
+ ws = out / "cases" / key
+ if args.render:
+ print(f"Rendering {key}", flush=True)
+ subprocess.run([
+ "node", str(HARNESS / "runtime_js/render_scene.mjs"),
+ "--ws", str(ws), "--out", str(out / "renders" / key),
+ "--times", "0,1.5,3", "--width", str(args.width), "--height", str(args.height),
+ "--fps-seconds", "0", "--no-settle", "--timeout-ms", "180000",
+ ], check=True, cwd=HARNESS, timeout=200)
+ views = json.loads((out / "renders" / key / "views.json").read_text())
+ if views:
+ shutil.copy2(out / "renders" / key / views[0]["path"], out / f"{key}.png")
+ if args.video:
+ print(f"Capturing {key}", flush=True)
+ subprocess.run([
+ "node", str(HERE / "capture.mjs"), "--ws", str(ws),
+ "--out", str(out / f"{key}.mp4"), "--ffmpeg", ffmpeg,
+ "--width", str(args.width), "--height", str(args.height),
+ "--seconds", str(args.seconds), "--fps", str(args.fps),
+ ], check=True, cwd=HARNESS, timeout=max(240, args.seconds * args.fps * 3))
+ overview(out)
+ print(f"Gallery: {out / 'index.html'}")
+ print(f"Serve: node {HERE / 'serve.mjs'} --out {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/harness/examples/graphics_lab/build_recipes.py b/harness/examples/graphics_lab/build_recipes.py
new file mode 100644
index 00000000..90e376e0
--- /dev/null
+++ b/harness/examples/graphics_lab/build_recipes.py
@@ -0,0 +1,98 @@
+"""Render the standalone GLSL recipe studies through the production GL host.
+
+python examples/graphics_lab/build_recipes.py [--video] [--case rain_window]
+All source dependencies and hashes are retained beside the rendered evidence.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import html
+import json
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+from codeverse3d.languages.glsl_shader import compose
+from codeverse3d.prompts import load_text
+from codeverse3d.spatial.gl_render import GlHost
+from codeverse3d.tracks.graphics import cookbook_functions, defined_names, with_helpers
+
+HERE = Path(__file__).resolve().parent
+TITLES = {"rain_window": "Rain on glass", "material_light": "Material and moving light",
+ "volume_plume": "Rising smoke volume"}
+
+
+def build(out: Path, selected: list[str], video: bool) -> dict:
+ out.mkdir(parents=True, exist_ok=True)
+ known = cookbook_functions(load_text("glsl_shader/cookbook.md"))
+ manifest = {"source_kind": "authored_recipe_study", "cases": []}
+ host = GlHost(timeout_s=240)
+ cards = []
+ for key, title in TITLES.items():
+ if selected and key not in selected:
+ continue
+ source = (HERE / "glsl_cases" / f"{key}.frag").read_text()
+ own = defined_names(source)
+ used = [recipe for name, recipe in known.items()
+ if name not in own and re.search(r"\b" + re.escape(name) + r"\s*\(", source)]
+ recipes = "\n\n".join(recipe.text for recipe in with_helpers(used, known)) + "\n"
+ case = out / key
+ (case / "src").mkdir(parents=True, exist_ok=True)
+ (case / "src/shader.frag").write_text(source)
+ (case / "src/recipes.glsl").write_text(recipes)
+ times = tuple(i / 24 for i in range(144)) if video else (0.0, 1.5, 3.0)
+ result = host.render_fragment_shader(compose(source, recipes_src=recipes).source,
+ case / "render", width=960, height=600, times=times)
+ if not result.ok or any(frame.nan or frame.inf for frame in result.frames):
+ raise RuntimeError(f"{key}: {result.error_message or 'nonfinite pixels'}")
+ shutil.copy2(result.frames[0].path, case / "preview.png")
+ if video:
+ ffmpeg = shutil.which("ffmpeg")
+ if not ffmpeg:
+ import imageio_ffmpeg
+ ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
+ # The GL host's filenames use a minimum of two index digits:
+ # lexicographic glob order puts frame 100 before frame 10. Feed
+ # the ordered result directly so a six-second film stays in time.
+ with subprocess.Popen([ffmpeg, "-y", "-loglevel", "error", "-f", "image2pipe",
+ "-vcodec", "png", "-r", "24", "-i", "-", "-an",
+ "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p",
+ "-movflags", "+faststart", str(case / "film.mp4")],
+ stdin=subprocess.PIPE) as encoder:
+ assert encoder.stdin is not None
+ for frame in result.frames:
+ encoder.stdin.write(Path(frame.path).read_bytes())
+ encoder.stdin.close()
+ if encoder.wait():
+ raise RuntimeError(f"{key}: video encoder failed")
+ record = {"id": key, "title": title, "renderer": result.renderer, "gpu": result.gpu,
+ "frames": len(result.frames), "render_ms": result.duration_ms,
+ "source_sha256": {"shader.frag": hashlib.sha256(source.encode()).hexdigest(),
+ "recipes.glsl": hashlib.sha256(recipes.encode()).hexdigest()}}
+ manifest["cases"].append(record)
+ media = (f'<video controls loop playsinline poster="{key}/preview.png" src="{key}/film.mp4"></video>'
+ if video else f'<img src="{key}/preview.png" alt="{html.escape(title)}">')
+ cards.append(f'<article><h2>{html.escape(title)}</h2>{media}<p><a href="{key}/src/shader.frag">'
+ f'Study source</a> · <a href="{key}/src/recipes.glsl">Library recipes</a></p></article>')
+ print(json.dumps(record), flush=True)
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
+ (out / "index.html").write_text('''<!doctype html><html lang="en"><meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1"><title>Graphics Lab · GLSL Studies</title>
+<style>body{margin:40px auto;max-width:1280px;padding:0 24px;background:#101817;color:#e8eee9;font:16px/1.6 system-ui}
+main{display:grid;grid-template-columns:repeat(auto-fit,minmax(360px,1fr));gap:24px}article{background:#1b2724;padding:20px}
+img,video{width:100%;display:block}h1{font-size:42px}h2{font-size:22px}a{color:#c4d9af}</style>
+<h1>Light, surfaces, atmosphere.</h1><p>Three authored studies using the agent-facing GLSL recipe library.
+Rendered locally with the production OpenGL host. Source and dependencies are included.</p><main>'''
+ + "".join(cards) + "</main></html>\n")
+ return manifest
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--out", type=Path, default=HERE / "output/seven-hour/recipes")
+ parser.add_argument("--case", action="append", choices=list(TITLES), default=[])
+ parser.add_argument("--video", action="store_true")
+ args = parser.parse_args()
+ build(args.out, args.case, args.video)
diff --git a/harness/examples/graphics_lab/capture.mjs b/harness/examples/graphics_lab/capture.mjs
new file mode 100644
index 00000000..1a83ab0c
--- /dev/null
+++ b/harness/examples/graphics_lab/capture.mjs
@@ -0,0 +1,94 @@
+#!/usr/bin/env node
+/** Deterministic frames from the production scene host, encoded as H.264. */
+import fs from 'node:fs';
+import path from 'node:path';
+import {spawn} from 'node:child_process';
+import {parseArgs} from 'node:util';
+import {createHash} from 'node:crypto';
+import {openHost} from '../../runtime_js/lib/host_page.mjs';
+const {values:a} = parseArgs({options:{ws:{type:'string'},out:{type:'string'},
+ ffmpeg:{type:'string',default:'ffmpeg'},width:{type:'string',default:'1280'},
+ height:{type:'string',default:'720'},seconds:{type:'string',default:'6'},
+ fps:{type:'string',default:'24'},camera:{type:'string',default:'0'}}});
+if (!a.ws || !a.out) throw new Error('--ws and --out required');
+if (!/\.mp4$/i.test(a.out)) throw new Error('--out must end in .mp4');
+const fps = Number(a.fps), count = Math.round(Number(a.seconds) * fps);
+if (!(fps>0 && fps<=60 && count>0 && count<=3600)) throw new Error('Invalid capture duration/fps');
+for (const size of [Number(a.width), Number(a.height)]) {
+ if (!Number.isInteger(size) || size < 2 || size > 8192 || size % 2) {
+ throw new Error('H.264 width and height must be even integers from 2 to 8192');
+ }
+}
+function sourceHashes() {
+ const root=path.join(path.resolve(a.ws),'src'), hashes={};
+ function visit(directory) {
+ for (const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((x,y)=>x.name.localeCompare(y.name))) {
+ const file=path.join(directory,entry.name);
+ if(entry.isDirectory()) visit(file);
+ else if(entry.isFile() && /\.(?:m?js|glsl|vert|frag)$/.test(entry.name)) {
+ hashes[path.relative(root,file).split(path.sep).join('/')]=createHash('sha256').update(fs.readFileSync(file)).digest('hex');
+ }
+ }
+ }
+ visit(root);return hashes;
+}
+const capturedSource=sourceHashes();
+const host = await openHost(a.ws,{width:Number(a.width),height:Number(a.height),
+ gpu:'auto',post:true,settle:false,createSceneTimeoutMs:60000});
+let encoder;
+try {
+ if (!host.boot.ok) throw new Error(host.boot.error);
+ const camera = host.boot.cameras[Number(a.camera)];
+ if (!camera) throw new Error('Camera not found');
+ fs.mkdirSync(path.dirname(path.resolve(a.out)),{recursive:true});
+ encoder = spawn(a.ffmpeg,['-y','-loglevel','error','-f','image2pipe','-vcodec','png',
+ '-r',String(fps),'-i','-','-an','-c:v','libx264','-crf','18','-pix_fmt','yuv420p',
+ '-movflags','+faststart',a.out],{stdio:['pipe','ignore','pipe']});
+ let stderr=''; encoder.stderr.on('data',b=>{stderr=(stderr+b).slice(-4000);});
+ let encoderError;
+ encoder.on('error', error => { encoderError = error; });
+ encoder.stdin.on('error', error => { encoderError = error; });
+ const done = new Promise(resolve => encoder.once('close', resolve));
+ const timings=[];
+ const referenceFrames=[];
+ const referenceIndices=new Set([0,Math.floor(count/3),Math.floor(count*2/3)]);
+ const referenceDirectory=path.join(path.dirname(path.resolve(a.out)),
+ 'capture_frames',path.basename(a.out,'.mp4'));
+ fs.mkdirSync(referenceDirectory,{recursive:true});
+ for (let i=0;i<count;i++) {
+ const frame=await host.page.evaluate((spec,t)=>window.__c3v.renderAt(spec,t),camera,i/fps);
+ timings.push(frame.ms);
+ const png=Buffer.from(frame.dataUrl.split(',')[1],'base64');
+ if(referenceIndices.has(i)) {
+ const file=path.join(referenceDirectory,`frame_${String(i).padStart(4,'0')}.png`);
+ fs.writeFileSync(file,png);
+ referenceFrames.push({index:i,time_s:i/fps,
+ path:path.relative(path.dirname(path.resolve(a.out)),file).split(path.sep).join('/'),
+ sha256:createHash('sha256').update(png).digest('hex')});
+ }
+ if (encoderError) throw encoderError;
+ await new Promise((resolve, reject) => {
+ encoder.stdin.write(png, error => error ? reject(error) : resolve());
+ });
+ }
+ encoder.stdin.end();
+ const code=await done;
+ if (encoderError) throw encoderError;
+ if (code!==0) throw new Error(`ffmpeg exited ${code}: ${stderr}`);
+ if (host.errors.console.length || host.errors.page.length || host.errors.shader_console.length) {
+ throw new Error(JSON.stringify(host.errors));
+ }
+ if(JSON.stringify(capturedSource)!==JSON.stringify(sourceHashes())) throw new Error('Scene source changed during capture');
+ const summary={ok:true,frames:count,fps,seconds:count/fps,camera:camera.name,
+ gpu:host.gpu,renderer:host.boot.renderer,width:Number(a.width),height:Number(a.height),
+ console_errors:host.errors.console,shader_errors:host.errors.shader_console,
+ source_sha256:capturedSource,
+ video_sha256:createHash('sha256').update(fs.readFileSync(a.out)).digest('hex'),
+ reference_frames:referenceFrames,
+ render_ms_mean:timings.reduce((s,t)=>s+t,0)/count};
+ fs.writeFileSync(a.out.replace(/\.mp4$/i,'.capture.json'),JSON.stringify(summary,null,2));
+ console.log(JSON.stringify({...summary,source_sha256:undefined,source_files:Object.keys(capturedSource).length}));
+} finally {
+ if (encoder && encoder.exitCode===null) encoder.kill();
+ await host.close();
+}
diff --git a/harness/examples/graphics_lab/check.mjs b/harness/examples/graphics_lab/check.mjs
new file mode 100644
index 00000000..17a726f7
--- /dev/null
+++ b/harness/examples/graphics_lab/check.mjs
@@ -0,0 +1,152 @@
+#!/usr/bin/env node
+/** Exercise the staged gallery through its real browser controls. */
+import fs from 'node:fs';
+import path from 'node:path';
+import assert from 'node:assert/strict';
+import {createRequire} from 'node:module';
+import {fileURLToPath} from 'node:url';
+import {parseArgs} from 'node:util';
+import {launchBrowser} from '../../runtime_js/lib/host_env.mjs';
+import {releaseBrowser} from '../../runtime_js/lib/host_page.mjs';
+const require = createRequire(import.meta.url);
+const {serveDirs} = require('../../runtime_js/serve.cjs');
+const here = path.dirname(fileURLToPath(import.meta.url));
+const {values} = parseArgs({options: {out: {type: 'string', default: path.join(here, 'output')}}});
+const root = path.resolve(values.out);
+// Include comments and documentation, not just currently visible UI text.
+const sourceExtensions = new Set(['.js', '.mjs', '.py', '.html', '.css', '.md', '.glsl', '.vert', '.frag']);
+let englishFilesChecked = 0;
+function checkEnglish(directory) {
+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {
+ if (['.git', 'node_modules', '__pycache__'].includes(entry.name)) continue;
+ const file = path.join(directory, entry.name);
+ if (entry.isDirectory()) checkEnglish(file);
+ else if (entry.isFile() && sourceExtensions.has(path.extname(entry.name))) {
+ assert(!/\p{Script=Han}/u.test(fs.readFileSync(file, 'utf8')), `Non-English example: ${file}`);
+ englishFilesChecked++;
+ }
+ }
+}
+checkEnglish(here);
+if (!root.startsWith(here + path.sep)) checkEnglish(root);
+const server = await serveDirs({root, routes: {
+ '/': {body: fs.readFileSync(path.join(root, 'index.html'), 'utf8')},
+ '/favicon.ico': {body: ''},
+}});
+const launched = await launchBrowser({gpu: 'auto'});
+let page;
+const errors = [], results = [];
+try {
+ page = await launched.browser.newPage();
+ await page.setViewport({width: 1440, height: 1000, deviceScaleFactor: 1});
+ page.on('pageerror', error => errors.push(error.message));
+ page.on('console', message => {
+ if (message.type() === 'error') errors.push(message.text());
+ });
+ page.on('response', response => {
+ if (response.status() >= 400) errors.push(`${response.status()} ${response.url()}`);
+ });
+ await page.goto(server.base, {waitUntil: 'networkidle0'});
+ await page.waitForFunction(() => !!window.graphicsLab);
+ const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json')));
+ assert.equal(await page.$$eval('.card', cards => cards.length), manifest.cases.length);
+ assert.equal(await page.evaluate(() => document.documentElement.lang), 'en');
+ await page.screenshot({path: path.join(root, 'gallery.png'), fullPage: true});
+
+ for (let index = 0; index < manifest.cases.length; index++) {
+ const item = manifest.cases[index];
+ console.log(`Checking ${item.id}`);
+ await page.click(`.card:nth-child(${index + 1})`);
+ const videoExists = fs.existsSync(path.join(root, `${item.id}.mp4`));
+ if (videoExists) {
+ await page.waitForFunction(() => document.querySelector('#video').readyState >= 2);
+ const video = await page.evaluate(async () => {
+ const element = document.querySelector('#video');
+ element.muted = true;
+ await element.play();
+ return {width: element.videoWidth, height: element.videoHeight, duration: element.duration};
+ });
+ assert(video.width > 0 && video.height > 0 && video.duration > 0);
+ }
+ await page.click('#explore');
+ await page.waitForFunction(() => !!window.graphicsLab.active && !document.querySelector('#status').textContent,
+ {timeout: 60000});
+ await page.waitForFunction(() => window.graphicsLab.time > .1);
+ await page.click('#pause');
+ const paused = await page.evaluate(() => window.graphicsLab.time);
+ // Two rendered browser frames must leave simulation time unchanged while paused.
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ assert.equal(await page.evaluate(() => window.graphicsLab.time), paused);
+ await page.$eval('#time', slider => {
+ slider.value = '2.5';
+ slider.dispatchEvent(new Event('input', {bubbles: true}));
+ });
+ assert.equal(await page.evaluate(() => window.graphicsLab.time), 2.5);
+ const cameras = await page.$$eval('#camera option', options => options.map(option => option.value));
+ for (const camera of cameras) {
+ await page.select('#camera', camera);
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ }
+ await page.select('#camera', '0');
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ const screen = await page.$('#canvas');
+ await screen.screenshot({path: path.join(root, `${item.id}.live.png`)});
+ const canvasOk = await page.$eval('#canvas', canvas => {
+ const gl = canvas.getContext('webgl2');
+ return !!gl && !gl.isContextLost() && canvas.width > 0 && canvas.height > 0;
+ });
+ assert(canvasOk, `${item.id}: live WebGL context lost`);
+ await page.click('#watch');
+ await page.click('#explore');
+ await page.waitForFunction(() => window.graphicsLab.time > 2.5);
+ await page.click('#close');
+ assert.equal(await page.evaluate(() => !!window.graphicsLab.active), false);
+ results.push({case: item.id, cameras: cameras.length, video: videoExists, controls: 'pass'});
+ }
+ // Cancelling a boot must not resurrect the old scene after returning to the gallery.
+ await page.evaluate(async () => {
+ document.querySelector('.card').click();
+ const loading = window.graphicsLab.explore();
+ document.querySelector('#close').click();
+ await loading;
+ });
+ assert.equal(await page.evaluate(() => !!window.graphicsLab.active), false);
+ assert.equal(await page.evaluate(() => /\p{Script=Han}/u.test(document.body.innerText)), false);
+ let comparisons = 0;
+ if (fs.existsSync(path.join(root, 'comparison.html'))) {
+ await page.goto(`${server.base}/comparison.html`, {waitUntil: 'networkidle0'});
+ await page.waitForFunction(() => [...document.images].every(image => image.complete && image.naturalWidth > 0));
+ const comparisonManifest = path.join(root, 'comparison', 'manifest.json');
+ assert(fs.existsSync(comparisonManifest), 'Comparison page has no artifact manifest');
+ const records = JSON.parse(fs.readFileSync(comparisonManifest, 'utf8'));
+ assert(Array.isArray(records) && records.length > 0, 'Comparison manifest has no pairs');
+ const actualPairs = await page.$$eval('.compare', elements => elements.map(element =>
+ [...element.querySelectorAll('img')].map(image => image.getAttribute('src'))));
+ comparisons = actualPairs.length;
+ assert.equal(comparisons, records.length, 'Comparison page and artifact manifest disagree');
+ for (let index = 0; index < records.length; index++) {
+ const expected = ['before', 'after'].map(variant => records[index].variants?.[variant]?.image);
+ assert(expected.every(image => typeof image === 'string'), 'Comparison pair has missing images');
+ assert.deepEqual(actualPairs[index], expected, `Wrong comparison images for ${records[index].case}`);
+ for (const relative of expected) {
+ const image = path.resolve(root, relative);
+ assert(image.startsWith(root + path.sep) && fs.existsSync(image), `Missing comparison artifact: ${relative}`);
+ }
+ }
+ await page.$$eval('input[type="range"]', inputs => inputs.forEach(input => {
+ input.value = '27'; input.dispatchEvent(new Event('input', {bubbles: true}));
+ }));
+ assert(await page.$$eval('.compare', elements => elements.every(element => element.style.getPropertyValue('--split') === '27%')));
+ assert.equal(await page.evaluate(() => document.documentElement.lang), 'en');
+ await page.screenshot({path: path.join(root, 'comparison-page.png'), fullPage: true});
+ }
+ assert.deepEqual(errors, []);
+ const report = {ok: true, gpu: launched.gpu, renderer: launched.renderer,
+ englishFilesChecked, cases: results, comparisons, errors};
+ fs.writeFileSync(path.join(root, 'browser-check.json'), JSON.stringify(report, null, 2));
+ console.log(JSON.stringify(report));
+} finally {
+ await page?.close();
+ await releaseBrowser(launched);
+ await server.close();
+}
diff --git a/harness/examples/graphics_lab/compare.py b/harness/examples/graphics_lab/compare.py
new file mode 100644
index 00000000..0edac75b
--- /dev/null
+++ b/harness/examples/graphics_lab/compare.py
@@ -0,0 +1,107 @@
+"""Render controlled library comparisons from an immutable baseline workspace set.
+
+Each baseline/<case>/src tree is copied twice. Only the named library module is
+replaced in the second copy; scene, camera, lighting and all other modules stay
+byte-identical. No provider calls or external assets are used.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+from build import HARNESS, HERE, LIB
+
+CASES = (
+ ('ocean', 'ocean.js', 'ocean', 'Ocean', 'Directional waves, filtered reflections and broken whitecaps.'),
+ ('stream', 'stream.js', 'stream', 'Stream', 'Refraction, water-column absorption, ripple lighting and seated cobbles.'),
+ ('rocks', 'rock.js', 'granite', 'Rock', 'Fracture geometry, recessed weathering and mineral scale.'),
+ ('meadow', 'meadow.js', 'blades', 'Meadow', 'Leaf growth forms, habitat variation and shadowed transmission.'),
+)
+
+
+def hashes(root: Path) -> dict[str, str]:
+ return {str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest()
+ for path in sorted(root.rglob('*.js'))}
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--baseline', type=Path, required=True)
+ parser.add_argument('--out', type=Path, default=HERE / 'output')
+ args = parser.parse_args()
+ out = args.out.resolve()
+ destination = out / 'comparison'
+ records = []
+ for key, module, camera, title, note in CASES:
+ record = {'case': key, 'module': module, 'camera': camera, 'time': 0,
+ 'title': title, 'note': note, 'variants': {}}
+ baseline = args.baseline.resolve() / key / 'src'
+ if not (baseline / 'scene.js').is_file():
+ raise FileNotFoundError(f'Missing baseline workspace: {baseline}')
+ for variant in ('before', 'after'):
+ workspace = destination / 'workspaces' / key / variant
+ source = workspace / 'src'
+ if source.exists():
+ shutil.rmtree(source)
+ shutil.copytree(baseline, source)
+ if variant == 'after':
+ shutil.copy2(LIB / module, source / 'lib' / module)
+ render = destination / 'renders' / key / variant
+ print(f'Comparing {key}: {variant}', flush=True)
+ subprocess.run([
+ 'node', str(HARNESS / 'runtime_js/render_scene.mjs'),
+ '--ws', str(workspace), '--out', str(render), '--times', '0',
+ '--width', '1280', '--height', '720', '--fps-seconds', '0',
+ '--no-settle', '--timeout-ms', '180000',
+ ], check=True, cwd=HARNESS, timeout=200)
+ frame = render / f'{camera}_t0.png'
+ image = destination / f'{key}-{variant}.png'
+ shutil.copy2(frame, image)
+ record['variants'][variant] = {
+ 'image': str(image.relative_to(out)), 'source_sha256': hashes(source),
+ 'metrics': str((render / 'metrics.json').relative_to(out)),
+ }
+ before = record['variants']['before']['source_sha256']
+ after = record['variants']['after']['source_sha256']
+ differences = [name for name in sorted(before.keys() | after.keys()) if before.get(name) != after.get(name)]
+ if differences != [f'lib/{module}']:
+ raise ValueError(f'{key}: expected exactly one changed module, found {differences}')
+ records.append(record)
+ (destination / 'manifest.json').write_text(json.dumps(records, indent=2))
+ cards = '\n'.join(f'''<section><h2>{record['title']}</h2><p>{record['note']}</p>
+<div class="compare" style="--split:50%">
+<img src="{record['variants']['before']['image']}" alt="{record['title']} before refinement">
+<img class="after" src="{record['variants']['after']['image']}" alt="{record['title']} after library refinement">
+<span class="divider"></span><span class="label old">Before</span><span class="label new">After</span>
+</div><label class="control">Reveal refinement <input type="range" min="0" max="100" value="50" aria-label="{record['title']} comparison position"></label>
+<p class="detail">Only <code>{record['module']}</code> changed. Camera, scene, lighting and time are identical.
+<a href="{record['variants']['before']['image']}">Before image</a> · <a href="{record['variants']['after']['image']}">After image</a></p></section>'''
+ for record in records)
+ (out / 'comparison.html').write_text('''<!doctype html>
+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Graphics Lab · Refinement comparison</title><style>
+*{box-sizing:border-box}body{margin:0;background:#10191c;color:#e5e9de;font:16px/1.5 system-ui,sans-serif}
+main{max-width:1280px;margin:auto;padding:36px 24px 80px}a{color:#bdd8bb}h1{font-size:clamp(32px,5vw,64px);line-height:1.1;margin:36px 0 18px}
+h2{font-size:28px;margin:0}p{color:#aab8b5;max-width:900px}.intro{margin-bottom:48px}section{margin:0 0 60px}
+.compare{position:relative;aspect-ratio:16/9;overflow:hidden;border:1px solid #364244;background:#1e2a2e}
+.compare img{position:absolute;inset:0;width:100%;height:100%;object-fit:contain}.after{clip-path:inset(0 0 0 var(--split))}
+.divider{position:absolute;left:var(--split);height:100%;width:2px;background:#e5e9de;transform:translateX(-1px)}
+.label{position:absolute;top:14px;padding:5px 10px;background:#10191cbb;font-size:13px}.old{left:14px}.new{right:14px}
+.control{display:flex;align-items:center;gap:20px;margin-top:16px}input{flex:1;accent-color:#b6d3a7;min-width:80px}.detail{font-size:13px}code{color:#e5e9de}
+</style></head><body><main><a href="./">← Graphics Lab</a><div class="intro"><h1>Same scene. Refined library.</h1>
+<p>Drag each slider to inspect actual GPU renders. These comparisons isolate the library change; the main gallery also includes revised scene composition. Images use the production renderer and postprocessing, with no painted or generated image layers.</p>
+<a href="comparison/manifest.json">Source hashes and render records</a></div>
+''' + cards + '''</main><script>
+document.querySelectorAll('input').forEach(input=>input.addEventListener('input',()=>{
+ input.closest('section').querySelector('.compare').style.setProperty('--split',input.value+'%');
+}));
+</script></body></html>''')
+ print(f'Comparison: {out / "comparison.html"}')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/harness/examples/graphics_lab/glsl_cases/material_light.frag b/harness/examples/graphics_lab/glsl_cases/material_light.frag
new file mode 100644
index 00000000..8d94468d
--- /dev/null
+++ b/harness/examples/graphics_lab/glsl_cases/material_light.frag
@@ -0,0 +1,56 @@
+// Analytic spheres under a studio key: direct GGX and approximate environment fill.
+// No transmission, area-light solver, or path-traced indirect light is claimed.
+vec3 centre(int i) { return vec3((float(i)-1.0)*1.5,0.0,0.0); }
+float sphereHit(vec3 ro,vec3 rd,vec3 c) {
+ vec3 oc=ro-c;float b=dot(oc,rd),h=b*b-dot(oc,oc)+.64*.64;
+ if(h<0.0) return 1000.0;
+ float near=-b-sqrt(h);return near>.001?near:1000.0;
+}
+vec3 studio(vec3 d,float roughness) {
+ vec3 base=mix(vec3(.12,.09,.065),vec3(.10,.15,.23),smoothstep(-.2,.8,d.y));
+ float softbox=pow(max(dot(d,normalize(vec3(-1,2,2))),0.0),mix(72.0,4.0,roughness));
+ float strip=pow(max(dot(d,normalize(vec3(2,1,-1))),0.0),mix(100.0,8.0,roughness));
+ return base+vec3(2.8,2.5,2.0)*softbox+vec3(.4,.8,1.2)*strip;
+}
+float visibility(vec3 p,vec3 toLight) {
+ float result=1.0;
+ for(int i=0;i<3;i++) {
+ vec3 toSphere=centre(i)-p;float along=dot(toSphere,toLight);
+ if(along>.02) {
+ float distance=length(toSphere-toLight*along);
+ result=min(result,smoothstep(.58,.70+along*.08,distance));
+ }
+ }
+ return result;
+}
+void mainImage(out vec4 fragColor,in vec2 fragCoord) {
+ vec2 uv=(fragCoord-.5*u_resolution)/u_resolution.y;
+ vec3 ro=vec3(.65,1.9,5.6),target=vec3(0,-.12,0);
+ vec3 f=normalize(target-ro),r=normalize(cross(f,vec3(0,1,0))),up=cross(r,f);
+ vec3 rd=normalize(uv.x*r+uv.y*up+1.65*f);
+ float hit=1000.0;int object=-1;
+ for(int i=0;i<3;i++) {float d=sphereHit(ro,rd,centre(i));if(d<hit){hit=d;object=i;}}
+ float ground=rd.y<0.0?(-.64-ro.y)/rd.y:1000.0;
+ if(ground<hit){hit=ground;object=3;}
+ vec3 colour=studio(rd,1.0)*.45;
+ if(hit<1000.0) {
+ vec3 p=ro+rd*hit,n=object==3?vec3(0,1,0):normalize(p-centre(object)),v=-rd;
+ vec3 albedo=object==0?vec3(.65,.21,.075):object==1?vec3(.72,.51,.20):vec3(.55,.67,.72);
+ float metal=object==1?1.0:0.0,roughness=object==0?.5:object==1?.19:.12;
+ if(object==3){albedo=vec3(.18,.2,.21)*(.88+.12*noise(p.xz*18.0));roughness=.88;metal=0.0;}
+ vec3 light=normalize(vec3(-2.2+sin(u_time*.5),4.2,3.0));
+ float shadow=visibility(p+n*.002,light);
+ colour=pbrDirect(albedo,metal,roughness,n,v,light,vec3(4.3,3.9,3.3))*shadow;
+ colour+=pbrDirect(albedo,metal,roughness,n,v,normalize(vec3(3,1,-2)),vec3(.25,.50,.9));
+ vec3 fresnel=fresnelSchlick(max(dot(n,v),0.0),mix(vec3(.04),albedo,metal));
+ colour+=(1.0-metal)*(1.0-fresnel)*albedo*studio(n,1.0)*.3;
+ colour+=fresnel*studio(reflect(-v,n),roughness)*(1.0-.55*roughness);
+ if(object==3) {
+ float contact=1.0;
+ for(int i=0;i<3;i++) contact*=1.0-.45*exp(-3.5*length(p.xz-centre(i).xz));
+ colour*=contact;
+ }
+ colour=mix(colour,vec3(.08,.1,.13),1.0-exp(-hit*.008));
+ }
+ fragColor=vec4(gamma(tonemapACES(colour)),1.0);
+}
diff --git a/harness/examples/graphics_lab/glsl_cases/rain_window.frag b/harness/examples/graphics_lab/glsl_cases/rain_window.frag
new file mode 100644
index 00000000..615af3d8
--- /dev/null
+++ b/harness/examples/graphics_lab/glsl_cases/rain_window.frag
@@ -0,0 +1,27 @@
+// Rain on glass with coherent falling droplets and a defocused night street.
+// The library supplies dropsLayer, bokehSoft, hash12, tonemapACES and gamma.
+vec3 street(vec2 uv, float t) {
+ vec2 p=(uv-.5)*vec2(u_resolution.x/u_resolution.y,1.0);
+ float city=1.0-smoothstep(-.03,.35,p.y);
+ vec3 colour=vec3(.005,.008,.015)+bokehSoft(p*1.1+vec2(0,.11),t*.15)*city*1.4;
+ float horizon=exp(-pow((p.y+.10)*7.0,2.0));
+ colour+=vec3(.015,.025,.034)*horizon;
+ float traffic=exp(-pow((p.y+.29)*22.0,2.0));
+ colour+=traffic*(vec3(.3,.045,.012)*exp(-pow((p.x-.24-.035*t)*9.0,2.0))+
+ vec3(.12,.20,.32)*exp(-pow((p.x+.3+.045*t)*12.0,2.0)));
+ return colour;
+}
+void mainImage(out vec4 fragColor,in vec2 fragCoord) {
+ vec2 uv=fragCoord/u_resolution;
+ vec2 rain=dropsLayer(uv,u_time*1.2,3.8)+.35*dropsLayer(uv+3.17,u_time*.9,7.3);
+ float bead=rain.x+.3*rain.y;
+ vec2 normal=vec2(dFdx(bead),dFdy(bead))*u_resolution*vec2(.0008,.0011);
+ normal=clamp(normal,vec2(-.025),vec2(.025));
+ vec3 colour=street(uv+normal,u_time);
+ colour*=1.0-.14*rain.x;
+ float edge=length(normal);
+ colour+=street(uv+vec2(-.04,.07),u_time)*.18*smoothstep(.008,.027,edge)*(1.0-.7*rain.y);
+ colour*=.82+.18*pow(16.0*uv.x*uv.y*(1.0-uv.x)*(1.0-uv.y),.2);
+ colour+=(hash12(fragCoord)-.5)/900.0;
+ fragColor=vec4(gamma(tonemapACES(colour)),1.0);
+}
diff --git a/harness/examples/graphics_lab/glsl_cases/volume_plume.frag b/harness/examples/graphics_lab/glsl_cases/volume_plume.frag
new file mode 100644
index 00000000..135d8844
--- /dev/null
+++ b/harness/examples/graphics_lab/glsl_cases/volume_plume.frag
@@ -0,0 +1,53 @@
+// Prescribed rising density, not a fluid simulation. Metre-space integration.
+float plumeDensity(vec3 p,float t) {
+ float height=p.y;
+ if(height<0.0||height>3.0) return 0.0;
+ float age=height/.65;
+ vec2 drift=vec2(.08*age,.03*age)+vec2(.10*sin(height*3.0-t*1.1),.09*cos(height*2.7-t*.9))*height;
+ vec3 q=vec3(p.xz-drift,height-t*.65);
+ vec3 warp=vec3(noise3(q*2.5),noise3(q*2.5+13.0),noise3(q*2.5+29.0))-.5;
+ float coarse=fbmVolume(q*3.2+warp*.8+vec3(4.2,1.7,0.0));
+ float radius=.12+.21*height;
+ float body=max(0.0,1.0-length(p.xz-drift)/radius+(coarse-.47)*2.8);
+ float detail=fbmVolume(q*9.7+vec3(13.0,7.0,t*.13));
+ return max(0.0,body*.65-(1.0-detail)*.25)*
+ smoothstep(0.0,.13,height)*(1.0-smoothstep(2.1,3.0,height));
+}
+void mainImage(out vec4 fragColor,in vec2 fragCoord) {
+ vec2 uv=(fragCoord-.5*u_resolution)/u_resolution.y;
+ vec3 ro=vec3(3.0,2.7,5.0),target=vec3(.1,1.3,0);
+ vec3 f=normalize(target-ro),right=normalize(cross(f,vec3(0,1,0))),up=cross(right,f);
+ vec3 rd=normalize(uv.x*right+uv.y*up+1.55*f);
+ vec3 toSun=normalize(vec3(-1.5,2.5,-1.0));
+ vec3 horizon=vec3(.06,.085,.11);
+ vec3 background=mix(horizon,vec3(.025,.055,.085),smoothstep(0.0,.6,rd.y));
+ float ground=rd.y<0.0?-ro.y/rd.y:1000.0;
+ if(ground<1000.0) {
+ vec3 p=ro+rd*ground;
+ background=vec3(.035,.041,.046)*(.92+.08*noise(p.xz*12.0));
+ background=mix(background,horizon,1.0-exp(-ground*.06));
+ background*=1.0-.5*exp(-dot(p.xz,p.xz)*3.0);
+ }
+ vec3 inv=1.0/(rd+vec3(1e-7));
+ vec3 nearBox=(vec3(-1.4,0,-1.4)-ro)*inv,farBox=(vec3(1.4,3,1.4)-ro)*inv;
+ vec3 lower=min(nearBox,farBox),upper=max(nearBox,farBox);
+ float enter=max(0.0,max(lower.x,max(lower.y,lower.z))),leave=min(ground,min(upper.x,min(upper.y,upper.z)));
+ vec3 colour=vec3(0);float transmission=1.0;
+ if(leave>enter) {
+ float stepLength=(leave-enter)/64.0;
+ for(int i=0;i<64;i++) {
+ vec3 p=ro+rd*(enter+(float(i)+.5)*stepLength);
+ float density=plumeDensity(p,u_time),lightDepth=0.0;
+ if(density>.001) {
+ for(int j=0;j<6;j++) lightDepth+=plumeDensity(p+toSun*(float(j)+.5)*.18,u_time)*.18;
+ float stepT=beerTransmittance(density*3.6,stepLength);
+ vec3 illumination=vec3(.075,.12,.17)+vec3(7.0,5.9,4.4)*
+ phaseHG(dot(rd,toSun),.45)*beerTransmittance(lightDepth*3.6,1.0);
+ colour+=transmission*(1.0-stepT)*illumination;
+ transmission*=stepT;
+ }
+ if(transmission<.015) break;
+ }
+ }
+ fragColor=vec4(gamma(tonemapACES(colour+transmission*background)),1.0);
+}
diff --git a/harness/examples/graphics_lab/index.html b/harness/examples/graphics_lab/index.html
new file mode 100644
index 00000000..3d7854df
--- /dev/null
+++ b/harness/examples/graphics_lab/index.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Graphics Lab · Material & Motion</title><link rel="stylesheet" href="./viewer.css">
+<script type="importmap">{"imports":{"three":"/__runtime/node_modules/three/build/three.module.js","three/addons/":"/__runtime/node_modules/three/examples/jsm/"}}</script>
+</head><body>
+<header><a class="brand" href="./">3D CODEVERSE <span>/ GRAPHICS LAB</span></a><span class="edition">MATERIAL & MOTION</span></header>
+<main><section class="intro"><p class="eyebrow">NATURE, MATERIALS & ATMOSPHERE</p><h1>Light. Form. Motion.</h1>
+<p>Fire, water, stone, living vegetation and changing weather. Explore library studies and independently authored agent scenes, from cloud banks and waterfalls to intimate material details. Watch the films or step inside each scene.</p><!--COMPARISON_LINK--></section>
+<section id="gallery" aria-label="Scene gallery"></section>
+<section id="stage" hidden><div class="stage-heading"><div><p class="eyebrow" id="category"></p><h2 id="title"></h2><p id="subtitle"></p></div>
+<button id="close" class="quiet">Back to gallery ↗</button></div>
+<div id="screen"><video id="video" controls loop playsinline></video><div id="live" hidden><canvas id="canvas"></canvas></div><p id="status" role="status"></p></div>
+<div class="toolbar"><div class="tabs"><button id="watch" class="active">Watch film</button><button id="explore">Explore live</button></div>
+<div class="live-controls" hidden><button id="pause">Pause</button><label>Camera <select id="camera"></select></label>
+<label>Time <input id="time" type="range" min="0" max="20" step=".02" value="0"></label><output id="seconds">0.00 s</output></div>
+<a id="still" href="#" target="_blank">Open still ↗</a></div>
+<p id="hint">Films are rendered frame by frame from scene code. In live mode, drag to orbit and scroll to zoom.</p></section>
+</main><footer><span>THREE.JS · LOCAL RENDERING</span><span>Procedural scenes. Every frame comes from code.</span></footer>
+<script type="module" src="./viewer.js"></script></body></html>
diff --git a/harness/examples/graphics_lab/package.py b/harness/examples/graphics_lab/package.py
new file mode 100644
index 00000000..d8b1d515
--- /dev/null
+++ b/harness/examples/graphics_lab/package.py
@@ -0,0 +1,325 @@
+"""Package six published studies without rebuilding or rendering anything.
+
+python examples/graphics_lab/package.py --out examples/graphics_lab/output --name studies_v2
+Existing packages are never overwritten. Uses only the Python standard library.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import html
+import json
+import math
+import re
+import shutil
+import tempfile
+import zipfile
+from datetime import UTC, datetime
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+
+
+def digest(path: Path) -> str:
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def write_json(path: Path, data: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+
+
+def local_file(root: Path, relative: str) -> Path:
+ path = (root / relative).resolve()
+ if not path.is_relative_to(root) or not path.is_file():
+ raise ValueError(f"Missing or out-of-root published file: {relative}")
+ return path
+
+
+def check_hash(path: Path, expected: str) -> None:
+ if digest(path) != expected:
+ raise ValueError(f"Published source hash mismatch: {path}")
+
+
+def capture_record(path: Path, contents: bytes | None = None) -> dict:
+ record = json.loads(contents if contents is not None else path.read_bytes())
+ if not record.get("ok") or record.get("console_errors") or record.get("shader_errors"):
+ raise ValueError(f"Capture did not complete cleanly: {path}")
+ for field in ("width", "height", "fps", "frames", "seconds"):
+ value = record.get(field)
+ if not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
+ raise ValueError(f"Invalid capture {field}: {path}")
+ if not math.isclose(record["frames"] / record["fps"], record["seconds"], abs_tol=0.01):
+ raise ValueError(f"Capture frame count and duration disagree: {path}")
+ return record
+
+
+def verify_capture_sources(out: Path, scene: str, record: dict, libraries: dict,
+ shaders: dict | None = None) -> dict:
+ """Prefer the capture-time hashes; older sidecars only identify a camera."""
+ if "source_sha256" not in record:
+ return {"mode": "legacy_without_capture_source_hashes", "files_checked": 0}
+ hashes = record["source_sha256"]
+ required = {f"lib/{name}" for name in libraries} | {f"scenes/{scene}.js", "scene.js"}
+ required.update(f"shaders/{name}" for name in (shaders or {}))
+ if not isinstance(hashes, dict) or not required.issubset(hashes):
+ raise ValueError(f"Capture source hashes are incomplete: {scene}")
+ staged = out / "cases" / scene / "src"
+ for relative, expected in hashes.items():
+ if staged.is_dir():
+ check_hash(local_file(staged.resolve(), relative), expected)
+ elif relative == "scene.js":
+ wrapper = f"export {{createScene}} from './scenes/{scene}.js';\n"
+ if hashlib.sha256(wrapper.encode()).hexdigest() != expected:
+ raise ValueError(f"Cannot verify nonstandard capture entry point without staged workspace: {scene}")
+ elif relative in required:
+ check_hash(local_file((out / "src").resolve(), relative), expected)
+ else:
+ raise ValueError(f"Cannot verify captured source without staged workspace: {scene}/{relative}")
+ return {"mode": "capture_source_hashes", "files_checked": len(hashes),
+ "reference": "staged_workspace" if staged.is_dir() else "published_sources_and_standard_entry"}
+
+
+def offline_page(cases: list[dict], videos: list[dict]) -> str:
+ titles = {case["id"]: case["title"] for case in cases}
+ cards = []
+ for video in videos:
+ scene, key, capture = video["origin_scene_id"], video["origin_video_id"], video["capture"]
+ title = titles[scene] if key == scene else "Extra: Fire at the hearth"
+ details = f"{capture['width']} × {capture['height']} · {capture['fps']} fps · {capture['seconds']} seconds"
+ cards.append(
+ f'<article><h2>{html.escape(title)}</h2>'
+ f'<video controls playsinline preload="metadata" poster="previews/{scene}.png">'
+ f'<source src="videos/{key}.mp4" type="video/mp4"></video>'
+ f'<p>{details}</p><nav><a href="videos/{key}.mp4" download>Download video</a>'
+ f'<a href="src/scenes/{scene}.js">Scene source</a>'
+ f'<a href="previews/{scene}.png">Preview</a></nav></article>'
+ )
+ return """<!doctype html><html lang="en"><head><meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Graphics Lab: Six Published Studies</title><style>
+*{box-sizing:border-box}body{margin:0;background:#101716;color:#edf0e9;font:16px/1.6 system-ui,sans-serif}
+header,main,footer{max-width:1320px;margin:auto;padding:32px}h1{font-size:clamp(32px,5vw,60px);line-height:1.1}
+main{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,430px),1fr));gap:26px}
+article{background:#18211f;border:1px solid #34443b;border-radius:14px;overflow:hidden}
+h2{font-size:20px;font-weight:550;margin:18px 20px}video{width:100%;display:block;aspect-ratio:16/9;background:#060908}
+article p,nav{padding:0 20px}p,footer{color:#b6c5bb}nav{display:flex;flex-wrap:wrap;gap:20px;padding-bottom:22px}
+a{color:#d2e2ae;text-underline-offset:4px}</style></head><body><header>
+<h1>Six studies in light and nature.</h1><p>The first six published manual library studies, with existing
+films and source code. Open this page directly to watch offline.</p><a href="README.md">Package notes</a>
+ · <a href="manifest.json">Source and capture manifest</a></header><main>""" + "".join(cards) + """</main>
+<footer>The video page needs no server, JavaScript or network access. Executing the Three.js scenes
+requires a compatible runtime; see <a href="README.md">README.md</a>.</footer></body></html>
+"""
+
+
+def readme(cases: list[dict], library_count: int) -> str:
+ table = "\n".join(
+ f"| {c['id']} | `src/scenes/{c['id']}.js` | `videos/{c['id']}.mp4` | `previews/{c['id']}.png` |"
+ for c in cases
+ )
+ return f"""# Graphics Lab: first six published studies
+
+This package is a snapshot of the supplied gallery's first six manual library studies.
+Scene code and all {library_count} shared library modules are byte-for-byte copies of that gallery,
+validated against its published manifest. Films and previews are existing gallery assets.
+Later gallery changes are excluded. No source rebuild, rendering, dependency download or model
+call occurs during packaging.
+
+## Watch offline
+
+Open `index.html` directly in a browser using a `file://` URL. The video page needs no installation,
+server, JavaScript or network access. MP4 files in `videos/` can be uploaded individually.
+If included, `hearth.mp4` is a second camera from the fire scene.
+Original resolution, duration, frame rate and renderer records are in `provenance/captures/`.
+
+| ID | Scene code | Film | Preview |
+| --- | --- | --- | --- |
+{table}
+
+## Run the scene source
+
+Scenes export `createScene({{ THREE, renderer, loaders }})`, returning the scene, authored cameras
+and update function. `src/scene.js` selects fire by default; change its export path to another ID.
+Keep `src/scenes/` beside `src/lib/` and `src/shaders/` (when present) so relative imports resolve.
+
+Executing the code requires Three.js r182 (`three` 0.182.x), WebGL 2, ES module resolution for
+`three` and `three/addons/`, and a compatible scene host. The original harness uses Node.js 20.6+
+and Chromium through Puppeteer. Its host configures sRGB output, ACES tone mapping, filtered
+shadows and a post-processing chain including ambient occlusion, bloom and grading. Another
+host can produce a different appearance. Runtime code and npm dependencies are not bundled.
+
+## Provenance and integrity
+
+`manifest.json` records SHA-256 and size for every payload file except itself, plus original
+scene/video IDs and capture records. `provenance/published_selection.json` preserves expected
+scene/library hashes, the original published manifest digest, and staged-workspace comparisons
+where those workspaces exist. The packager verifies the ZIP CRC and every extracted file hash.
+
+When a capture sidecar includes `source_sha256`, every recorded source hash is verified against
+the retained capture workspace. If that workspace is absent, the published scene/library files
+and the standard generated entry point are checked instead. Mismatches stop packaging.
+Per-video `source_verification` records the evidence used. Legacy sidecars without source hashes
+are explicitly marked: for those films, published/staged source agreement is not a direct
+source-to-video hash binding. Capture records are not a new playback or aesthetic evaluation.
+When present, the encoded MP4 digest and retained input-frame hashes are also checked.
+Input frames keep their original paths under `capture_frames/`; paths recorded in original
+capture metadata resolve from this package's root, not from `provenance/captures/`.
+
+The package excludes model-run records, credentials, environment files and `node_modules`.
+The offline video page is independent of the Three.js runtime.
+"""
+
+
+def build_package(out: Path, name: str) -> dict:
+ out = out.resolve()
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", name):
+ raise ValueError("Package name must be one folder name using letters, digits, '.', '_' or '-'")
+ packages = out / "packages"
+ destination, archive = packages / name, packages / f"{name}.zip"
+ if destination.exists() or archive.exists():
+ raise FileExistsError(f"Package already exists; choose a new --name: {destination}")
+ published_file = local_file(out, "manifest.json")
+ published_hash = digest(published_file)
+ published = json.loads(published_file.read_text(encoding="utf-8"))
+ cases = published["cases"][:6]
+ if len(cases) != 6 or any(c.get("source_kind") != "library_study" for c in cases):
+ raise ValueError("The first six published cases must be manual library studies")
+ ids = [case["id"] for case in cases]
+ if len(set(ids)) != 6 or "fire" not in ids or any(not re.fullmatch(r"[a-z0-9_]+", i) for i in ids):
+ raise ValueError("Scene IDs must be unique safe filenames and include fire")
+ libraries = published["library_sha256"]
+ shaders = published.get("shader_sha256", {})
+ actual = {p.name for p in (out / "src/lib").iterdir() if p.is_file()}
+ if not libraries or actual != set(libraries):
+ raise ValueError("Published library files and manifest entries disagree")
+ packages.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix=".package-", dir=packages) as temp:
+ work = Path(temp) / name
+ work.mkdir()
+ origins, checks, videos = {}, [], []
+
+ def copy(source: Path, relative: str, expected: str | None = None) -> None:
+ expected = expected or digest(source)
+ target = work / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, target)
+ check_hash(target, expected)
+ origins[relative] = source.relative_to(out).as_posix()
+
+ for filename, expected in sorted(libraries.items()):
+ if Path(filename).name != filename or not filename.endswith(".js"):
+ raise ValueError(f"Invalid shared library filename: {filename}")
+ copy(local_file(out, f"src/lib/{filename}"), f"src/lib/{filename}", expected)
+ for filename, expected in sorted(shaders.items()):
+ if (Path(filename).is_absolute() or ".." in Path(filename).parts
+ or Path(filename).suffix not in {".glsl", ".vert", ".frag"}):
+ raise ValueError(f"Invalid external shader filename: {filename}")
+ copy(local_file(out, f"src/shaders/{filename}"), f"src/shaders/{filename}", expected)
+ for case in cases:
+ key = case["id"]
+ copy(local_file(out, case["module"]), f"src/scenes/{key}.js", case["scene_sha256"])
+ preview = local_file(out, f"{key}.png")
+ with preview.open("rb") as stream:
+ if stream.read(8) != b"\x89PNG\r\n\x1a\n":
+ raise ValueError(f"Preview is not a PNG: {preview}")
+ copy(preview, f"previews/{key}.png")
+ staged = out / "cases" / key / "src"
+ if staged.exists():
+ check_hash(staged / "scenes" / f"{key}.js", case["scene_sha256"])
+ for filename, expected in libraries.items():
+ check_hash(staged / "lib" / filename, expected)
+ for filename, expected in shaders.items():
+ check_hash(staged / "shaders" / filename, expected)
+ checks.append({"scene_id": key, "published_hash_matches": True,
+ "staged_workspace_present": staged.exists(),
+ "staged_library_files_checked": len(libraries) if staged.exists() else 0,
+ "staged_shader_files_checked": len(shaders) if staged.exists() else 0})
+ video_ids = [(key, key) for key in ids]
+ if (out / "hearth.mp4").exists():
+ video_ids.append(("fire", "hearth"))
+ for scene, key in video_ids:
+ source = local_file(out, f"{key}.mp4")
+ with source.open("rb") as stream:
+ if stream.read(12)[4:8] != b"ftyp":
+ raise ValueError(f"Video is not an MP4 container: {source}")
+ capture = local_file(out, f"{key}.capture.json")
+ capture_bytes = capture.read_bytes()
+ capture_digest = hashlib.sha256(capture_bytes).hexdigest()
+ record = capture_record(capture, capture_bytes)
+ verification = verify_capture_sources(out, scene, record, libraries, shaders)
+ video_digest = record.get("video_sha256") or digest(source)
+ if record.get("video_sha256"):
+ check_hash(source, video_digest)
+ verification["encoded_digest_checked"] = True
+ references = record.get("reference_frames", [])
+ for reference in references:
+ relative = reference["path"]
+ if (Path(relative).is_absolute() or ".." in Path(relative).parts
+ or not relative.startswith("capture_frames/") or not relative.endswith(".png")):
+ raise ValueError(f"Invalid retained input frame path: {relative}")
+ copy(local_file(out, relative), relative, reference["sha256"])
+ verification["retained_input_frames_checked"] = len(references)
+ copy(source, f"videos/{key}.mp4", video_digest)
+ copy(capture, f"provenance/captures/{key}.capture.json", capture_digest)
+ videos.append({"video": f"videos/{key}.mp4", "origin_scene_id": scene,
+ "origin_video_id": key, "capture": record,
+ "source_verification": verification})
+ (work / "src/scene.js").write_text("export { createScene } from './scenes/fire.js';\n", encoding="utf-8")
+ (work / "README.md").write_text(readme(cases, len(libraries)), encoding="utf-8")
+ (work / "index.html").write_text(offline_page(cases, videos), encoding="utf-8")
+ provenance = {"published_manifest_sha256": published_hash, "selected_cases": cases,
+ "library_sha256": libraries, "shader_sha256": shaders, "source_checks": checks}
+ write_json(work / "provenance/published_selection.json", provenance)
+ files = {}
+ for file in sorted(work.rglob("*")):
+ if not file.is_file():
+ continue
+ relative = file.relative_to(work).as_posix()
+ if file.suffix in {".js", ".html", ".md", ".glsl", ".vert", ".frag"} and re.search(r"[\u3400-\u9fff]", file.read_text(encoding="utf-8")):
+ raise ValueError(f"Example text must be English: {relative}")
+ files[relative] = {"sha256": digest(file), "bytes": file.stat().st_size,
+ "origin": origins.get(relative, "Generated package metadata or offline viewer")}
+ manifest = {"package_name": name, "created_utc": datetime.now(UTC).isoformat(),
+ "default_scene_id": "fire", "shared_library_count": len(libraries),
+ "published_manifest_sha256": published_hash, "scenes": cases,
+ "videos": videos, "source_checks": checks,
+ "integrity_scope": "All payload files except manifest.json itself", "files": files}
+ write_json(work / "manifest.json", manifest)
+ check_hash(published_file, published_hash)
+ expected_files = {p.relative_to(work).as_posix(): digest(p) for p in work.rglob("*") if p.is_file()}
+ temporary_zip = Path(temp) / f"{name}.zip"
+ with zipfile.ZipFile(temporary_zip, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as zipped:
+ for relative in sorted(expected_files):
+ zipped.write(work / relative, f"{name}/{relative}")
+ with zipfile.ZipFile(temporary_zip) as zipped:
+ expected_names = {f"{name}/{relative}" for relative in expected_files}
+ if zipped.testzip() is not None or set(zipped.namelist()) != expected_names:
+ raise ValueError("ZIP CRC or file list verification failed")
+ extracted = Path(temp) / "verify"
+ zipped.extractall(extracted)
+ for relative, expected in expected_files.items():
+ check_hash(extracted / name / relative, expected)
+ if destination.exists() or archive.exists():
+ raise FileExistsError(f"Package appeared during packaging: {destination}")
+ work.rename(destination)
+ temporary_zip.rename(archive)
+ return {"folder": str(destination), "zip": str(archive), "files": len(expected_files),
+ "zip_bytes": archive.stat().st_size, "zip_sha256": digest(archive),
+ "source_manifest": "pass", "zip_crc_and_extracted_hashes": "pass"}
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--out", type=Path, default=HERE / "output", help="Existing published gallery root")
+ parser.add_argument("--name", required=True, help="New folder/ZIP name under <out>/packages")
+ args = parser.parse_args()
+ try:
+ print(json.dumps(build_package(args.out, args.name), indent=2))
+ except (OSError, ValueError, KeyError, TypeError) as error:
+ parser.exit(1, f"Package failed: {error}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/harness/examples/graphics_lab/scenes/campfire.js b/harness/examples/graphics_lab/scenes/campfire.js
new file mode 100644
index 00000000..67298c4c
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/campfire.js
@@ -0,0 +1,182 @@
+/** Two fuel-bed scales: a campfire and open bonfire in a wooded clearing. */
+import * as THREE from 'three';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+import { makeFireField } from '../lib/firefield.js';
+import { makeRock } from '../lib/rock.js';
+import { makeTree } from '../lib/tree.js';
+import { makeMeadow } from '../lib/meadow.js';
+import { patchStandard } from '../lib/shader.js';
+import { patchMicroBreakup } from '../lib/surface_wear.js';
+import { attachDisposal, snapshotResources } from '../lib/lifecycle.js';
+import { fbm2, mulberry32 } from '../lib/noise.js';
+
+const smooth = THREE.MathUtils.smoothstep;
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(0x202d35);
+ scene.fog = new THREE.FogExp2(0x202d35, .044);
+ scene.add(new THREE.HemisphereLight(0x9cb3c3, 0x241a11, .65));
+ const moon = new THREE.DirectionalLight(0xaabdc9, 1.15);
+ moon.position.set(-7, 12, -5); moon.castShadow = true;
+ moon.shadow.mapSize.set(2048, 2048); moon.shadow.normalBias = .009;
+ Object.assign(moon.shadow.camera, {left:-14, right:17, top:14, bottom:-14, far:38});
+ scene.add(moon);
+ const actors = [], random = mulberry32(341);
+ const ownEffect = object => { actors.push(object); return object; };
+ const groundHeight = (x, z) => fbm2(x * .22, z * .22, {seed:43, octaves:3}) * .23
+ * smooth(Math.hypot(x, z), 1.2, 3.0) * smooth(Math.hypot(x-8, z+1), 2.8, 4.5);
+ const groundMat = new THREE.MeshStandardMaterial({color:0x51483b, roughness:.98});
+ patchStandard(groundMat, {name:'CampSoil',
+ vertexHead:'varying vec3 vCampEarth;',
+ vertexBody:'vCampEarth=(modelMatrix*vec4(transformed,1.0)).xyz;',
+ fragmentHead:'varying vec3 vCampEarth;',
+ fragmentBody:`
+ float campSoil=astraFbm2(vCampEarth.xz*13.0,4);
+ float campBed=min(length(vCampEarth.xz),length(vCampEarth.xz-vec2(8.0,-1.0))/2.6);
+ float campAsh=(1.0-smoothstep(.40,.73,campBed))
+ *smoothstep(.24,.73,astraFbm2(vCampEarth.xz*31.0,3));
+ diffuseColor.rgb*=.63+campSoil*.60;
+ diffuseColor.rgb=mix(diffuseColor.rgb,vec3(.14,.13,.115),campAsh*.68);
+ `});
+ patchMicroBreakup(groundMat, {scale:.055, strength:.14, seed:41});
+ const groundGeometry = new THREE.PlaneGeometry(150, 150, 220, 220);
+ groundGeometry.rotateX(-Math.PI/2);
+ const gp = groundGeometry.attributes.position;
+ for(let i=0; i<gp.count; i++) gp.setY(i,groundHeight(gp.getX(i),gp.getZ(i)));
+ groundGeometry.computeVertexNormals();
+ const ground = new THREE.Mesh(groundGeometry, groundMat);
+ ground.name='ForestClearing'; ground.receiveShadow=true; scene.add(ground);
+ const grass=ownEffect(makeMeadow({size:[34,28], ground:false, density:360,
+ height:.12, bladeWidth:.006, maxBlades:135000, dry:.43, seed:31,
+ heightAt:groundHeight, shadows:false,
+ mask:(x,z)=>smooth(Math.hypot(x,z),1.04,2.0)*smooth(Math.hypot(x-8,z+1),2.65,3.7),
+ wind:{strength:.12,speed:.8}}));scene.add(grass);
+ const grove=[[-9,-6],[-9.6,-10],[-.7,-10],[3.7,-11],[9.4,-10],
+ [13,-6],[-8.5,.5],[15,1.5],[-2.8,-17],[6.8,-19]];
+ for(let i=0;i<grove.length;i++) {
+ const tree=ownEffect(makeTree({species:i%4===0?'birch':'oak', height:7+random()*2.8,
+ crownRadius:2.6+random()*.9, leafDensity:.8, maxLeaves:11000, leafSegments:4,
+ seed:140+i, wind:{strength:.12,speed:.7}, shadows:false}));
+ const [x,z]=grove[i];tree.position.set(x,groundHeight(x,z),z);scene.add(tree);
+ }
+
+ // Preserve local log coordinates when batching. Fine cracks emit between
+ // dark charcoal blocks; powdery ash remains a rough reflective surface.
+ const char = new THREE.MeshStandardMaterial({color:0x2c2722, roughness:.96});
+ patchStandard(char,{name:'CampChar',
+ vertexHead:'attribute vec3 fuelLocal; attribute float fuelEnd; varying vec3 vFuel; varying float vFuelEnd;',
+ vertexBody:'vFuel=fuelLocal;vFuelEnd=fuelEnd;', fragmentHead:`
+ varying vec3 vFuel; varying float vFuelEnd;
+ vec3 campCharField(vec3 p) {
+ float theta=atan(p.z+1e-7,p.x+1e-7);
+ vec2 q=mix(vec2(theta*3.0,p.y*19.0),p.xz*43.0,step(.5,vFuelEnd));
+ q+=vec2(astraNoise2(q*.44),astraNoise2(q*.39+19.0))*.85;
+ vec2 cell=abs(fract(q)-.5);
+ float crack=smoothstep(.445,.495,max(cell.x,cell.y));
+ float ash=smoothstep(.40,.73,astraFbm2(q*.8+vec2(2.0,11.0),3));
+ float heat=smoothstep(.54,.75,astraFbm2(q*.71+2.7,3));
+ return vec3(crack,ash,heat);
+ }
+ `, fragmentBody:`
+ vec3 charField=campCharField(vFuel);
+ diffuseColor.rgb*=.52+.42*astraNoise2(vec2(atan(vFuel.z+1e-7,vFuel.x+1e-7)*42.0,vFuel.y*4.0));
+ diffuseColor.rgb=mix(diffuseColor.rgb,vec3(.19,.175,.16),charField.y*.67);
+ diffuseColor.rgb*=1.0-charField.x*.70;
+ `, normalBody:`
+ float charRelief=(1.0-campCharField(vFuel).x)*.00075;
+ vec3 charDx=dFdx(-vViewPosition),charDy=dFdy(-vViewPosition);
+ vec3 charR1=cross(charDy,normal),charR2=cross(normal,charDx);
+ float charDet=dot(charDx,charR1);
+ normal=normalize(normal-sign(charDet)*(dFdx(charRelief)*charR1+dFdy(charRelief)*charR2)
+ /max(abs(charDet),1e-9));
+ `, outputBody:`
+ vec3 charEmission=campCharField(vFuel);
+ gl_FragColor.rgb+=vec3(.32,.017,.0005)*charEmission.x*charEmission.z*(1.0-charEmission.y*.7);
+ `});
+ const coalMaterial=new THREE.MeshStandardMaterial({color:0x201e1b, roughness:.98});
+ patchStandard(coalMaterial,{name:'CampCoals',
+ vertexHead:'attribute float coalHeat; varying float vCoalHeat; varying vec3 vCoalLocal;',
+ vertexBody:'vCoalHeat=coalHeat;vCoalLocal=position;',
+ fragmentHead:'varying float vCoalHeat; varying vec3 vCoalLocal;',
+ fragmentBody:`
+ float coalAsh=smoothstep(.34,.67,astraNoise2(vCoalLocal.xz*5.0+vCoalHeat*21.0));
+ diffuseColor.rgb=mix(diffuseColor.rgb,vec3(.12,.115,.10),coalAsh*.7);
+ `, outputBody:`
+ float coalLine=1.0-smoothstep(.025,.11,abs(astraFbm2(vCoalLocal.xy*7.0,3)-.49));
+ gl_FragColor.rgb+=vec3(.95,.032,.0008)*coalLine*vCoalHeat*vCoalHeat;
+ `});
+
+ function fuelBed(x,z,scale,seed) {
+ const group=new THREE.Group();group.name='CharredFuelBed';group.position.set(x,0,z);scene.add(group);
+ const rand=mulberry32(seed), parts=[], transform=new THREE.Matrix4();
+ const position=new THREE.Vector3(), rotation=new THREE.Quaternion(), euler=new THREE.Euler();
+ for(let i=0;i<12;i++) {
+ const angle=i/12*Math.PI*2+.09*rand();
+ const rock=ownEffect(makeRock({type:'granite', seed:seed+i,
+ size:[(.25+rand()*.10)*scale,(.18+rand()*.06)*scale,(.22+rand()*.10)*scale],
+ detail:4, weathering:1.7, color:0x625f57, moisture:.2, burial:.045}));
+ rock.position.set(Math.cos(angle)*.72*scale,0,Math.sin(angle)*.72*scale);
+ rock.rotation.y=rand()*Math.PI*2;group.add(rock);
+ }
+ for(let i=0;i<8;i++) {
+ const geometry=new THREE.CylinderGeometry((.045+rand()*.021)*scale,
+ (.065+rand()*.021)*scale,(.70+rand()*.24)*scale,20,16);
+ const p=geometry.attributes.position;
+ for(let j=0;j<p.count;j++) {
+ const irregular=1+.06*Math.sin(p.getY(j)*29/scale+i)+.035*Math.sin(p.getY(j)*61/scale+p.getX(j)*17/scale);
+ const endWear=Math.sign(p.getY(j))*.010*scale
+ *Math.sin(p.getX(j)*91/scale+i)*Math.cos(p.getZ(j)*76/scale-i);
+ p.setXYZ(j,p.getX(j)*irregular,p.getY(j)+endWear,p.getZ(j)*irregular);
+ }
+ geometry.computeVertexNormals();
+ const normals=geometry.attributes.normal;
+ geometry.setAttribute('fuelEnd',new THREE.Float32BufferAttribute(
+ Array.from({length:p.count},(_,j)=>Math.abs(normals.getY(j))),1));
+ const local=p.clone();for(let j=0;j<local.count;j++)local.setXYZ(j,local.getX(j)/scale,local.getY(j)/scale,local.getZ(j)/scale);
+ geometry.setAttribute('fuelLocal',local);
+ euler.set(Math.PI*.5+(rand()-.5)*.31,0,i*1.93);
+ rotation.setFromEuler(euler);
+ position.set((rand()-.5)*.25*scale,(.10+i*.018)*scale,(rand()-.5)*.25*scale);
+ geometry.applyMatrix4(transform.compose(position,rotation,new THREE.Vector3(1,1,1)));parts.push(geometry);
+ }
+ const logs=new THREE.Mesh(mergeGeometries(parts),char);parts.forEach(p=>p.dispose());
+ logs.name='PartlyConsumedLogs';logs.castShadow=logs.receiveShadow=true;group.add(logs);
+ const count=210,coalGeometry=new THREE.DodecahedronGeometry(1,1),heat=new Float32Array(count);
+ const coals=new THREE.InstancedMesh(coalGeometry,coalMaterial,count);coals.name='AshAndCoal';
+ for(let i=0;i<count;i++) {
+ const angle=rand()*Math.PI*2,r=Math.sqrt(rand())*.46*scale,s=(.007+rand()*.021)*scale;
+ position.set(Math.cos(angle)*r,.35*s+.003*scale,Math.sin(angle)*r);
+ rotation.setFromEuler(euler.set(rand(),rand(),rand()));
+ transform.compose(position,rotation,new THREE.Vector3(s,s*.34,s*.8));coals.setMatrixAt(i,transform);
+ heat[i]=.1+Math.pow(rand(),1.8)*.9;
+ }
+ coalGeometry.setAttribute('coalHeat',new THREE.InstancedBufferAttribute(heat,1));
+ coals.receiveShadow=true;coals.computeBoundingSphere();group.add(coals);
+ return group;
+ }
+ const fuel=fuelBed(0,0,1,7),bigFuel=fuelBed(8,-1,2.6,29);
+ const fire=ownEffect(makeFireField({name:'CampsiteFire',seed:51,quality:'high',wind:[.06,.035],intensity:.8,
+ emitters:[{position:[-.23,.10,.08],radius:.18,height:.73},{position:[.20,.14,-.02],radius:.20,height:1.05},
+ {position:[-.04,.16,-.22],radius:.18,height:.90},{position:[.09,.10,.23],radius:.17,height:.65}],
+ smoke:{height:3.6,density:.6,albedo:0x685f54},embers:{count:42,size:[.001,.0045],lifetime:[1.5,3]},
+ lighting:{count:2,intensity:2.6},occluders:[fuel,ground],depthResolution:768}));scene.add(fire);
+ const bonfire=ownEffect(makeFireField({name:'OpenBonfire',seed:79,quality:'high',wind:[.23,.08],intensity:.8,
+ emitters:[{position:[-.54,.22,.1],radius:.52,height:2.3},{position:[.42,.24,.12],radius:.48,height:2.8},
+ {position:[.03,.30,-.53],radius:.44,height:2.5},{position:[.14,.18,.53],radius:.47,height:1.9}],
+ smoke:{height:8,density:.48,albedo:0x504a43},embers:{count:120,size:[.002,.009],lifetime:[2,5]},
+ lighting:{count:3,intensity:14},occluders:[bigFuel,ground],depthResolution:768}));
+ bonfire.position.set(8,0,-1);scene.add(bonfire);
+
+ const resources=snapshotResources(scene);
+ for(const actor of actors) {
+ for(const resource of snapshotResources(actor))resources.delete(resource);
+ resources.add({dispose:()=>actor.userData.dispose()});
+ }
+ resources.add({dispose:()=>moon.shadow.dispose()});attachDisposal(scene,resources);
+ return {scene,cameras:[
+ {name:'campfire',position:[1.9,1.25,2.7],lookAt:[0,.69,0],fov:42},
+ {name:'embers_and_char',position:[.85,.58,1.22],lookAt:[0,.34,0],fov:44},
+ {name:'open_bonfire',position:[12.9,3.4,5.7],lookAt:[8,2,-1],fov:43},
+ ],update(t,dt){actors.forEach(actor=>actor.userData.update(t,dt));},dispose(){scene.userData.dispose();}};
+}
diff --git a/harness/examples/graphics_lab/scenes/cloud_volume.js b/harness/examples/graphics_lab/scenes/cloud_volume.js
new file mode 100644
index 00000000..5f4879f2
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/cloud_volume.js
@@ -0,0 +1,110 @@
+/** Mountain lake under a drifting, self-shadowed cumulus field. */
+import * as THREE from 'three';
+import { makeCloudVolume } from '../lib/cloudvolume.js';
+import { makeOcean } from '../lib/water.js';
+import { makeRock } from '../lib/rock.js';
+import { makeMeadow } from '../lib/meadow.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { fbm2 } from '../lib/noise.js';
+
+export const BOUNDS = { min: [-90, -5, -120], max: [90, 35, 90] };
+export function heightAt(x, z) {
+ const bank = .095 * z + .015 * x;
+ return -3 + Math.max(0, bank) + fbm2(x * .07, z * .07, { seed: 27 }) * 2;
+}
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ const rig = sunRig({ mood: 'day', azimuth: -135, elevation: 32, bounds: 70, disc: false });
+ scene.add(rig.sun, rig.fill);
+ scene.environment = rig.envTex;
+ scene.fog = new THREE.FogExp2(0xb2cad8, .00075);
+ makeSky(scene, { rig, turbidity: 2.3, rayleigh: 1.45, scale: 8000 });
+
+ const cloudOptions = [
+ { size: [980, 660, 750], position: [-220, 700, -1900], seed: 29, coverage: .64 },
+ { size: [1200, 520, 680], position: [900, 560, -2900], seed: 54, coverage: .61 },
+ { size: [1300, 390, 680], position: [-1450, 540, -3200], seed: 87, coverage: .66 },
+ ];
+ const clouds = cloudOptions.map(({ position, ...options }) => {
+ const cloud = makeCloudVolume({
+ ...options, density: .07, quality: 'high', wind: [8, 1.3],
+ sunDirection: rig.sunDir, sunColor: 0xfff7ea,
+ skyColor: 0xacbfd8, sunIntensity: 1.55,
+ });
+ cloud.position.fromArray(position);
+ scene.add(cloud);
+ return cloud;
+ });
+
+ const lake = makeOcean(6000, 6000, {
+ sunDir: rig.sunDir, waterColor: 0x153d44, distortionScale: .45,
+ glitter: .3, rttSize: 1024, size: .65,
+ });
+ scene.add(lake);
+
+ // Two staggered ridges supply a distance reference for the cloud scale.
+ for (let layer = 0; layer < 2; layer++) {
+ const geometry = new THREE.PlaneGeometry(4200, 850, 128, 40);
+ geometry.rotateX(-Math.PI / 2);
+ const position = geometry.attributes.position;
+ for (let i = 0; i < position.count; i++) {
+ const x = position.getX(i), z = position.getZ(i);
+ const spine = Math.exp(-Math.pow((z + 80) / 270, 2));
+ const ridge = 130 + 180 * fbm2(x * .0015, layer * 10, { seed: 13 + layer })
+ + 70 * Math.sin(x * .0028 + layer * 2.1);
+ position.setY(i, Math.max(-8, ridge * spine
+ + fbm2(x * .011, z * .011, { seed: 11 + layer, octaves: 4 }) * 60));
+ }
+ geometry.computeVertexNormals();
+ const ridge = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({
+ color: layer ? 0x566661 : 0x4e6155, roughness: .96,
+ }));
+ ridge.position.set(layer * 180, -6, -1150 - layer * 620);
+ ridge.receiveShadow = true;
+ scene.add(ridge);
+ }
+
+ const bankGeometry = new THREE.PlaneGeometry(180, 150, 90, 75);
+ bankGeometry.rotateX(-Math.PI / 2);
+ const bankPosition = bankGeometry.attributes.position;
+ for (let i = 0; i < bankPosition.count; i++) {
+ bankPosition.setY(i, heightAt(bankPosition.getX(i), bankPosition.getZ(i)));
+ }
+ bankGeometry.computeVertexNormals();
+ const bank = new THREE.Mesh(bankGeometry, new THREE.MeshStandardMaterial({ color: 0x4d5140, roughness: .98 }));
+ bank.receiveShadow = true;
+ scene.add(bank);
+ const grass = makeMeadow({
+ size: [160, 130], density: 8, maxBlades: 70000, height: .34,
+ seed: 63, color: 0x596b35, dry: .15, ground: false,
+ heightAt, mask: (x, z) => THREE.MathUtils.smoothstep(heightAt(x, z), .4, 2),
+ wind: { direction: [1, .2], strength: .45, speed: 1.0 },
+ });
+ scene.add(grass);
+ for (let i = 0; i < 17; i++) {
+ const x = -48 + i * 5.4;
+ const z = 26 + Math.sin(i * 1.7) * 3;
+ const rock = makeRock({
+ seed: 90 + i, type: 'granite', size: [3.1 + i % 3, 1.8 + i % 2, 2.3 + i % 3],
+ color: 0x767970, moisture: .75, moss: .12, burial: .16,
+ });
+ rock.position.set(x, heightAt(x, z) - .4, z);
+ rock.rotation.y = i * .87;
+ scene.add(rock);
+ }
+ return {
+ scene,
+ cameras: [
+ { name: 'lake', position: [24, 8.5, 60], lookAt: [-75, 165, -950], fov: 53 },
+ { name: 'clouds', position: [-200, 220, -600], lookAt: [-220, 670, -1900], fov: 46 },
+ { name: 'inside', position: [-220, 650, -1820], lookAt: [200, 700, -1920], fov: 64 },
+ ],
+ update(t, dt) {
+ clouds.forEach((cloud) => cloud.userData.update(t));
+ lake.userData.update(t);
+ grass.userData.update(t, dt);
+ },
+ };
+}
diff --git a/harness/examples/graphics_lab/scenes/external_shader.js b/harness/examples/graphics_lab/scenes/external_shader.js
new file mode 100644
index 00000000..c9595c85
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/external_shader.js
@@ -0,0 +1,134 @@
+/**
+ * External shader files: a controlled alloy-material sculpture study.
+ * The animated colour phase is artistic, not a thermal or optical simulation.
+ * Scene creation awaits all local files; update only changes cached uniforms.
+ */
+import * as THREE from 'three';
+import { attachDisposal, snapshotResources } from '../lib/lifecycle.js';
+
+export async function createScene({ loaders }) {
+ const text = new THREE.FileLoader(loaders.manager);
+ const [vertexShader, fragmentSource, commonSource] = await Promise.all([
+ text.loadAsync(new URL('../shaders/external_shader.vert', import.meta.url).href),
+ text.loadAsync(new URL('../shaders/external_shader.frag', import.meta.url).href),
+ text.loadAsync(new URL('../shaders/external_shader_common.glsl', import.meta.url).href),
+ ]);
+ const scene = new THREE.Scene();
+ scene.name = 'ChromaticAlloyStudy';
+ scene.background = new THREE.Color(0x252c33);
+ const group = new THREE.Group();
+ group.name = 'AlloyExhibit';
+ scene.add(group);
+
+ const hemisphere = new THREE.HemisphereLight(0xcbdcf0, 0x5a493b, 1.8);
+ const key = new THREE.DirectionalLight(0xffdfb0, 1.8);
+ key.position.set(-3, 4, 3);
+ key.castShadow = true;
+ key.shadow.mapSize.set(1024, 1024);
+ key.shadow.camera.left = -5;
+ key.shadow.camera.right = 5;
+ key.shadow.camera.top = 5;
+ key.shadow.camera.bottom = -5;
+ key.shadow.camera.near = 0.1;
+ key.shadow.camera.far = 20;
+ key.shadow.normalBias = 0.018;
+ key.shadow.radius = 12;
+ const fill = new THREE.DirectionalLight(0x9bc8ff, 0.7);
+ fill.position.set(4, 2, -3);
+ scene.add(hemisphere, key, fill);
+
+ const studioMaterial = new THREE.MeshStandardMaterial({ color: 0x33383c, roughness: 0.78 });
+ const floor = new THREE.Mesh(new THREE.CircleGeometry(8, 192), studioMaterial);
+ floor.name = 'StudioFloor';
+ floor.rotation.x = -Math.PI / 2;
+ floor.receiveShadow = true;
+ group.add(floor);
+
+ // A continuous circular cyclorama avoids a clipped floor/background horizon.
+ // Its inward normals join the floor smoothly and work from every fixed camera.
+ const positions = [], normals = [], indices = [];
+ const radialSegments = 32, aroundSegments = 192;
+ for (let ring = 0; ring <= radialSegments + 1; ring++) {
+ const angle = Math.min(ring, radialSegments) / radialSegments * Math.PI / 2;
+ const radius = 8 + 4 * Math.sin(angle);
+ const y = ring > radialSegments ? 16 : 4 * (1 - Math.cos(angle));
+ for (let column = 0; column <= aroundSegments; column++) {
+ const azimuth = column / aroundSegments * Math.PI * 2;
+ const x = Math.sin(azimuth), z = Math.cos(azimuth);
+ positions.push(x * radius, y, z * radius);
+ normals.push(-x * Math.sin(angle), Math.cos(angle), -z * Math.sin(angle));
+ if (ring < radialSegments + 1 && column < aroundSegments) {
+ const a = ring * (aroundSegments + 1) + column;
+ const b = a + aroundSegments + 1;
+ indices.push(a, b, a + 1, a + 1, b, b + 1);
+ }
+ }
+ }
+ const coveGeometry = new THREE.BufferGeometry();
+ coveGeometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
+ coveGeometry.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3));
+ coveGeometry.setIndex(indices);
+ const cove = new THREE.Mesh(coveGeometry, studioMaterial);
+ cove.name = 'StudioCyclorama';
+ cove.receiveShadow = true;
+ group.add(cove);
+ const plinth = new THREE.Mesh(new THREE.CylinderGeometry(1.62, 1.66, 0.25, 128),
+ new THREE.MeshStandardMaterial({ color: 0x282e34, roughness: 0.58, metalness: 0.08 }));
+ plinth.name = 'ExhibitPlinth';
+ plinth.position.y = 0.125;
+ plinth.castShadow = plinth.receiveShadow = true;
+ group.add(plinth);
+ const edge = new THREE.Mesh(new THREE.TorusGeometry(1.62, 0.009, 8, 192),
+ new THREE.MeshStandardMaterial({ color: 0xa78d60, roughness: 0.28, metalness: 0.7 }));
+ edge.name = 'BrassRim';
+ edge.rotation.x = Math.PI / 2;
+ edge.position.y = 0.235;
+ group.add(edge);
+
+ // The external shader uses an analytic studio environment. Its warm key and
+ // blue fill share the host lights' world directions; it does not sample
+ // environment maps or receive shadows from surrounding scene objects.
+ const material = new THREE.ShaderMaterial({
+ name: 'ExternalAnodizedAlloy',
+ glslVersion: THREE.GLSL3,
+ vertexShader,
+ fragmentShader: `${commonSource}\n${fragmentSource}`,
+ uniforms: {
+ uTime: { value: 0 },
+ uRoughness: { value: 0.39 },
+ uFilmStrength: { value: 0.42 },
+ uBaseReflectance: { value: new THREE.Color(0.50, 0.52, 0.56) },
+ },
+ fog: false,
+ });
+ const sculpture = new THREE.Mesh(new THREE.TorusKnotGeometry(0.84, 0.255, 320, 64, 2, 3), material);
+ sculpture.name = 'ChromaticFold';
+ sculpture.rotation.set(0.25, 0.22, -0.22);
+ sculpture.geometry.computeBoundingBox();
+ sculpture.position.y = 1.57;
+ sculpture.castShadow = true;
+ group.add(sculpture);
+ const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.045, 0.055, 0.54, 32),
+ new THREE.MeshStandardMaterial({ color: 0x272a2e, metalness: 0.75, roughness: 0.32 }));
+ stem.name = 'SculptureMount';
+ stem.position.y = 0.52;
+ stem.castShadow = true;
+ group.add(stem);
+
+ const resources = snapshotResources(group);
+ resources.add({ dispose() { key.shadow.dispose(); } });
+ attachDisposal(group, resources);
+ return {
+ scene,
+ cameras: [
+ { name: 'alloy', position: [4.5, 3.05, 5.8], lookAt: [0, 1.35, 0], fov: 37 },
+ { name: 'surface', position: [2.05, 1.95, 3.05], lookAt: [0, 1.55, 0], fov: 34 },
+ { name: 'profile', position: [-4.5, 2.25, 3.7], lookAt: [0, 1.38, 0], fov: 37 },
+ ],
+ update(t) {
+ material.uniforms.uTime.value = t;
+ sculpture.rotation.y = 0.22 + 0.18 * Math.sin(t * 0.4);
+ },
+ dispose() { group.userData.dispose(); },
+ };
+}
diff --git a/harness/examples/graphics_lab/scenes/fire.js b/harness/examples/graphics_lab/scenes/fire.js
new file mode 100644
index 00000000..197fdf0e
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/fire.js
@@ -0,0 +1,127 @@
+/** Candlelit still life + a wood hearth. No image textures or external assets. */
+import * as THREE from 'three';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { makeFire, makeCandle } from '../lib/fire.js';
+import { patchStandard } from '../lib/shader.js';
+import { mulberry32 } from '../lib/noise.js';
+
+export function createScene({ renderer }) {
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(0x080b10);
+ scene.fog = new THREE.FogExp2(0x080b10, 0.025);
+ const pmrem = new THREE.PMREMGenerator(renderer), room = new RoomEnvironment();
+ const envTarget = pmrem.fromScene(room, 0.04);
+ scene.environment = envTarget.texture; scene.environmentIntensity = 0.12;
+ pmrem.dispose(); room.dispose();
+ scene.add(new THREE.HemisphereLight(0x607b99, 0x1b120d, 0.35));
+ const moon = new THREE.DirectionalLight(0x9bbbd6, 1.4);
+ moon.position.set(-3, 4, -1); scene.add(moon);
+
+ const stone = new THREE.MeshStandardMaterial({ color: 0x434443, roughness: 0.96 });
+ patchStandard(stone, { name: 'LabFireStone', vertexHead: 'varying vec3 vStone;',
+ vertexBody: 'vStone = (modelMatrix * vec4(position, 1.0)).xyz;',
+ fragmentHead: 'varying vec3 vStone;', fragmentBody: `
+ float n = astraFbm2(vStone.xy * 23.0 + vStone.z * 0.17, 4) * 0.5
+ + astraFbm2(vStone.xz * 31.0, 3) * 0.5;
+ diffuseColor.rgb *= 0.55 + n * 1.2;
+ ` });
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(20, 20), stone);
+ floor.name = 'SlateFloor'; floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);
+ const wall = new THREE.Mesh(new THREE.BoxGeometry(24, 6, 0.3), stone);
+ wall.name = 'StoneWall'; wall.position.set(0, 2, -2.3); scene.add(wall);
+
+ const oak = new THREE.MeshStandardMaterial({ color: 0x654026, roughness: 0.7 });
+ patchStandard(oak, { name: 'LabFireOak', vertexHead: 'varying vec3 vOak;',
+ vertexBody: 'vOak = (modelMatrix * vec4(position, 1.0)).xyz;',
+ fragmentHead: 'varying vec3 vOak;', fragmentBody: `
+ float warp = astraNoise2(vOak.xz * vec2(1.8, 9.0)) * 0.007;
+ float ring = sin((vOak.z + warp) * 850.0 + astraNoise2(vOak.xz * 14.0) * 5.0);
+ float fine = astraNoise2(vOak.xz * vec2(65.0, 1200.0));
+ diffuseColor.rgb *= 0.70 + ring * 0.11 + fine * 0.38;
+ ` });
+ const table = new THREE.Group(); table.name = 'CandleTable';
+ for (let i = 0; i < 5; i++) {
+ const plank = new THREE.Mesh(new THREE.BoxGeometry(1.18, 0.075, 0.182), oak);
+ plank.name = `OakPlank_${i}`; plank.position.set(0.03 * Math.sin(i), 0.77, (i - 2) * 0.185);
+ plank.castShadow = true; plank.receiveShadow = true; table.add(plank);
+ }
+ for (const x of [-0.43, 0.43]) for (const z of [-0.32, 0.32]) {
+ const leg = new THREE.Mesh(new THREE.BoxGeometry(0.085, 0.74, 0.085), oak);
+ leg.name = 'TableLeg'; leg.position.set(x, 0.37, z); table.add(leg);
+ }
+ scene.add(table);
+ const brass = new THREE.MeshStandardMaterial({ color: 0x9c793a, metalness: 0.87, roughness: 0.32 });
+ const actors = [];
+ const candleSpecs = [[-0.12, -0.025, 0.075, 0.30, 15], [0.10, 0.08, 0.055, 0.185, 8], [-0.02, -0.20, 0.053, 0.225, 2]];
+ for (const [x, z, radius, height, seed] of candleSpecs) {
+ const tray = new THREE.Mesh(new THREE.CylinderGeometry(radius * 1.45, radius * 1.38, 0.012, 64), brass);
+ tray.name = 'BrassCandleSaucer'; tray.position.set(x, 0.814, z); tray.receiveShadow = true; scene.add(tray);
+ const rim = new THREE.Mesh(new THREE.TorusGeometry(radius * 1.40, 0.0045, 8, 64), brass);
+ rim.name = 'SaucerRolledEdge'; rim.rotation.x = Math.PI / 2; rim.position.set(x, 0.824, z); scene.add(rim);
+ const candle = makeCandle({ radius, height, seed, drips: 10, flameHeight: 0.071,
+ color: 0xe6d2a8, lightIntensity: 0.035, quality: 'high' });
+ candle.position.set(x, 0.821, z); scene.add(candle); actors.push(candle);
+ }
+ // A used brass wick trimmer and matches anchor the scale of the still life.
+ for (const x of [0.29, 0.34]) {
+ const ring = new THREE.Mesh(new THREE.TorusGeometry(0.025, 0.003, 8, 32), brass);
+ ring.name = 'WickTrimmerHandle'; ring.rotation.x = Math.PI / 2;
+ ring.position.set(x, 0.815, 0.14); scene.add(ring);
+ const shaft = new THREE.Mesh(new THREE.BoxGeometry(0.007, 0.006, 0.115), brass);
+ shaft.name = 'WickTrimmerArm'; shaft.rotation.y = x < 0.3 ? -0.22 : 0.22;
+ shaft.position.set(x + (x < 0.3 ? 0.01 : -0.01), 0.815, 0.055); scene.add(shaft);
+ }
+
+ const hearth = new THREE.Group(); hearth.name = 'WoodHearth'; hearth.position.set(-4.0, 0.04, -0.9);
+ const random = mulberry32(49);
+ for (let i = 0; i < 13; i++) {
+ const angle = i / 13 * Math.PI * 2;
+ const rock = new THREE.Mesh(new THREE.DodecahedronGeometry(0.15 + random() * 0.045, 1), stone);
+ rock.name = `HearthStone_${i}`;
+ rock.scale.set(1.25, 0.72, 1); rock.rotation.set(random(), random(), random());
+ rock.position.set(Math.cos(angle) * 0.58, 0.075, Math.sin(angle) * 0.58);
+ rock.castShadow = true; rock.receiveShadow = true; hearth.add(rock);
+ }
+ const char = new THREE.MeshStandardMaterial({ color: 0x231710, roughness: 0.97, emissive: 0x160200 });
+ patchStandard(char, { name: 'LabCharcoal', vertexHead: 'varying vec3 vChar;',
+ vertexBody: 'vChar = position;', fragmentHead: 'varying vec3 vChar;',
+ fragmentBody: `
+ float grain = astraNoise2(vChar.xy * vec2(80.0, 13.0));
+ diffuseColor.rgb *= 0.5 + grain;
+ `,
+ outputBody: `
+ float angle = atan(vChar.z, vChar.x);
+ vec2 cell = vec2(angle * 3.9, vChar.y * 24.0);
+ cell += vec2(astraNoise2(cell * 0.7), astraNoise2(cell * 0.81 + 12.7)) * 0.5;
+ vec2 edge = abs(fract(cell) - 0.5);
+ float cracks = smoothstep(0.456, 0.49, max(edge.x, edge.y));
+ float live = astraNoise2(vChar.xy * 27.0);
+ gl_FragColor.rgb += vec3(0.45, 0.035, 0.001) * cracks * smoothstep(0.33, 0.77, live);
+ ` });
+ for (let i = 0; i < 7; i++) {
+ const log = new THREE.Mesh(new THREE.CylinderGeometry(0.055, 0.08, 0.83, 13, 7), char);
+ const lp = log.geometry.attributes.position;
+ for(let j=0;j<lp.count;j++) {
+ const s = 1 + 0.11*Math.sin(lp.getY(j)*21 + i) + 0.06*Math.cos(lp.getX(j)*87 + lp.getY(j)*45);
+ lp.setXYZ(j, lp.getX(j)*s, lp.getY(j), lp.getZ(j)*s);
+ }
+ log.geometry.computeVertexNormals();
+ log.name = `CharredLog_${i}`; log.rotation.set(Math.PI / 2 + (random() - 0.5) * 0.45, 0, i * 1.79);
+ log.position.set((random() - 0.5) * 0.22, 0.10 + i * 0.022, (random() - 0.5) * 0.22);
+ log.castShadow = true; log.receiveShadow = true; hearth.add(log);
+ }
+ const coals = new THREE.MeshStandardMaterial({ color: 0x180a04, roughness: 1, emissive: 0xf33102, emissiveIntensity: 0.75 });
+ for (let i = 0; i < 25; i++) {
+ const coal = new THREE.Mesh(new THREE.DodecahedronGeometry(0.028 + random() * 0.025, 0), coals);
+ coal.name = `Coal_${i}`; coal.position.set((random() - 0.5) * 0.65, 0.026, (random() - 0.5) * 0.65);
+ coal.scale.y = 0.6; hearth.add(coal);
+ }
+ const fire = makeFire({ radius: 0.28, height: 0.85, seed: 27, quality: 'high',
+ lightIntensity: 2.5, embers: 32, wind: [0.055, 0.02] });
+ fire.position.y = 0.15; hearth.add(fire); scene.add(hearth); actors.push(fire);
+ const cameras = [
+ { name: 'candle_macro', position: [0.49, 1.22, 0.71], lookAt: [-0.01, 0.995, -0.025], fov: 37 },
+ { name: 'hearth', position: [-2.78, 1.22, 1.0], lookAt: [-4.0, 0.54, -0.9], fov: 37 },
+ ];
+ return { scene, cameras, update(t, dt) { actors.forEach((a) => a.userData.update(t, dt)); } };
+}
diff --git a/harness/examples/graphics_lab/scenes/ice.js b/harness/examples/graphics_lab/scenes/ice.js
new file mode 100644
index 00000000..92d7cafa
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/ice.js
@@ -0,0 +1,157 @@
+/** Winter thaw: fractured lake ice, trapped air and a snow-covered rocky shore. */
+import * as THREE from 'three';
+import { makeFracturedIce } from '../lib/ice.js';
+import { makeWaterNormals } from '../lib/water.js';
+import { makeRock } from '../lib/rock.js';
+import { patchSnow } from '../lib/accumulation.js';
+import { patchMicroBreakup } from '../lib/surface_wear.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { fbm2, mulberry32 } from '../lib/noise.js';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+
+const smooth = (a, b, value) => {
+ const t = Math.max(0, Math.min(1, (value - a) / (b - a)));
+ return t * t * (3 - 2 * t);
+};
+
+export function createScene() {
+ const scene = new THREE.Scene(), owned = [], rocks = [], rand = mulberry32(314);
+ const rig = sunRig({ mood: 'overcast', elevation: 27, azimuth: -128, bounds: 35,
+ intensity: 2.2, fill: 1.7, disc: false });
+ rig.sun.shadow.mapSize.set(4096, 4096); rig.sun.shadow.normalBias = 0.015;
+ scene.add(rig.sun, rig.fill); scene.environment = rig.envTex;
+ makeSky(scene, { rig, turbidity: 2.2, rayleigh: 1.4 });
+ scene.fog = new THREE.FogExp2(0xcbd7dd, 0.009);
+ const floorHeight = (x, z) => {
+ const angle=Math.atan2(z+0.3,x);
+ const r = Math.hypot(x / 5.6, (z + 0.3) / 4.6)
+ + Math.sin(angle*5+.4)*.027 + fbm2(x*.9,z*.9,{seed:119,octaves:2})*.055;
+ return -0.69 + smooth(0.82, 1.2, r) * 1.15
+ + fbm2(x * 0.45, z * 0.45, { seed: 34, octaves: 3 }) * 0.17
+ + smooth(10, 46, -z) * (2.6 + fbm2(x * 0.022, z * 0.034, {seed:18,octaves:4}) * 11);
+ };
+ const groundGeometry = new THREE.PlaneGeometry(180, 180, 320, 320);
+ groundGeometry.rotateX(-Math.PI / 2);
+ const p = groundGeometry.attributes.position, colors = [], color = new THREE.Color();
+ const mud = new THREE.Color(0x28312e), snow = new THREE.Color(0xbac8d0);
+ for (let i = 0; i < p.count; i++) {
+ // Spend vertices at the pond contact rather than on distant snow.
+ const focus=value=>Math.sign(value)*90*Math.pow(Math.abs(value)/90,1.65);
+ const x = focus(p.getX(i)), z = focus(p.getZ(i)), h = floorHeight(x, z);
+ p.setX(i,x);p.setZ(i,z);
+ p.setY(i, h); color.copy(mud).lerp(snow, smooth(-0.4, 0.14, h));
+ colors.push(color.r, color.g, color.b);
+ }
+ groundGeometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
+ groundGeometry.computeVertexNormals();
+ const groundMaterial = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.91 });
+ patchMicroBreakup(groundMaterial, { scale: 0.11, strength: 0.12, hue: 0.018, seed: 31 });
+ const ground = new THREE.Mesh(groundGeometry, groundMaterial);
+ ground.name = 'SnowAndLakebed'; ground.receiveShadow = true; scene.add(ground);
+ owned.push(groundGeometry, groundMaterial);
+
+ const ice = makeFracturedIce({
+ outline: [[-4.7,-1.2],[-3.3,-3.4],[-0.2,-4.0],[2.5,-3.5],[4.4,-1.5],
+ [4.6,1.0],[3.1,2.8],[0.5,3.6],[-2.5,3.0],[-4.4,1.3]].map(([x,z])=>[x*1.3,z*1.3]),
+ thickness: 0.24, crackDensity: 0.42, gap: 0.009, heave: 0.012,
+ frost: 0.26, bubbles: 0.85, chipping: 0.18, seed: 73, attenuationDistance: 1.3,
+ });
+ scene.add(ice);
+ // Water occupies only the open fissures and the narrow exposed perimeter.
+ // It sits just below the ice freeboard, while the clear volume retains a
+ // view of the lakebed and trapped air through its own transmission pass.
+ const rim = Array.from({length:96},(_,i)=>{
+ const angle=i/96*Math.PI*2;return [Math.cos(angle)*7,Math.sin(angle)*6-0.3];
+ });
+ const waterShape = new THREE.Shape(rim.map(([x,z]) => new THREE.Vector2(x,-z)));
+ for (const polygon of ice.userData.floeOutlines) {
+ waterShape.holes.push(new THREE.Path(polygon.map(([x,z]) => new THREE.Vector2(x,-z))));
+ }
+ const waterGeometry = new THREE.ShapeGeometry(waterShape);
+ waterGeometry.rotateX(-Math.PI/2);
+ const waterNormals = makeWaterNormals(256, {broadband:true});
+ waterNormals.repeat.set(0.3,0.3);
+ const waterMaterial = new THREE.MeshStandardMaterial({color:0x0a2025,roughness:0.19,metalness:0,
+ normalMap:waterNormals,normalScale:new THREE.Vector2(0.09,0.09)});
+ const water = new THREE.Mesh(waterGeometry, waterMaterial); water.position.y = -0.027;
+ water.name = 'WaterBetweenFloes'; scene.add(water); owned.push(waterGeometry,waterMaterial,waterNormals);
+ const addRock = (x, z, s, seed, snowy = true) => {
+ const rock = makeRock({ type: 'granite', seed, size: [s * 1.3, s * 0.7, s],
+ detail: s > 1 ? 7 : 3, color: 0x606664, moisture: 0.65, weathering: 1.0, burial: 0.1 });
+ rock.position.set(x, floorHeight(x, z), z); rock.rotation.y = rand() * Math.PI;
+ if (snowy) patchSnow(rock.material, { depth: 0.06, color: 0xc0cbd0, seed: seed + 13 });
+ scene.add(rock); rocks.push(rock); return rock;
+ };
+ addRock(-4.6, -1.9, 2.2, 304); addRock(4.1, -2.4, 1.8, 32);
+ addRock(-3.2, -3.8, 1.45, 102); addRock(0.4, -4.7, 1.0, 59);
+ addRock(3.0, 3.15, 0.8, 930); addRock(-3.3, 2.65, 0.7, 12);
+ // The bed remains visible through clear portions, making refraction and
+ // trapped air depth observable rather than relying on a blue color alone.
+ for (let i = 0; i < 65; i++) {
+ const a = rand() * Math.PI * 2, r = Math.sqrt(rand()) * 4;
+ const x = Math.cos(a) * r, z = Math.sin(a) * r * 0.78;
+ addRock(x, z, 0.06 + rand() * 0.22, 2000 + i, false);
+ }
+ for (let i = 0; i < 22; i++) {
+ const a = rand() * Math.PI * 2, r = 5.4 + rand() * 2.5;
+ addRock(Math.cos(a) * r, Math.sin(a) * r * 0.86,
+ 0.18 + rand() * 0.56, 700 + i);
+ }
+ // Broken pressure slabs expose a thick edge beside the main sheet.
+ const slab = makeFracturedIce({ outline: [[-1.0,-0.5],[-0.1,-0.85],[0.85,-0.42],
+ [1.03,0.3],[0.3,0.76],[-0.85,0.48]], thickness: 0.23, crackDensity: 0,
+ gap: 0, frost: 0.42, bubbles: 0.8, chipping: 1, seed: 49, attenuationDistance: 0.85 });
+ slab.position.set(-2.0, 0.16, 2.8); slab.rotation.set(-0.06, 0.42, -0.15);
+ scene.add(slab);
+ // A lower floe makes the pressure ridge's support visible. Seat the
+ // raised slab on it using actual transformed vertices and local height.
+ const support=makeFracturedIce({outline:[[-.9,-.55],[.35,-.8],[.95,-.05],
+ [.6,.62],[-.55,.72]],thickness:.16,crackDensity:0,gap:0,
+ frost:.82,bubbles:.35,chipping:.7,seed:59});
+ support.position.set(-2.7,.055,3.12);scene.add(support);
+ slab.updateMatrixWorld(true);
+ const sp=slab.getObjectByName('IceVolume').geometry.attributes.position;
+ const contact=new THREE.Vector3();let lift=-Infinity;
+ for(let i=0;i<sp.count;i++){
+ contact.fromBufferAttribute(sp,i).applyMatrix4(slab.matrixWorld);
+ const height=support.userData.sampleHeight(contact.x-support.position.x,contact.z-support.position.z);
+ if(height!==null)lift=Math.max(lift,height+support.position.y-contact.y);
+ const sheet=ice.userData.sampleHeight(contact.x,contact.z);
+ if(sheet!==null)lift=Math.max(lift,sheet-contact.y);
+ }
+ if(Number.isFinite(lift))slab.position.y+=lift+.001;
+
+ // Sparse dead reeds break the shoreline silhouette without obscuring ice.
+ const reedParts = [];
+ for (let i = 0; i < 65; i++) {
+ const x = -5.0 + rand() * 1.2, z = -2 + rand() * 5;
+ const y = floorHeight(x, z), h = 0.36 + rand() * 0.62;
+ const curve = new THREE.QuadraticBezierCurve3(new THREE.Vector3(x,y,z),
+ new THREE.Vector3(x + 0.04,y+h*0.55,z), new THREE.Vector3(x+0.12,y+h,z+0.04));
+ reedParts.push(new THREE.TubeGeometry(curve, 5, 0.004, 3, false));
+ }
+ const reedGeometry = mergeGeometries(reedParts); reedParts.forEach(g => g.dispose());
+ const reedMaterial = new THREE.MeshStandardMaterial({ color: 0x6a5740, roughness: 0.85 });
+ const reeds = new THREE.Mesh(reedGeometry, reedMaterial); reeds.name = 'WinterReeds';
+ reeds.castShadow = true; scene.add(reeds); owned.push(reedGeometry, reedMaterial);
+
+ // A distant broken ridge provides reflected shape and a winter horizon.
+ for (let i = 0; i < 9; i++) {
+ const rock = makeRock({ type: 'granite', seed: 803 + i,
+ size: [8 + rand()*6, 3 + rand()*3, 8], detail: 4, color: 0x7c8588 });
+ const x=-65+i*16,z=-63-rand()*16;
+ rock.position.set(x,floorHeight(x,z)-1.8,z);
+ patchSnow(rock.material, { depth: 0.1, color: 0xc6d2d8, seed: i + 81 });
+ scene.add(rock); rocks.push(rock);
+ }
+ scene.userData.grade = { exposure: 0.94, contrast: 1.04, saturation: 0.92 };
+ return { scene, cameras: [
+ { name: 'frozen_shore', position: [6.9, 3.2, 7.7], lookAt: [-0.3, 0.1, -0.5], fov: 48 },
+ { name: 'clear_ice', position: [1.8, 1.1, 3.2], lookAt: [0.15, -0.07, 0.65], fov: 48 },
+ { name: 'fracture_edge', position: [-0.2, 0.64, 5.0], lookAt: [-1.9, 0.08, 2.6], fov: 42 },
+ ], update(t, dt) { ice.userData.update(t, dt); slab.userData.update(t, dt);support.userData.update(t,dt);
+ waterNormals.offset.set(t*0.008,t*0.004); },
+ dispose() { ice.userData.dispose(); slab.userData.dispose();support.userData.dispose();rocks.forEach(r => r.userData.dispose());
+ owned.forEach(r => r.dispose()); rig.envTex.dispose(); } };
+}
diff --git a/harness/examples/graphics_lab/scenes/meadow.js b/harness/examples/graphics_lab/scenes/meadow.js
new file mode 100644
index 00000000..2b0b6296
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/meadow.js
@@ -0,0 +1,65 @@
+/** Wind crossing a lush upland meadow, with close leaf geometry and far slopes. */
+import * as THREE from 'three';
+import { makeMeadow } from '../lib/meadow.js';
+import { makeRock } from '../lib/rock.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { patchStandard } from '../lib/shader.js';
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ const rig = sunRig({mood:'day', azimuth:125, elevation:31, bounds:9,
+ intensity:4.3, fill:1.3});
+ scene.add(rig.sun, rig.sun.target, rig.fill);
+ rig.sun.shadow.mapSize.set(4096,4096);
+ rig.sun.shadow.normalBias=.0015;
+ rig.sun.shadow.radius=2.2;
+ scene.environment=rig.envTex;
+ makeSky(scene,{rig});
+ scene.fog=new THREE.FogExp2(0xc0c6b2,.019);
+ scene.userData.grade={contrast:1.03,saturation:.93,warmth:.01};
+ const heightAt=(x,z)=>.12*Math.sin(x*.45)+.09*Math.cos(z*.48)
+ +.16*Math.sin(z*.19+x*.17) + 2.2*Math.exp(-Math.pow((z+14)/8,2));
+ const wind={direction:[1,.4],strength:.46,speed:1.15};
+ const field=makeMeadow({size:[14,14],density:1650,maxBlades:145000,segments:4,
+ height:.32,bladeWidth:.012,seed:41,dry:.065,heightAt,
+ color:0x537e2c,wind});
+ scene.add(field);
+ const distant=makeMeadow({size:[24,8],density:250,maxBlades:48000,segments:3,
+ height:.42,bladeWidth:.037,seed:114,dry:.065,ground:true,
+ heightAt:(x,z)=>heightAt(x,z-11),
+ mask:(x,z)=>Math.abs(x)<7 && Math.abs(z-11)<7 ? 0:1,
+ color:0x537e2c,wind});
+ distant.position.z=-11;scene.add(distant);
+
+ // Rooted stones show leaf-scale occlusion and anchor the field's depth.
+ for(const [x,z,s,seed] of [[-1.15,-.4,.9,19],[1.7,-3.8,.72,91],[-3.4,-4.1,.54,44]]) {
+ const rock=makeRock({size:[s,s*.62,s*.85],type:'granite',seed,moss:.4,detail:4});
+ rock.position.set(x,heightAt(x,z)-.05,z);rock.rotation.y=seed*.47;scene.add(rock);
+ }
+
+ const ground=new THREE.PlaneGeometry(260,260,110,110);ground.rotateX(-Math.PI/2);
+ const p=ground.attributes.position;
+ for(let i=0;i<p.count;i++) {
+ const x=p.getX(i),z=p.getZ(i);
+ // The real near soil belongs to the meadow; broad hills stay beneath it.
+ const far=THREE.MathUtils.smoothstep(Math.hypot(x,z),28,55);
+ p.setY(i,heightAt(x,z)+far*(1.6+1.6*Math.sin(x*.065+z*.028)));
+ }
+ ground.computeVertexNormals();
+ const soil=new THREE.MeshStandardMaterial({color:0x293e18,roughness:1});
+ patchStandard(soil,{name:'LabMeadowHills',vertexHead:'varying vec3 vHill;',
+ vertexBody:'vHill = transformed;',fragmentHead:'varying vec3 vHill;',
+ fragmentBody:`
+ if(abs(vHill.x)<6.95 && abs(vHill.z)<6.95) discard;
+ if(abs(vHill.x)<11.95 && vHill.z< -7.05 && vHill.z> -14.95) discard;
+ float field = astraFbm2(vHill.xz*.55,3);
+ diffuseColor.rgb *= .79+field*.5;`});
+ const earth=new THREE.Mesh(ground,soil);earth.name='DistantMeadow';
+ earth.receiveShadow=true;scene.add(earth);
+ const cameras=[
+ {name:'meadow',position:[1.3,1.3,4.3],lookAt:[.8,.40,-1],fov:36},
+ {name:'blades',position:[.60,.76,2.8],lookAt:[.4,.18,1.0],fov:36},
+ ];
+ return {scene,cameras,update(t,dt){field.userData.update(t,dt);distant.userData.update(t,dt);}};
+}
diff --git a/harness/examples/graphics_lab/scenes/ocean.js b/harness/examples/graphics_lab/scenes/ocean.js
new file mode 100644
index 00000000..52ce181c
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/ocean.js
@@ -0,0 +1,94 @@
+/** Atlantic cove: displaced water and fracture-plane basalt in late afternoon. */
+import * as THREE from 'three';
+import { makeOceanSurface } from '../lib/ocean.js';
+import { makeRock } from '../lib/rock.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+export const BOUNDS = { min: [-110, -4, -110], max: [110, 14, 90] };
+export function heightAt() {
+ return -3;
+}
+export async function createScene() {
+ const scene = new THREE.Scene();
+ const rig = sunRig({
+ mood: 'golden',
+ azimuth: -120,
+ elevation: 16,
+ bounds: 42,
+ intensity: 4.1,
+ fill: 1.25,
+ disc: false,
+ });
+ scene.add(rig.sun, rig.fill);
+ scene.environment = rig.envTex;
+ makeSky(scene, { rig, turbidity: 3.4, rayleigh: 1.6, scale: 3500 });
+ scene.fog = new THREE.FogExp2(0xbec8c7, 0.0022);
+ const ocean = makeOceanSurface({
+ width: 1800,
+ depth: 1800,
+ segments: 384,
+ waveHeight: 1.65,
+ wavelength: 31,
+ windDirection: [0.35, 1],
+ choppiness: 1,
+ foam: 0.9,
+ seed: 83,
+ reflectionSize: 1024,
+ waterColor: 0x07353e,
+ shallowColor: 0x278779,
+ shoreline: { direction: [0, -1], position: -22, width: 5 },
+ });
+ scene.add(ocean);
+ const rocks = [
+ [-13, -0.7, 13, 8, 4.5, 8],
+ [15, -1.2, 8, 8, 5.3, 8],
+ [21, -1.8, -3, 7, 4.8, 6],
+ [-21, -1.6, -8, 12, 8, 11],
+ [-26, -2, -14, 8, 11, 8],
+ [-18, -1.3, 22, 7, 3.4, 7],
+ [20, -1, 22, 10, 4, 9],
+ [-8, -1, 25, 5, 2, 5],
+ ];
+ for (let i = 0; i < rocks.length; i++) {
+ const [x, y, z, w, h, d] = rocks[i];
+ const rock = makeRock({
+ type: 'basalt',
+ seed: 91 + i,
+ size: [w, h, d],
+ detail: 5,
+ moisture: 0.75,
+ weathering: 1.15,
+ moss: 0.08,
+ });
+ rock.position.set(x, y, z);
+ rock.rotation.y = i * 0.77;
+ scene.add(rock);
+ }
+ // The beach actually intersects the mean sea level; swash remains on its wet edge.
+ const g = new THREE.PlaneGeometry(220, 90, 80, 35);
+ g.rotateX(-Math.PI / 2);
+ const p = g.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i),
+ z = p.getZ(i) + 52;
+ p.setXYZ(i, x, (z - 22) * 0.115 + Math.sin(x * 0.14) * 0.16, z);
+ }
+ g.computeVertexNormals();
+ const beach = new THREE.Mesh(
+ g,
+ new THREE.MeshStandardMaterial({ color: 0x85775d, roughness: 0.94 })
+ );
+ beach.name = 'WetBeach';
+ beach.receiveShadow = true;
+ scene.add(beach);
+ return {
+ scene,
+ cameras: [
+ { name: 'ocean', position: [5, 3.8, 21], lookAt: [-2, 0.2, -11], fov: 51 },
+ { name: 'wave_detail', position: [7, 2.0, 8], lookAt: [-4, 0.1, -9], fov: 44 },
+ ],
+ update(t, dt) {
+ ocean.userData.update(t, dt);
+ },
+ };
+}
diff --git a/harness/examples/graphics_lab/scenes/rain_shelter.js b/harness/examples/graphics_lab/scenes/rain_shelter.js
new file mode 100644
index 00000000..23fd12d7
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/rain_shelter.js
@@ -0,0 +1,174 @@
+/** Rain on a woodland shelter: covered timber, wet gravel and reflected trees. */
+import * as THREE from 'three';
+import { makeRain, makeSplashes, wetten } from '../lib/rain.js';
+import { makeRock } from '../lib/rock.js';
+import { makeTree, makeShrub } from '../lib/tree.js';
+import { makeMeadow } from '../lib/meadow.js';
+import { sunRig } from '../lib/environment.js';
+import { makeMirrorFloor } from '../lib/wetground.js';
+import { patchTriplanar } from '../lib/terrain_shade.js';
+import { weatheredWood } from '../lib/materials.js';
+import { mergeStatic } from '../lib/merge.js';
+import { mulberry32, fbm2 } from '../lib/noise.js';
+
+const smooth=(a,b,value)=>THREE.MathUtils.smoothstep(value,a,b);
+export const BOUNDS = { min: [-38, -.5, -38], max: [38, 15, 38] };
+export function heightAt(x,z) {
+ const clearing=Math.hypot(x/10.0,(z+1)/11.8);
+ return -.018+smooth(.61,1.14,clearing)*(.16+Math.abs(fbm2(x*.18,z*.18,{seed:101}))*1.8)
+ +smooth(1.1,2.8,clearing)*(.48+.25*Math.sin(x*.2+z*.11));
+}
+
+export function createScene() {
+ const scene=new THREE.Scene(),owned=new Set(),effects=[],rand=mulberry32(35);
+ const own=value=>{owned.add(value);return value;};
+ const effect=value=>{effects.push(value);scene.add(value);return value;};
+ const rig=sunRig({mood:'overcast',intensity:1.35,fill:1.55,bounds:23,disc:false,
+ azimuth:135,elevation:46});
+ rig.sun.shadow.mapSize.set(2048,2048);rig.sun.shadow.normalBias=.012;
+ scene.add(rig.sun,rig.fill);scene.environment=rig.envTex;
+ scene.background=new THREE.Color(0x88979d);scene.fog=new THREE.FogExp2(0x88979d,.018);
+
+ const groundGeometry=own(new THREE.PlaneGeometry(76,76,100,100));groundGeometry.rotateX(-Math.PI/2);
+ const p=groundGeometry.attributes.position;
+ for(let i=0;i<p.count;i++)p.setY(i,heightAt(p.getX(i),p.getZ(i)));
+ groundGeometry.computeVertexNormals();
+ const soil=own(new THREE.MeshStandardMaterial({color:0x464b39,roughness:.95}));
+ patchTriplanar(soil,{scale:.11,relief:.0015,roughness:.93,colorA:0x242923,colorB:0x58604a});
+ const ground=new THREE.Mesh(groundGeometry,soil);ground.name='RaisedForestFloor';ground.receiveShadow=true;
+ scene.add(ground);
+ const wetFloor=effect(makeMirrorFloor(32,36,{seed:7,rttSize:1024,color:0x727979,
+ overlayColor:0x554f42,overlayOpacity:.84,puddleMask:true,ripple:.10,rippleScale:10,detail:1}));
+ wetFloor.name='RainFilledClearing';
+
+ const timber=new THREE.Group(),roofParts=new THREE.Group();
+ timber.name='ShelterCarpentry';roofParts.name='PitchedSheetRoof';
+ const wood=weatheredWood({color:0x79654d,roughness:.91,bump:.0008,scale:5,contrast:.20,seed:24});
+ const roofMaterial=own(new THREE.MeshStandardMaterial({color:0x4b5149,roughness:.69,metalness:.14}));
+ wetten(roofMaterial,.65,{minRoughness:.25,darken:.22});
+ let part=0;
+ const box=(name,size,position,material=wood,rotation=[0,0,0],parent=timber)=>{
+ const geometry=new THREE.BoxGeometry(...size),pos=geometry.attributes.position,uv=geometry.attributes.uv;
+ if(material===wood){
+ // Growth grain follows the long axis of each board in metric units.
+ const along=size.indexOf(Math.max(...size)),across=(along+1)%3;
+ for(let i=0;i<uv.count;i++)uv.setXY(i,pos.getComponent(i,across)*.45+part*.117,
+ pos.getComponent(i,along)*.32+part*.173);
+ }
+ const mesh=new THREE.Mesh(geometry,material);mesh.name=name;mesh.position.set(...position);mesh.rotation.set(...rotation);
+ mesh.castShadow=mesh.receiveShadow=true;parent.add(mesh);part++;return mesh;
+ };
+ const beam=(name,a,b,width,depth=width)=>{
+ const from=new THREE.Vector3(...a),to=new THREE.Vector3(...b),direction=to.clone().sub(from);
+ const mesh=box(name,[width,direction.length(),depth],from.add(to).multiplyScalar(.5).toArray());
+ mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0),direction.normalize());return mesh;
+ };
+ for(let plank=0;plank<25;plank++)box('DeckBoard',[.277,.065,6.8],[-3.456+plank*.288,.104,0]);
+ for(const x of [-3.5,3.5])for(const z of [-3.4,3.4]){
+ box('Upright',[.24,3.68,.24],[x,1.84,z]);
+ for(const sign of [-1,1])if(Math.abs(x+sign*.90)<3.6)
+ beam('KneeBrace',[x,2.77,z],[x+sign*.90,3.56,z],.13);
+ beam('LongBrace',[x,2.91,z],[x,3.54,z-Math.sign(z)*.82],.13);
+ }
+ for(const z of [-3.4,3.4])box('CrossBeam',[7.3,.26,.25],[0,3.60,z]);
+ for(const x of [-3.5,3.5])box('LongBeam',[.22,.22,7.1],[x,3.52,0]);
+ box('RidgeBeam',[.17,.22,8.12],[0,4.39,0]);
+ for(const z of [-3.85,-2.3,-.76,.76,2.3,3.85])for(const side of [-1,1])
+ beam('RoofRafter',[0,4.36,z],[side*4.1,3.45,z],.10,.18);
+ for(const side of [-1,1]){
+ box('RoofPanel',[4.3,.055,8.4],[side*2.06,4.0,0],roofMaterial,[0,0,-side*.22],roofParts);
+ for(let k=-5;k<=5;k++)box('StandingSeam',[4.3,.029,.035],[side*2.06,4.045,k*.78],
+ roofMaterial,[0,0,-side*.22],roofParts);
+ box('EaveTrim',[.075,.13,8.44],[side*4.15,3.55,0],roofMaterial,[0,0,0],roofParts);
+ }
+ // Bench and a small table make the roof's physical scale legible.
+ for(const x of [-2.9,2.9]){
+ for(let plank=0;plank<3;plank++)box('BenchSeat',[.145,.048,4.55],[x+(plank-1)*.157,.50,0]);
+ for(const z of [-1.8,1.8]){
+ box('BenchLeg',[.095,.40,.15],[x,.30,z]);
+ box('BenchBearer',[.54,.085,.17],[x,.43,z]);
+ box('BackrestUpright',[.06,.67,.08],[x+Math.sign(x)*.26,.73,z]);
+ }
+ for(let plank=0;plank<2;plank++)box('BenchBack',[.045,.15,4.50],[x+Math.sign(x)*.26,.81+plank*.17,0]);
+ }
+ for(let i=0;i<4;i++)box('TableTop',[1.5,.06,.17],[0,.86,-1.72+i*.182]);
+ for(const x of [-.55,.55])for(const z of [-1.62,-1.12])box('TableLeg',[.09,.69,.09],[x,.49,z]);
+ const collectParts=(parts,name)=>{
+ const result=mergeStatic([parts],{variance:.05});result.name=name;
+ parts.traverse(o=>o.geometry?.dispose());return effect(result);
+ };
+ collectParts(timber,'CoveredTimberStructure');
+ const roof=collectParts(roofParts,'RainShelterRoof');
+ // A soft, warm sheltered lamp contrasts with the cool wet clearing.
+ const lampMaterial=own(new THREE.MeshStandardMaterial({color:0xffe4b5,emissive:0xffcb80,emissiveIntensity:2,roughness:.5}));
+ const shadeMaterial=own(new THREE.MeshStandardMaterial({color:0x202826,roughness:.55,metalness:.4}));
+ const bulb=new THREE.Mesh(own(new THREE.SphereGeometry(.058,16,12)),lampMaterial);bulb.position.set(0,3.47,-1.35);scene.add(bulb);
+ const shade=new THREE.Mesh(own(new THREE.ConeGeometry(.24,.15,24,1,true)),shadeMaterial);
+ shade.position.set(0,3.55,-1.35);shade.material.side=THREE.DoubleSide;scene.add(shade);
+ const lamp=own(new THREE.PointLight(0xffd69d,13,8,2));lamp.position.copy(bulb.position);scene.add(lamp);
+
+ for(let i=0;i<48;i++){
+ const side=i%2?1:-1,x=side*(6.0+rand()*8),z=-13+rand()*27;
+ const s=.17+Math.pow(rand(),2)*1.0;
+ const rock=makeRock({seed:101+i,type:i%4?'granite':'sandstone',size:[s*1.3,s*.55,s],
+ detail:4,color:0x697266,moisture:.82,moss:.30,weathering:1});
+ rock.position.set(x,heightAt(x,z)-s*.12,z);rock.rotation.y=rand()*6.28;effect(rock);
+ }
+ effect(makeMeadow({size:[34,36],height:.27,density:720,maxBlades:240000,
+ bladeWidth:.012,segments:5,seed:83,color:0x486032,dry:.14,ground:false,seedHeads:.001,
+ heightAt,mask:(x,z)=>smooth(.78,1.18,Math.hypot(x/10,(z+1)/11.8))
+ *(.40+.6*smooth(-.15,.16,fbm2(x*.32,z*.32,{seed:85}))),
+ wind:{direction:[.65,.3],strength:.18,speed:.7}}));
+ // A close strip has enough short blades to read as turf at eye level.
+ // Sampling converts its local patch coordinates back to the terrain frame.
+ const turf=makeMeadow({size:[16,16],height:.13,density:3000,maxBlades:300000,
+ bladeWidth:.005,segments:4,seed:89,color:0x485b34,dry:.12,ground:false,seedHeads:0,
+ heightAt:(x,z)=>heightAt(x+5,z+8),
+ mask:(x,z)=>smooth(.83,1.08,Math.hypot((x+5)/10,(z+9)/11.8))
+ *(.5+.5*smooth(-.16,.2,fbm2((x+5)*.32,(z+8)*.32,{seed:85}))),
+ wind:{direction:[.65,.3],strength:.10,speed:.7}});
+ turf.position.set(5,0,8);effect(turf);
+ for(let i=0;i<18;i++){
+ const angle=2.2+i*2.39996,r=14+rand()*16,x=Math.cos(angle)*r,z=Math.sin(angle)*r-4;
+ if(z>0&&x>3)continue; // Keep the established exterior camera's sightline open.
+ const species=i%4===0?'birch':i%3===0?'willow':'oak';
+ const tree=makeTree({species,seed:800+i,height:6+rand()*2.5,crownRadius:2.3+rand()*1.1,
+ maxLeaves:17000,leafDensity:1.1,leafSegments:4,shadows:false,wind:{dir:[.65,.3],strength:.16,speed:.7}});
+ tree.position.set(x,heightAt(x,z)-.045,z);effect(tree);
+ }
+ for(const [x,z,h] of [[-7,-2,1.8],[7,-5,2.4],[-5,-9,1.4],[9,3,1.6],[-9,8,1.3],[4,-12,2.3]]){
+ const shrub=makeShrub({seed:1010+Math.round(x*3+z),height:h,crownRadius:h*.7,
+ maxLeaves:1100,leafDensity:.42,wind:{dir:[.65,.3],strength:.16,speed:.7}});
+ shrub.position.set(x,heightAt(x,z)-.035,z);effect(shrub);
+ }
+ // Small physical gravel interrupts the wet clearing without hiding its pools.
+ const gravelGeometry=own(new THREE.IcosahedronGeometry(1,1));
+ const gravelMaterial=own(new THREE.MeshStandardMaterial({color:0x8d9380,roughness:.55}));
+ const gravel=own(new THREE.InstancedMesh(gravelGeometry,gravelMaterial,1600));
+ gravel.name='WetGravel';gravel.receiveShadow=true;
+ const pebble=new THREE.Object3D(),tint=new THREE.Color();
+ for(let i=0;i<gravel.count;i++){
+ const angle=rand()*Math.PI*2,r=Math.sqrt(rand())*9.5;
+ const x=Math.cos(angle)*r,z=Math.sin(angle)*r*1.12-1;
+ const size=.007+Math.pow(rand(),2)*.028;
+ const y=Math.max(.004,heightAt(x,z));
+ pebble.position.set(x,y+size*.26,z);pebble.scale.set(size,size*.50,size*(.6+rand()*.5));
+ pebble.rotation.set(rand(),rand()*6.28,rand());pebble.updateMatrix();gravel.setMatrixAt(i,pebble.matrix);
+ tint.setHSL(.10+rand()*.08,.10+rand()*.10,.14+rand()*.11);gravel.setColorAt(i,tint);
+ }
+ gravel.instanceMatrix.needsUpdate=true;gravel.instanceColor.needsUpdate=true;scene.add(gravel);
+ const surfaces=[roof,ground];
+ // The authored terrain function avoids casting every rain-atlas ray through
+ // the full terrain mesh whenever the camera moves. Roof rays remain exact.
+ effect(makeRain({seed:5,count:11000,radius:24,height:22,length:.46,
+ surfaces:[roof],heightAt,groundY:0,shelterResolution:48,shelterUpdateDistance:3}));
+ effect(makeSplashes({seed:11,count:720,surfaces,surfaceBias:.35,
+ area:{x:0,z:0,w:32,d:32},y:0,size:.13,opacity:.42}));
+ // Library updates accept absolute time, including scrub and rewind.
+ return {scene,cameras:[
+ {name:'courtyard',position:[13,4.1,16],lookAt:[0,1.8,0],fov:51},
+ {name:'sheltered',position:[.5,1.55,2.7],lookAt:[.5,1.55,-9],fov:62},
+ {name:'rain_and_reflections',position:[7.5,.78,9.7],lookAt:[-.8,1.2,-1.4],fov:46},
+ ],update(t,dt){for(const item of effects)item.userData.update?.(t,dt);},
+ dispose(){for(const item of effects)item.userData.dispose?.();for(const item of owned)item.dispose();rig.dispose();}};
+}
diff --git a/harness/examples/graphics_lab/scenes/rocks.js b/harness/examples/graphics_lab/scenes/rocks.js
new file mode 100644
index 00000000..072f652c
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/rocks.js
@@ -0,0 +1,54 @@
+import * as THREE from 'three';
+import { makeRock, makeRockField } from '../lib/rock.js';
+import { makeSandTerrain } from '../lib/sand.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { mulberry32 } from '../lib/noise.js';
+
+/** A weathered outcrop: sedimentary ledges, mineral grains and damp talus. */
+export function createScene() {
+ const scene = new THREE.Scene();
+ const rig = sunRig({ mood: 'day', bounds: 24, azimuth: 138, elevation: 24, intensity: 5.2, fill: 0.7 });
+ rig.sun.shadow.mapSize.set(4096, 4096);
+ rig.sun.shadow.normalBias = 0.014;
+ scene.add(rig.sun, rig.fill); scene.environment = rig.envTex;
+ makeSky(scene, { rig, turbidity: 2.8 });
+ scene.fog = new THREE.FogExp2(0xafbdc4, 0.007);
+ const ground = makeSandTerrain({ seed: 61, size: 140, segments: 256, duneHeight: 0.30, duneSpacing: 13,
+ color: 0x766c57, rippleSpacing: 0.10, detailStrength: 0.30 });
+ scene.add(ground);
+ const h = ground.userData.sampleHeight, rocks = [];
+ const add = (opts, x, z, a = 0) => {
+ const rock = makeRock(opts); rock.position.set(x, h(x, z), z); rock.rotation.y = a;
+ scene.add(rock); rocks.push(rock); return rock;
+ };
+ add({ type: 'sandstone', seed: 19, size: [5.2, 3.8, 3.6], color: 0x947155, detail: 12, moisture: 0.15 }, -1.2, -1.6, 0.5);
+ add({ type: 'sandstone', seed: 73, size: [3.0, 1.0, 2.0], color: 0x947155, detail: 10 }, -3.6, 0.1, -0.6);
+ add({ type: 'granite', seed: 31, size: [2.8, 1.9, 2.3], detail: 10, moisture: 0.6, moss: 0.35 }, 2.0, 1.7, 0.3);
+ add({ type: 'granite', seed: 52, size: [1.2, 0.85, 1.0], detail: 7, moisture: 0.55, moss: 0.6 }, 0.4, 3.1, 0.8);
+ add({ type: 'basalt', seed: 84, size: [2.1, 1.8, 1.7], detail: 8, moisture: 0.28 }, 3.5, -2.2, 0.35);
+ add({ type: 'basalt', seed: 81, size: [1.7, 0.9, 1.2], detail: 6, moisture: 0.2 }, 4.4, -1.7, 0.7);
+ // Broken blocks accumulate at the parent outcrop. A second size tier and
+ // smaller scree connect the hero stones to the substrate instead of leaving
+ // unrelated samples evenly spaced across an empty plane.
+ const rand = mulberry32(908);
+ for (let i = 0; i < 23; i++) {
+ const a = rand() * Math.PI * 2, r = 1.5 + rand() * 2.8;
+ const x = -1.7 + Math.cos(a) * r, z = -1.1 + Math.sin(a) * r;
+ if (x > 0.3 && z > 0.5) continue;
+ const s = 0.42 + rand() * 1.0;
+ add({ type: 'sandstone', seed: 801 + i, size: [s * 1.4, s * 0.65, s], detail: 5,
+ color: 0x8b7053, weathering: 0.75, burial: 0.13 }, x, z, a);
+ }
+ const talus = makeRockField({ type: 'granite', seed: 35, radius: 7, count: 110, size: 0.3, detail: 2, moisture: 0.35, heightAt: h });
+ scene.add(talus);
+ for (let i = 0; i < 15; i++) add({ type: 'sandstone', seed: 210 + i,
+ size: [9 + (i % 3) * 3, 3 + (i % 4), 8], color: 0x847b68, detail: 4, burial: 0.22 },
+ -43 + i * 6, -23 - (i % 2) * 3, i * 0.7);
+ scene.userData.grade = { exposure: 1, contrast: 1.04, saturation: 0.99 };
+ return { scene, cameras: [
+ { name: 'outcrop', position: [10.4, 5.2, 12.9], lookAt: [0.1, 1.5, -0.3], fov: 47 },
+ { name: 'granite', position: [4.3, 2.8, 5.5], lookAt: [1.8, 0.8, 1.6], fov: 43 },
+ { name: 'strata', position: [-4.8, 3.0, 4.0], lookAt: [-1.3, 1.8, -0.8], fov: 42 },
+ ], update() {}, dispose() { ground.userData.dispose(); talus.userData.dispose(); rocks.forEach((r) => r.userData.dispose()); rig.envTex.dispose(); } };
+}
diff --git a/harness/examples/graphics_lab/scenes/sand.js b/harness/examples/graphics_lab/scenes/sand.js
new file mode 100644
index 00000000..408c3228
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/sand.js
@@ -0,0 +1,35 @@
+import * as THREE from 'three';
+import { makeSandTerrain } from '../lib/sand.js';
+import { makeRock } from '../lib/rock.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+
+/** Long stoss slopes, crisp lee crests and ripples lit across the wind. */
+export function createScene() {
+ const scene = new THREE.Scene();
+ const rig = sunRig({ mood: 'golden', bounds: 90, azimuth: 128, elevation: 16, intensity: 4.8, fill: 0.8,
+ fillSky: 0x9eafd2, fillGround: 0x795333 });
+ scene.add(rig.sun, rig.fill);
+ scene.environment = rig.envTex;
+ makeSky(scene, { rig, turbidity: 3.1 });
+ scene.fog = new THREE.FogExp2(0xc9b291, 0.0038);
+ const sand = makeSandTerrain({ seed: 42, size: 240, segments: 512,
+ duneHeight: 7.4, duneSpacing: 37, windDirection: [0.96, 0.28],
+ rippleSpacing: 0.19, color: 0xc39b68, grains: 420, windSpeed: 1.2 });
+ scene.add(sand);
+ const h = sand.userData.sampleHeight;
+ for (const [i, p] of [[-46, -55], [-57, -58], [-49, -66], [59, -73]].entries()) {
+ const rock = makeRock({ seed: 118 + i, type: 'sandstone', size: [9 + i * 1.6, 8 + i, 8], detail: 6,
+ color: 0x9b7253, burial: 0.20 });
+ rock.position.set(p[0], h(...p), p[1]); rock.rotation.y = i * 0.74;
+ scene.add(rock);
+ }
+ scene.userData.grade = { exposure: 0.98, contrast: 1.04, saturation: 1.02, warmth: 0.03 };
+ const cameras = [
+ { name: 'dunes', position: [28, h(28, 48) + 7.0, 48], lookAt: [-8, 3.4, -22], fov: 48 },
+ { name: 'ripples', position: [3, h(3, 8) + 1.3, 8], lookAt: [-2, h(-2, -1), -1], fov: 48 },
+ { name: 'crest', position: [-12, h(-12, 27) + 3.1, 27], lookAt: [-35, 2.4, -27], fov: 44 },
+ ];
+ return { scene, cameras, update(t, dt) { sand.userData.update(t, dt); },
+ dispose() { sand.userData.dispose(); scene.traverse((o) => { if (o.userData.rockType) o.userData.dispose(); }); rig.envTex.dispose(); } };
+}
diff --git a/harness/examples/graphics_lab/scenes/smoke.js b/harness/examples/graphics_lab/scenes/smoke.js
new file mode 100644
index 00000000..81fb6eae
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/smoke.js
@@ -0,0 +1,103 @@
+/** Two scales of rising density: warm tea and a cooling charcoal brazier. */
+import * as THREE from 'three';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { makeSmoke, makeSteam } from '../lib/smoke.js';
+import { patchStandard } from '../lib/shader.js';
+import { mulberry32 } from '../lib/noise.js';
+
+export function createScene({renderer}) {
+ const scene = new THREE.Scene();scene.background = new THREE.Color(0x15202b);
+ const room = new RoomEnvironment(), generator = new THREE.PMREMGenerator(renderer);
+ const environment = generator.fromScene(room,.03);generator.dispose();room.dispose();
+ scene.environment = environment.texture;scene.environmentIntensity = .36;
+ scene.add(new THREE.HemisphereLight(0xb5d4e8,0x554936,.6));
+ const sun = new THREE.DirectionalLight(0xffecd2,5.6);
+ sun.position.set(-1.4,2.7,-2.0);sun.castShadow = true;
+ sun.shadow.mapSize.set(2048,2048);sun.shadow.camera.left = -6;sun.shadow.camera.right = 6;
+ sun.shadow.camera.top = 6;sun.shadow.camera.bottom = -6;sun.shadow.normalBias = .002;
+ scene.add(sun);
+ const stone = new THREE.MeshStandardMaterial({color:0x262b2d,roughness:.87});
+ patchStandard(stone,{name:'PlumeSlate',vertexHead:'varying vec3 vSlate;',vertexBody:'vSlate=(modelMatrix*vec4(position,1.0)).xyz;',
+ fragmentHead:'varying vec3 vSlate;',fragmentBody:`
+ float mottling=astraFbm2(vSlate.xz*46.0+vSlate.y*4.0,4);
+ diffuseColor.rgb*=.91+mottling*.22;`,roughnessBody:'roughnessFactor=clamp(roughnessFactor+astraNoise2(vSlate.xz*110.0)*.06,0.0,1.0);'});
+ const table = new THREE.Mesh(new THREE.BoxGeometry(2.4,.06,2),stone);
+ table.name = 'SlateCounter';table.position.y = .72;table.receiveShadow = true;scene.add(table);
+ const ceramic = new THREE.MeshPhysicalMaterial({color:0x879994,roughness:.32,clearcoat:.38,clearcoatRoughness:.23});
+ patchStandard(ceramic,{name:'PlumeGlaze',vertexHead:'varying vec3 vGlaze;',vertexBody:'vGlaze=position;',
+ fragmentHead:'varying vec3 vGlaze;',fragmentBody:`
+ float grain=astraNoise2(vGlaze.xy*240.0+vGlaze.z*91.0);
+ diffuseColor.rgb*=.96+grain*.065;`});
+ const cupProfile = [[.033,0],[.039,.005],[.042,.012],[.045,.033],[.049,.071],[.051,.095],
+ [.050,.10],[.047,.10],[.046,.094],[.044,.074],[.039,.03],[.035,.009],[0,.009]];
+ const cup = new THREE.Mesh(new THREE.LatheGeometry(cupProfile.map(p=>new THREE.Vector2(...p)),96),ceramic);
+ cup.name = 'CeladonTeaCup';cup.position.y = .754;cup.castShadow = true;cup.receiveShadow = true;scene.add(cup);
+ const handle = new THREE.Mesh(new THREE.TorusGeometry(.032,.006,14,48),ceramic);
+ handle.name = 'CupHandle';handle.position.set(.064,.806,0);handle.scale.x = .8;scene.add(handle);
+ const tea = new THREE.Mesh(new THREE.CircleGeometry(.046,96),new THREE.MeshPhysicalMaterial({
+ color:0x422518,roughness:.11,metalness:0,clearcoat:1,ior:1.333}));
+ tea.name = 'TeaSurface';tea.rotation.x = -Math.PI/2;tea.position.y = .845;scene.add(tea);
+ const saucer = new THREE.Mesh(new THREE.LatheGeometry([[0,0],[.058,0],[.074,.004],[.084,.011],
+ [.084,.014],[.074,.009],[.047,.005],[0,.005]].map(p=>new THREE.Vector2(...p)),96),ceramic);
+ saucer.name = 'TeaSaucer';saucer.position.y = .750;scene.add(saucer);
+ const steam = makeSteam({height:.29,radius:.03,spread:.12,riseSpeed:.12,
+ wind:[.009,-.002],quality:'high',density:5.5,dissipation:2.8,turbulence:.9,seed:18});
+ steam.position.y = .849;scene.add(steam);
+ const steamLight=new THREE.PointLight(0xffead0,1.8,1.6,2);
+ steamLight.name='SteamBacklight';steamLight.position.set(-.12,.98,-.40);scene.add(steamLight);
+ const teaBackdrop = new THREE.Mesh(new THREE.PlaneGeometry(2.2,2.3),
+ new THREE.MeshStandardMaterial({color:0x182026,roughness:1}));
+ teaBackdrop.name = 'TeaAlcove';teaBackdrop.position.set(-.12,1.6,-.90);scene.add(teaBackdrop);
+
+ const copper = new THREE.MeshStandardMaterial({color:0xb66b43,metalness:.95,roughness:.3});
+ patchStandard(copper,{name:'PlumeHammeredCopper',vertexHead:'varying vec3 vCopper;',vertexBody:'vCopper=position;',
+ fragmentHead:'varying vec3 vCopper;',fragmentBody:'diffuseColor.rgb*=.8+.2*astraFbm2(vCopper.xy*18.0,3);',
+ roughnessBody:'roughnessFactor+=astraNoise2(vCopper.xy*170.0)*.1;'});
+ const kettle = new THREE.Group();kettle.name = 'CopperKettle';kettle.position.set(-.36,.754,.03);
+ kettle.rotation.y=2.2;
+ const kettleProfile = new THREE.SplineCurve([[0,0],[.073,0],[.106,.034],[.119,.080],
+ [.112,.139],[.075,.174],[.061,.178]].map(p=>new THREE.Vector2(...p))).getPoints(64);
+ const body = new THREE.Mesh(new THREE.LatheGeometry(kettleProfile,96),copper);body.castShadow=true;kettle.add(body);
+ const lid = new THREE.Mesh(new THREE.SphereGeometry(.064,64,24,0,Math.PI*2,0,Math.PI/2),copper);
+ lid.scale.y = .28;lid.position.y = .176;kettle.add(lid);
+ const dark = new THREE.MeshStandardMaterial({color:0x27211e,roughness:.62});
+ const knob = new THREE.Mesh(new THREE.SphereGeometry(.014,24,16),dark);knob.position.y=.208;kettle.add(knob);
+ const arch = new THREE.Mesh(new THREE.TorusGeometry(.11,.009,12,64,Math.PI),dark);
+ arch.position.y=.133;kettle.add(arch);
+ const spoutPath = new THREE.CatmullRomCurve3([new THREE.Vector3(.085,.052,0),
+ new THREE.Vector3(.143,.076,0),new THREE.Vector3(.17,.13,0),new THREE.Vector3(.18,.171,0)]);
+ const spout = new THREE.Mesh(new THREE.TubeGeometry(spoutPath,40,.014,18,false),copper);kettle.add(spout);scene.add(kettle);
+ const silver = new THREE.MeshStandardMaterial({color:0xb7b5aa,metalness:.95,roughness:.22});
+ const spoon = new THREE.Mesh(new THREE.SphereGeometry(.018,32,20),silver);
+ spoon.scale.set(.7,.10,1.3);spoon.position.set(.14,.757,.02);scene.add(spoon);
+ const stem = new THREE.Mesh(new THREE.CapsuleGeometry(.0024,.096,6,12),silver);
+ stem.rotation.x=Math.PI/2;stem.position.set(.14,.757,.086);scene.add(stem);
+
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(30,30),stone);floor.rotation.x=-Math.PI/2;
+ floor.name='WorkshopFloor';floor.receiveShadow=true;scene.add(floor);
+ const wall = new THREE.Mesh(new THREE.PlaneGeometry(40,14),new THREE.MeshStandardMaterial({color:0x152026,roughness:1}));wall.name='WorkshopWall';wall.position.set(0,5,-2.7);scene.add(wall);
+ const brazier = new THREE.Group();brazier.name='CoolingBrazier';brazier.position.set(8,0,0);scene.add(brazier);
+ const iron = new THREE.MeshStandardMaterial({color:0x313739,metalness:.7,roughness:.7});
+ const bowl = new THREE.Mesh(new THREE.LatheGeometry([[0,0],[.16,0],[.22,.04],[.29,.17],
+ [.31,.24],[.305,.248],[.297,.24],[.277,.175],[.21,.052],[.16,.014],[0,.014]].map(p=>new THREE.Vector2(...p)),64),iron);
+ bowl.position.y=.44;brazier.add(bowl);
+ for(const angle of [0,2.094,4.189]) {
+ const leg=new THREE.Mesh(new THREE.CylinderGeometry(.013,.017,.47,12),iron);
+ leg.position.set(Math.cos(angle)*.18,.235,Math.sin(angle)*.18);leg.castShadow=true;brazier.add(leg);
+ }
+ const char = new THREE.MeshStandardMaterial({color:0x181615,roughness:1});
+ const random=mulberry32(8);
+ for(let i=0;i<28;i++) {
+ const coal=new THREE.Mesh(new THREE.DodecahedronGeometry(.034+random()*.025),char);
+ const angle=random()*Math.PI*2,radial=Math.sqrt(random())*.21;
+ coal.position.set(Math.cos(angle)*radial,.54+random()*.03,Math.sin(angle)*radial);
+ coal.rotation.set(random()*3,random()*3,random()*3);coal.castShadow=true;brazier.add(coal);
+ }
+ const smoke=makeSmoke({height:1.9,radius:.075,spread:.19,riseSpeed:.43,wind:[.075,.012],
+ color:0xc8d0d4,density:4.2,quality:'high',seed:33});
+ smoke.position.set(8,.691,0);scene.add(smoke);
+ return {scene,cameras:[
+ {name:'tea_steam',position:[.40,1.14,.72],lookAt:[-.055,.975,-.005],fov:38},
+ {name:'charcoal_smoke',position:[10.7,1.95,4.2],lookAt:[8.16,1.38,0],fov:39},
+ ],update(t){steam.userData.update(t);smoke.userData.update(t);}};
+}
diff --git a/harness/examples/graphics_lab/scenes/stream.js b/harness/examples/graphics_lab/scenes/stream.js
new file mode 100644
index 00000000..b1f836d1
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/stream.js
@@ -0,0 +1,225 @@
+/** A close study of a clear brook, wet granite, gravel and continuous meadow banks. */
+import * as THREE from 'three';
+import { makeStream } from '../lib/stream.js';
+import { makeRock } from '../lib/rock.js';
+import { makeMeadow } from '../lib/meadow.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { patchStandard } from '../lib/shader.js';
+import { mulberry32 } from '../lib/noise.js';
+
+export const BOUNDS = { min: [-18, -2, -22], max: [18, 5, 22] };
+export function heightAt() {
+ return 0;
+}
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ const rig = sunRig({
+ mood: 'day',
+ azimuth: 145,
+ elevation: 39,
+ bounds: 23,
+ intensity: 4.6,
+ fill: 1.25,
+ disc: false,
+ });
+ scene.add(rig.sun, rig.fill);
+ scene.environment = rig.envTex;
+ makeSky(scene, { rig, turbidity: 3.8, scale: 2500 });
+ scene.fog = new THREE.FogExp2(0xb4c7b6, 0.012);
+ const obstacles = [
+ { u: 0.3, lateral: -0.3, radius: 0.36 },
+ { u: 0.48, lateral: 0.4, radius: 0.4 },
+ { u: 0.66, lateral: -0.3, radius: 0.35 },
+ { u: 0.78, lateral: 0.36, radius: 0.24 },
+ ];
+
+ const stream = makeStream({
+ points: [
+ [-2, 1, -19],
+ [0.7, 0.7, -10],
+ [-1.2, 0.35, -2],
+ [1, 0.12, 7],
+ [2, 0, 20],
+ ],
+ width: 3.8,
+ widthVariation: 0.22,
+ depth: 0.43,
+ speed: 1.25,
+ roughness: 0.6,
+ segments: 320,
+ widthSegments: 36,
+ stoneCount: 1200,
+ seed: 81,
+ waterColor: 0x376b57,
+ attenuationDistance: 4.5,
+ reflectionSize: 1024,
+ bedColor: 0x4f422a,
+ obstacles,
+ });
+ scene.add(stream);
+ // The same hydrodynamic obstacles get fractured, wet granite silhouettes in
+ // this composition. Their positions and wake parameters remain unchanged.
+ obstacles.forEach((obstacle, i) => {
+ stream.getObjectByName(`StreamObstacle_${i}`).visible = false;
+ const sample = stream.userData.sample(obstacle.u, obstacle.lateral);
+ const r = obstacle.radius;
+ const rock = makeRock({
+ seed: 405 + i,
+ type: 'granite',
+ size: [r * 1.9, r * 1.1, r * 2.3],
+ detail: 5,
+ color: 0x5c625c,
+ moisture: 0.9,
+ moss: 0.08,
+ weathering: 1.4,
+ });
+ rock.position.copy(sample.position);
+ rock.position.y -= r * 0.65;
+ rock.rotation.y = i * 1.65;
+ scene.add(rock);
+ });
+
+ // One continuous terrain surface avoids visible outer berms or ribbon seams.
+ // Its channel is below the separate stream bed, and its bank grows from the
+ // exact authored water boundary rather than intersecting a rectangular slab.
+ const samples = Array.from({ length: 241 }, (_, i) => stream.userData.sample(i / 240));
+ function nearest(x, z) {
+ const index = Math.max(0, Math.min(240, Math.round(((z + 19) / 39) * 240)));
+ let best = samples[index],
+ distance = Infinity;
+ for (let i = Math.max(0, index - 14); i <= Math.min(240, index + 14); i++) {
+ const sample = samples[i];
+ const d = (x - sample.position.x) ** 2 + (z - sample.position.z) ** 2;
+ if (d < distance) {
+ best = sample;
+ distance = d;
+ }
+ }
+ return { sample: best, offset: Math.sqrt(distance) - best.width * 0.5 };
+ }
+ function terrainHeight(x, z) {
+ const { sample, offset } = nearest(x, z);
+ const outside = Math.max(0, offset);
+ const bank =
+ sample.position.y +
+ (1 - Math.exp(-outside * 0.8)) * 0.55 +
+ Math.sin(x * 0.71 + z * 0.28) * Math.min(outside * 0.15, 0.15) -
+ 0.045;
+ const blend = THREE.MathUtils.smoothstep(offset, -0.24, 0.06);
+ return THREE.MathUtils.lerp(sample.position.y - 0.66, bank, blend);
+ }
+ const terrainGeometry = new THREE.PlaneGeometry(54, 65, 240, 260);
+ terrainGeometry.rotateX(-Math.PI / 2);
+ const p = terrainGeometry.attributes.position;
+ for (let i = 0; i < p.count; i++) p.setY(i, terrainHeight(p.getX(i), p.getZ(i)));
+ terrainGeometry.computeVertexNormals();
+ const terrainMaterial = new THREE.MeshStandardMaterial({ color: 0x414629, roughness: 1 });
+ patchStandard(terrainMaterial, {
+ name: 'MossAndLitter',
+ vertexHead: 'varying vec3 bankP;',
+ vertexBody: 'bankP=position;',
+ fragmentHead: 'varying vec3 bankP;',
+ fragmentBody: `
+ float moss=astraNoise2(bankP.xz*1.8)*.60+astraNoise2(bankP.xz*6.2)*.27+astraNoise2(bankP.xz*25.0)*.13;
+ diffuseColor.rgb*=.42+moss*.75;
+ diffuseColor.rgb=mix(diffuseColor.rgb,vec3(.046,.031,.014),smoothstep(.39,.68,moss)*.55);
+ `,
+ });
+ const terrain = new THREE.Mesh(terrainGeometry, terrainMaterial);
+ terrain.name = 'ContinuousBrookBanks';
+ terrain.receiveShadow = true;
+ scene.add(terrain);
+
+ const rng = mulberry32(801);
+ for (const side of [-1, 1]) {
+ for (let i = 0; i < 42; i++) {
+ // Deposits form loose groups with open gravel between them, rather than
+ // two evenly spaced rows enclosing a landscaped water channel.
+ const cluster = Math.floor(i / 3);
+ const u = 0.05 + (cluster / 14) * .9 + (rng() - .5) * .035;
+ if (rng() < .22) continue;
+ const sample = stream.userData.sample(u, side);
+ const across = new THREE.Vector3(sample.tangent.z, 0, -sample.tangent.x)
+ .normalize()
+ .multiplyScalar(side);
+ const size = 0.20 + rng() ** 1.8 * 1.05;
+ const rock = makeRock({
+ seed: 122 + i + (side + 1) * 30,
+ type: 'granite',
+ size: [size * 1.2, size * 0.62, size],
+ detail: 4,
+ color: 0x62615b,
+ moisture: 0.8,
+ moss: 0.3,
+ });
+ rock.position.copy(sample.position).addScaledVector(across, -.07 + rng() * .92);
+ rock.position.y = terrainHeight(rock.position.x, rock.position.z) - 0.08;
+ rock.rotation.y = rng() * Math.PI * 2;
+ scene.add(rock);
+ }
+ }
+ const shingleGeometry = new THREE.IcosahedronGeometry(1, 1);
+ const shingle = new THREE.InstancedMesh(shingleGeometry,
+ new THREE.MeshStandardMaterial({color:0x827b68,roughness:.83}), 1800);
+ shingle.name = 'BankShingle';
+ shingle.receiveShadow = true;
+ const shinglePose = new THREE.Object3D(), shingleColour = new THREE.Color();
+ for (let i=0;i<shingle.count;i++) {
+ const side = rng()<.5 ? -1 : 1;
+ const sample=stream.userData.sample(.02+rng()*.96,side);
+ const across=new THREE.Vector3(sample.tangent.z,0,-sample.tangent.x).normalize();
+ shinglePose.position.copy(sample.position).addScaledVector(across,side*(.02+rng()**1.9*.9));
+ const radius=.013+rng()**2*.067;
+ shinglePose.position.y=terrainHeight(shinglePose.position.x,shinglePose.position.z)+radius*.12;
+ shinglePose.scale.set(radius*(.8+rng()*.6),radius*(.3+rng()*.25),radius);
+ shinglePose.rotation.set((rng()-.5)*.3,rng()*Math.PI*2,(rng()-.5)*.3);
+ shinglePose.updateMatrix();shingle.setMatrixAt(i,shinglePose.matrix);
+ shingleColour.setHSL(.07+rng()*.055,.06+rng()*.2,.13+rng()*.23);
+ shingle.setColorAt(i,shingleColour);
+ }
+ scene.add(shingle);
+ // Two spatially continuous banks keep a high local blade density while
+ // respecting the per-field memory bound. Their masks meet at the channel.
+ const grasses = [-1, 1].map((side) => {
+ const xOffset = side * 4.5;
+ const grass = makeMeadow({
+ size: [9, 26],
+ density: 1400,
+ maxBlades: 300000,
+ height: 0.26,
+ bladeWidth: 0.013,
+ seed: 193 + (side + 1) * 3,
+ color: 0x405717,
+ dry: 0.1,
+ ground: false,
+ shadows: false,
+ heightAt: (x, z) => terrainHeight(x + xOffset, z),
+ mask(x, z) {
+ x += xOffset;
+ const { offset } = nearest(x, z);
+ const raggedEdge=.16+.14*Math.sin(z*1.17+x*2.8)+.12*Math.sin(z*3.3-x*1.1);
+ const edge = THREE.MathUtils.smoothstep(offset, Math.max(.03,raggedEdge), raggedEdge+.48);
+ const thin = .7+.3*Math.sin(x*1.9+z*.7)*Math.sin(z*1.2-x*.4);
+ return edge * thin;
+ },
+ wind: { direction: [0.8, 0.3], strength: 0.5, speed: 0.8 },
+ });
+ grass.position.x = xOffset;
+ scene.add(grass);
+ return grass;
+ });
+
+ return {
+ scene,
+ cameras: [
+ { name: 'stream', position: [4.4, 4.7, 7.5], lookAt: [0.1, 0.15, 1.4], fov: 43 },
+ { name: 'riffles', position: [2.6, 2.5, 5.8], lookAt: [0.3, 0.12, 2], fov: 40 },
+ ],
+ update(t, dt) {
+ stream.userData.update(t, dt);
+ grasses.forEach((grass) => grass.userData.update(t, dt));
+ },
+ };
+}
diff --git a/harness/examples/graphics_lab/scenes/structural_fire.js b/harness/examples/graphics_lab/scenes/structural_fire.js
new file mode 100644
index 00000000..cefdd8cf
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/structural_fire.js
@@ -0,0 +1,80 @@
+/** A authored damaged cottage with one shared fire/soot field. No structural simulation. */
+import * as THREE from 'three';
+import {makeFireField} from '../lib/firefield.js';
+import {makeMeadow} from '../lib/meadow.js';
+import {makeTree} from '../lib/tree.js';
+import {patchStandard} from '../lib/shader.js';
+import {mulberry32} from '../lib/noise.js';
+import {snapshotResources,attachDisposal} from '../lib/lifecycle.js';
+
+export function createScene(){
+ const scene=new THREE.Scene();scene.background=new THREE.Color(0x3b4652);scene.fog=new THREE.FogExp2(0x3b4652,.014);
+ scene.add(new THREE.HemisphereLight(0xbdcbd7,0x28211c,.8));
+ const sky=new THREE.DirectionalLight(0xc1d2e0,2);sky.position.set(-8,16,4);sky.castShadow=true;sky.shadow.mapSize.set(2048,2048);
+ Object.assign(sky.shadow.camera,{left:-12,right:12,top:12,bottom:-12});sky.shadow.normalBias=.018;scene.add(sky);
+ const random=mulberry32(251),actors=[],opaque=new THREE.Group();opaque.name='BorrowedHouseOccluders';scene.add(opaque);
+ const earthMat=new THREE.MeshStandardMaterial({color:0x666252,roughness:1});
+ patchStandard(earthMat,{name:'CottageYard',vertexHead:'varying vec3 vYard;',vertexBody:'vYard=position;',fragmentHead:'varying vec3 vYard;',fragmentBody:'diffuseColor.rgb*=.65+astraFbm2(vYard.xy*7.0,3)*.6;'});
+ const groundGeometry=new THREE.PlaneGeometry(90,90,80,80),gp=groundGeometry.attributes.position;
+ for(let i=0;i<gp.count;i++){const x=gp.getX(i),z=-gp.getY(i),edge=Math.max(0,Math.hypot(x,z)-14)/30;gp.setZ(i,edge*.8*(1+Math.sin(x*.21+z*.13)));}groundGeometry.computeVertexNormals();
+ const ground=new THREE.Mesh(groundGeometry,earthMat);ground.rotation.x=-Math.PI/2;ground.receiveShadow=true;ground.name='EarthYard';opaque.add(ground);
+ const plaster=new THREE.MeshStandardMaterial({color:0xa39682,roughness:.96});
+ patchStandard(plaster,{name:'SmokeStainedPlaster',vertexHead:'varying vec3 vWall;',vertexBody:'vWall=(modelMatrix*vec4(position,1.0)).xyz;',fragmentHead:'varying vec3 vWall;',fragmentBody:`
+ float n=astraFbm2(vWall.xy*3.0+vWall.z*.2,4);
+ float soot=smoothstep(1.2,2.8,vWall.y)*(.28+.7*astraNoise2(vWall.xz*1.4));
+ diffuseColor.rgb*=mix(.74+n*.4,.17+n*.14,soot);
+ `});
+ const char=new THREE.MeshStandardMaterial({color:0x251f1c,roughness:.94});
+ patchStandard(char,{name:'CharredStructuralTimber',vertexHead:'varying vec3 vBeam;',vertexBody:'vBeam=position;',fragmentHead:'varying vec3 vBeam;',fragmentBody:`
+ float grain=astraFbm2(vBeam.xy*vec2(36.0,5.0)+vBeam.z*4.0,3);diffuseColor.rgb*=.5+grain;
+ `,outputBody:`
+ float split=pow(max(0.0,sin(vBeam.x*109.0+astraNoise2(vBeam.xy*8.0)*5.0)),35.0);
+ gl_FragColor.rgb+=vec3(.035,.001,.00002)*split*smoothstep(.65,.90,astraNoise2(vBeam.xy*5.0+11.0));
+ `});
+ const tile=new THREE.MeshStandardMaterial({color:0x55443a,roughness:.9});
+ const stone=new THREE.MeshStandardMaterial({color:0x575652,roughness:.96});
+ function box(name,size,pos,mat=plaster){const m=new THREE.Mesh(new THREE.BoxGeometry(...size),mat);m.name=name;m.position.set(...pos);m.castShadow=m.receiveShadow=true;opaque.add(m);return m;}
+ // Wall strips make real empty door/window apertures; depth capture can see through them.
+ box('RubbleFoundation',[5.7,.35,4.4],[0,.16,0],stone);box('InteriorFloor',[5.2,.09,4],[0,.36,0],char);
+ box('RearWall',[5.5,2.9,.22],[0,1.78,-2.0]);box('WestWall',[.22,2.9,4],[ -2.65,1.78,0]);
+ box('EastWallLower',[.22,.8,4],[2.65,.72,0]);box('EastWallUpper',[.22,.8,4],[2.65,2.72,0]);
+ for(const z of [-1.6,.0,1.6])box('EastWindowPier',[.22,1.2,.55],[2.65,1.72,z]);
+ box('LeftWindowSill',[2.25,.75,.22],[-1.65,.71,2.0]);box('RightWindowSill',[1.55,.75,.22],[1.98,.71,2.0]);box('FacadeLintel',[5.5,.63,.22],[0,2.91,2.0]);
+ for(const [x,w] of [[-2.47,.56],[-.7,.50],[1.45,.53],[2.51,.48]])box('FacadePier',[w,1.50,.22],[x,1.83,2.0]);
+ // Charred framing and actual roof gaps expose the upper fire without a transparent wall.
+ for(const x of [-2.75,-.88,.88,2.75])box('TimberUpright',[.15,2.9,.27],[x,1.78,2.06],char);
+ for(const y of [2.59,3.18])box('FacadeCrossbeam',[5.65,.15,.28],[0,y,2.08],char);
+ box('LeftWindowSillTimber',[2.30,.15,.28],[-1.65,1.11,2.08],char);box('RightWindowSillTimber',[1.58,.15,.28],[1.98,1.11,2.08],char);
+ for(const x of [-2.75,-1.83,-.91,0,.91,1.83,2.75])for(const side of [-1,1]){
+ const rafter=box('ExposedRoofRafter',[.105,.12,2.53],[x,3.80,side*1.06],char);rafter.rotation.x=side*.51;
+ }
+ box('CharredRidgeBeam',[5.8,.18,.18],[0,4.42,0],char);
+ for(let ix=0;ix<19;ix++)for(let row=0;row<7;row++)for(const side of [-1,1]){
+ const x=-2.8+ix*.31,z=side*(.18+row*.31),y=4.43-Math.abs(z)*.555;
+ const damage=Math.exp(-((x-.55)**2+(z-.6)**2)*.9)+Math.exp(-((x+1.7)**2+(z+.5)**2)*1.2)*.7;
+ if(random()<damage*.94)continue;
+ const t=box('WeatheredRoofTile',[.304,.035,.36],[x,y,z],tile);t.rotation.x=side*.51;t.rotation.z=(random()-.5)*.035;
+ }
+ box('BrickChimney',[.56,1.62,.62],[-1.95,4.32,-.57],stone);
+ for(let row=0;row<9;row++){const band=box('ChimneyMortar',[.57,.016,.63],[-1.95,3.56+row*.18,-.57],plaster);band.material=plaster;}
+ // A few fallen beams and fragments connect the damaged roof to the yard.
+ for(let i=0;i<18;i++){const debris=box('FallenTimber',[.10+random()*.05,.08,.35+random()*.7],[(random()-.5)*5.7,.08,2.4+random()*1.7],char);debris.rotation.y=random()*Math.PI;debris.rotation.z=(random()-.5)*.15;}
+ const grass=makeMeadow({size:[30,26],density:170,height:.22,dry:.24,maxBlades:90000,seed:32,
+ mask:(x,z)=>Math.min(1,Math.max(0,(Math.max(Math.abs(x)-3.8,Math.abs(z)-3.5))*.9)),wind:{strength:.34,speed:1.1}});scene.add(grass);actors.push(grass);
+ for(let i=0;i<5;i++){const tree=makeTree({height:8+i*.5,crownRadius:2.5,leafDensity:.40,maxLeaves:5500,leafSegments:4,seed:100+i,shadows:false});tree.position.set((i-2)*5.5,0,-9-random()*3);scene.add(tree);actors.push(tree);}
+ const fire=makeFireField({name:'CottageSharedFire',seed:107,quality:'high',wind:[.32,.10],intensity:.88,
+ emitters:[
+ {position:[-1.62,.65,1.55],radius:.68,height:2.5},{position:[.33,.58,1.53],radius:.65,height:3.1},
+ {position:[1.86,.50,.93],radius:.64,height:2.7},{position:[2.44,1.25,.75],radius:.42,height:2.2},
+ {position:[-.85,1.5,.05],radius:.75,height:3.7},{position:[1.1,2.4,-.15],radius:.78,height:3.8},
+ {position:[-1.60,2.92,-.50],radius:.54,height:2.7},{position:[.18,3.4,.74],radius:.60,height:3.1},
+ ],smoke:{height:10,density:2.0,albedo:0x4f4a43},embers:{count:160,size:[.002,.010],lifetime:[2,5],riseSpeed:2.2},lighting:{count:4,intensity:38},occluders:[opaque],depthResolution:1024});scene.add(fire);actors.push(fire);
+ for(const light of fire.children.filter(o=>o.isPointLight).slice(0,2)){light.castShadow=true;light.shadow.mapSize.set(512,512);light.shadow.camera.near=.1;light.shadow.camera.far=18;light.shadow.normalBias=.025;}
+ const resources=snapshotResources(opaque);resources.add(sky);
+ for(const actor of actors)resources.add({dispose:()=>actor.userData.dispose()});attachDisposal(scene,resources);
+ return {scene,cameras:[
+ {name:'cottage_fire',position:[10.5,6.3,14.7],lookAt:[0,3.8,0],fov:43},
+ {name:'window_fire',position:[.9,2.45,7.2],lookAt:[.25,1.75,1.1],fov:47},
+ {name:'roof_fire',position:[6.8,7.8,8.3],lookAt:[0,4.0,.0],fov:44},
+ ],update(t,dt){actors.forEach(a=>a.userData.update(t,dt));},dispose(){scene.userData.dispose();}};
+}
diff --git a/harness/examples/graphics_lab/scenes/tree.js b/harness/examples/graphics_lab/scenes/tree.js
new file mode 100644
index 00000000..e0309745
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/tree.js
@@ -0,0 +1,62 @@
+/** A sunlit woodland edge: connected oak limbs, birch bark and a low hazel-like understory. */
+import * as THREE from 'three';
+import {makeTree,makeShrub} from '../lib/tree.js';
+import {makeMeadow} from '../lib/meadow.js';
+import {makeRock} from '../lib/rock.js';
+import {makeImposters} from '../lib/woodland.js';
+import {sunRig} from '../lib/environment.js';
+import {makeSky} from '../lib/sky.js';
+import {patchStandard} from '../lib/shader.js';
+
+export function createScene(){
+ const scene=new THREE.Scene();
+ const rig=sunRig({mood:'day',azimuth:125,elevation:31,bounds:12,intensity:4,fill:1.2});
+ scene.add(rig.sun,rig.sun.target,rig.fill);scene.environment=rig.envTex;makeSky(scene,{rig});
+ rig.sun.shadow.mapSize.set(4096,4096);rig.sun.shadow.normalBias=.004;rig.sun.shadow.radius=1.8;
+ scene.fog=new THREE.FogExp2(0xb5c3b5,.015);
+ scene.userData.grade={contrast:1.03,saturation:.94,warmth:.01};
+ const heightAt=(x,z)=>.08*Math.sin(x*.5)+.055*Math.sin(z*.4+x*.25);
+ const wind={dir:[1,.3],strength:.75,speed:.85};
+ const oak=makeTree({species:'oak',height:6.8,crownRadius:2.8,seed:23,wind});
+ oak.position.set(-.8,heightAt(-.8,0),0);scene.add(oak);
+ const birch=makeTree({species:'birch',height:6.6,crownRadius:1.5,leafDensity:.30,seed:76,wind});
+ birch.position.set(4,heightAt(4,-3),-3);scene.add(birch);
+ const willow=makeTree({species:'willow',height:5.3,crownRadius:2.1,leafDensity:.28,seed:12,wind});
+ willow.position.set(-5.2,heightAt(-5.2,-5),-5);scene.add(willow);
+ const shrub=makeShrub({height:1.35,crownRadius:1.1,leafSize:.09,leafDensity:.22,seed:41,wind});
+ shrub.position.set(3.3,heightAt(3.3,1),1);scene.add(shrub);
+ const grass=makeMeadow({size:[19,17],height:.30,density:550,maxBlades:80000,segments:3,bladeWidth:.022,
+ seed:39,color:0x526b2c,dry:.12,heightAt,wind,ground:false,seedHeads:.001,
+ mask:(x,z)=>(.25+.75*THREE.MathUtils.smoothstep(Math.hypot(x+.8,z),.35,1.1))
+ *THREE.MathUtils.smoothstep(Math.min(9.5-Math.abs(x),8.5-Math.abs(z)),0,2)});
+ scene.add(grass);
+ const terrain=new THREE.PlaneGeometry(600,600,220,220);terrain.rotateX(-Math.PI/2);
+ const p=terrain.attributes.position;
+ const earthHeight=(x,z)=>heightAt(x,z)-.008+1.7*Math.exp(-(((z+29)/14)**2))*THREE.MathUtils.smoothstep(-z,15,30);
+ for(let i=0;i<p.count;i++){
+ const x=Math.sign(p.getX(i))*300*Math.pow(Math.abs(p.getX(i))/300,1.8);
+ const z=Math.sign(p.getZ(i))*300*Math.pow(Math.abs(p.getZ(i))/300,1.8);
+ p.setXYZ(i,x,earthHeight(x,z),z);
+ }
+ terrain.computeVertexNormals();
+ const material=new THREE.MeshStandardMaterial({color:0x34321e,roughness:1,envMapIntensity:.65});
+ patchStandard(material,{name:'TreeGladeEarth',vertexHead:'varying vec3 vGlade;',vertexBody:'vGlade=transformed;',
+ uniforms:{uGladeFar:{value:new THREE.Color(0x5d6544)}},
+ fragmentHead:'varying vec3 vGlade; uniform vec3 uGladeFar;',
+ fragmentBody:`float earthDistance=smoothstep(10.,26.,length(vGlade.xz));
+ diffuseColor.rgb=mix(diffuseColor.rgb,uGladeFar,earthDistance);
+ diffuseColor.rgb*=.66+.62*astraFbm2(vGlade.xz*14.,3);
+ float litter=astraFbm2(vGlade.xz*2.1,2);
+ diffuseColor.rgb=mix(diffuseColor.rgb,vec3(.08,.063,.027),smoothstep(.48,.70,litter)*.4);`});
+ const ground=new THREE.Mesh(terrain,material);ground.receiveShadow=true;scene.add(ground);
+ const distant=makeImposters({source:'tree',count:230,extent:110,height:8,seed:51,
+ color:0x49672b,rig,wind,heightAt:(x,z)=>earthHeight(x,z-142)});
+ distant.position.z=-142;scene.add(distant);
+ const rock=makeRock({size:[1.1,.55,.8],seed:97,type:'granite',detail:3,moss:.4});
+ rock.position.set(-2.5,heightAt(-2.5,2.2)-.08,2.2);scene.add(rock);
+ const animated=[oak,birch,willow,shrub,grass,distant];
+ return {scene,cameras:[
+ {name:'woodland',position:[9.5,4.3,13.8],lookAt:[-.4,3.15,-.7],fov:43},
+ {name:'branches',position:[2.7,3.5,4.5],lookAt:[-.1,3.55,-.1],fov:42},
+ ],update(t,dt){for(const object of animated)object.userData.update(t,dt);}};
+}
diff --git a/harness/examples/graphics_lab/scenes/waterfall.js b/harness/examples/graphics_lab/scenes/waterfall.js
new file mode 100644
index 00000000..bd77e10d
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/waterfall.js
@@ -0,0 +1,202 @@
+/** An old stone weir in a wooded stream: a falling sheet and a shallow plunge pool. */
+import * as THREE from 'three';
+import { ConvexGeometry } from 'three/addons/geometries/ConvexGeometry.js';
+import { makeWaterfall } from '../lib/waterfall.js';
+import { makeStream } from '../lib/stream.js';
+import { makeRock } from '../lib/rock.js';
+import { makeMeadow } from '../lib/meadow.js';
+import { makeTree, makeShrub } from '../lib/tree.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { patchTriplanar } from '../lib/terrain_shade.js';
+import { patchStandard } from '../lib/shader.js';
+import { mulberry32, fbm2 } from '../lib/noise.js';
+
+export function createScene() {
+ const scene = new THREE.Scene(), height = 1.85;
+ const rig = sunRig({mood:'day',azimuth:138,elevation:44,bounds:14,
+ intensity:4.1,fill:.82,disc:false});
+ scene.add(rig.sun,rig.fill); scene.environment=rig.envTex;
+ rig.sun.shadow.mapSize.set(4096,4096); rig.sun.shadow.normalBias=.009;
+ makeSky(scene,{rig,turbidity:3.2,scale:1800});
+ scene.fog=new THREE.FogExp2(0x9ca99b,.018);
+ const waterfall=makeWaterfall({height,width:2.2,speed:.9,thickness:.055,
+ breakup:.68,foam:.56,quality:'high',seed:17,sprayRate:280});
+ // Surface froth has a little height above the receiving stream's wave crests.
+ waterfall.getObjectByName('WaterfallImpactFoam').position.y=.037;
+ scene.add(waterfall);
+ const upstream=makeStream({points:[[.6,height,-13],[.2,height,-6],[0,height,-2],[0,height,0]],
+ width:2.2,widthVariation:0,endFade:.65,depth:.22,speed:.9,segments:120,widthSegments:20,
+ stoneCount:140,obstacles:[],seed:88,roughness:.20,reflectionSize:0,
+ bedColor:0x4b4833,waterColor:0x92af88,attenuationDistance:4.2});
+ const downstream=makeStream({points:[[0,0,-.02],[0,0,2.1],[.32,-.035,5],[.9,-.10,13]],
+ width:3.8,widthVariation:.11,depth:.43,speed:.72,segments:180,widthSegments:28,
+ stoneCount:420,seed:81,roughness:.26,reflectionSize:512,
+ bedColor:0x5a503c,waterColor:0x647f59,attenuationDistance:4.5,obstacles:[]});
+ scene.add(upstream,downstream);
+ const smooth=(a,b,v)=>THREE.MathUtils.smoothstep(v,a,b);
+ const lowerSamples=Array.from({length:261},(_,i)=>downstream.userData.sample(i/260));
+ const upperSamples=Array.from({length:161},(_,i)=>upstream.userData.sample(i/160));
+ const closest=(x,z,samples)=>{
+ let best=samples[0],distance=Infinity;
+ for(const sample of samples) {
+ const d=(x-sample.position.x)**2+(z-sample.position.z)**2;
+ if(d<distance){distance=d;best=sample;}
+ }
+ return {sample:best,offset:Math.sqrt(distance)-best.width*.5};
+ };
+ const heightAt=(x,z)=>{
+ // Only the short built weir retains a sharp level change. The earth at its
+ // ends grades continuously between upstream and downstream elevations.
+ const upper=closest(x,z,upperSamples),lower=closest(x,z,lowerSamples);
+ const span=.01+2.0*smooth(1.7,3.0,Math.abs(x));
+ const blend=smooth(-.28-span,-.28+span,z);
+ const waterY=THREE.MathUtils.lerp(upper.sample.position.y,lower.sample.position.y,blend);
+ const offset=THREE.MathUtils.lerp(upper.offset,lower.offset,blend);
+ const outside=Math.max(0,offset),noise=fbm2(x*.32,z*.32,{seed:37});
+ const grade=height*(1-smooth(-2.3-Math.abs(x)*.13,2.0+Math.abs(x)*.12,z));
+ const hill=.55*Math.sin(x*.24+z*.13)+.30*Math.cos(z*.28-x*.16)+noise*.35;
+ const upland=grade+.25+hill*smooth(.3,3.2,outside);
+ const bank=waterY-.025+outside*.16+noise*.07;
+ if(Math.abs(x)<1.23 && z>-.28 && z<.9) return -.63;
+ const channel=waterY-.66;
+ const shore=THREE.MathUtils.lerp(channel,bank,smooth(-.17,.045,offset));
+ return THREE.MathUtils.lerp(shore,upland,smooth(.30,2.8,outside));
+ };
+ const groundMaterial=new THREE.MeshStandardMaterial({color:0x4c4c32,roughness:.98});
+ patchTriplanar(groundMaterial,{scale:.24,relief:.006,roughness:.98,colorA:0x20291a,colorB:0x4c5032});
+ const groundGeometry=new THREE.PlaneGeometry(46,54,240,280);groundGeometry.rotateX(-Math.PI/2);
+ const p=groundGeometry.attributes.position;
+ for(let i=0;i<p.count;i++) p.setY(i,heightAt(p.getX(i),p.getZ(i)));
+ groundGeometry.computeVertexNormals();
+ const ground=new THREE.Mesh(groundGeometry,groundMaterial);
+ ground.name='WoodlandBanks';ground.receiveShadow=true;scene.add(ground);
+
+ // Weathered masonry explains the straight spillway. The banks roll around
+ // its abutments instead of continuing as a sheer, uninterrupted earth wall.
+ const random=mulberry32(47),masonry=new THREE.Group();masonry.name='OldStoneWeir';
+ const materials=[],wetMaterials=[];
+ for(let i=0;i<8;i++) {
+ for(const wet of [false,true]) {
+ const material=new THREE.MeshStandardMaterial({roughness:wet?.50:.93});
+ const tint=(random()-.5)*.11;
+ patchTriplanar(material,{scale:.053,relief:.004,roughness:wet?.50:.93,
+ colorA:new THREE.Color(wet?0x343d30:0x575a4c).offsetHSL(0,0,tint*.6),
+ colorB:new THREE.Color(wet?0x59634f:0x777463).offsetHSL(0,0,tint)});
+ patchStandard(material,{name:'WeirStoneAge',fragmentBody:`
+ float weirColony=smoothstep(.36,.66,astraFbm2(vAstraWorld.xz*8.0+vAstraWorld.y*2.6,3));
+ float weirMoss=(pow(max(0.0,vAstraWorldN.y),3.0)*.36
+ +exp(-max(0.0,vAstraWorld.y)*3.0)*.57)*weirColony;
+ diffuseColor.rgb=mix(diffuseColor.rgb,vec3(.058,.075,.025),weirMoss);
+ float weirWet=(1.0-smoothstep(.03,.43,vAstraWorld.y))*.38;
+ diffuseColor.rgb*=1.0-weirWet;`});
+ (wet?wetMaterials:materials).push(material);
+ }
+ }
+ let blockId=0;
+ const block=(name,x,y,z,w,h,d,wet=false)=>{
+ // Broken corners give each stone a broad face and a rough, chipped outline.
+ // Face planes remain connected; this is dressed rubble, not a pile of spheres.
+ const vertices=[],shear=(random()-.5)*.065,tilt=(random()-.5)*.035;
+ for(const sx of [-1,1])for(const sy of [-1,1])for(const sz of [-1,1]) {
+ const px=sx*w*.50+sy*shear,py=sy*h*.50, pz=sz*d*.50+sx*tilt;
+ const cx=w*(.025+random()*.11),cy=h*(.045+random()*.19),cz=d*(.015+random()*.045);
+ vertices.push(new THREE.Vector3(px-sx*cx,py,pz),new THREE.Vector3(px,py-sy*cy,pz),
+ new THREE.Vector3(px,py,pz-sz*cz));
+ }
+ const material=(wet?wetMaterials:materials)[blockId++%8];
+ const mesh=new THREE.Mesh(new ConvexGeometry(vertices),material);
+ mesh.name=name;mesh.position.set(x,y,z);mesh.rotation.z=(random()-.5)*.025;
+ mesh.castShadow=true;mesh.receiveShadow=true;masonry.add(mesh);return mesh;
+ };
+ // A recessed backing fills small mortar joints without a bright earth leak.
+ const backing=new THREE.Mesh(new THREE.BoxGeometry(3.10,2.05,.45),
+ new THREE.MeshStandardMaterial({color:0x242820,roughness:.95}));
+ backing.position.set(0,.8,-.30);backing.receiveShadow=true;masonry.add(backing);
+ for(let row=0;row<7;row++) {
+ let left=-1.65;
+ while(left<1.65) {
+ const w=Math.min(1.65-left,.36+random()*.32);if(w<.07)break;
+ block('WetWeirCourse',left+w*.5,-.15+row*.295,-.23-random()*.025,w-.008,.28,.44,true);
+ left+=w;
+ }
+ }
+ // Coping sits below the six-centimetre water layer at the crest.
+ for(let i=0;i<6;i++)block('SubmergedCoping',-1.10+(i+.5)*2.2/6,height-.145,-.34,
+ 2.2/6-.005,.16,.76,true);
+ for(const side of [-1,1]) {
+ for(let row=0;row<8;row++) {
+ let edge=1.15;
+ while(edge<2.50) {
+ const w=Math.min(2.50-edge,.30+random()*.36);if(w<.06)break;
+ block('WeirAbutment',side*(edge+w*.5),-.10+row*.30,-.22-random()*.04,w,.282,.90+random()*.12);
+ edge+=w;
+ }
+ }
+ for(let j=0;j<3;j++)block('WornAbutmentCap',side*(1.36+j*.45),2.16,-.24,.46,.17,1.02);
+ for(let i=0;i<4;i++)block('UpstreamWing',side*(1.43+i*.05),height+.15,-1.0-i*.54,.47,.52,.53);
+ }
+ scene.add(masonry);
+
+ const stones=[];
+ for(let i=0;i<59;i++) {
+ const side=i%2?1:-1,z=-5+random()*14;
+ const reference=closest(0,z,z<-.3?upperSamples:lowerSamples).sample;
+ const x=reference.position.x+side*(reference.width*.5+.06+random()*.60);
+ if(Math.abs(z)<.95)continue;
+ const size=[.19+random()*.48,.13+random()*.30,.20+random()*.52];
+ const stone=makeRock({type:i%5===0?'sandstone':'basalt',size,seed:310+i,detail:4,
+ color:i%5===0?0x71674d:0x565b4a,moisture:.52,moss:.18,weathering:1.1});
+ stone.position.set(x,heightAt(x,z)-size[1]*.24,z);stone.rotation.y=random()*6.28;
+ scene.add(stone);stones.push({x,z,r:Math.max(size[0],size[2])*.48});
+ }
+ for(const [x,z,s] of [[-2.25,1.0,1.0],[2.62,.60,.8],[-2.55,-.55,.76],[2.9,-1.4,1.10]]) {
+ const rock=makeRock({type:'sandstone',size:[s,s*.62,s*.8],seed:700+Math.round(s*100),
+ detail:5,color:0x65624c,moisture:.32,moss:.35,weathering:1.3});
+ rock.position.set(x,heightAt(x,z)-s*.20,z);rock.rotation.y=random()*6.28;scene.add(rock);
+ stones.push({x,z,r:s*.48});
+ }
+ const meadow=makeMeadow({size:[17,23],height:.26,density:1400,maxBlades:230000,segments:4,seed:83,
+ color:0x4c6428,bladeWidth:.014,dry:.12,ground:false,seedHeads:.002,heightAt,
+ mask:(x,z)=>{
+ const {offset}=closest(x,z,z<-.3?upperSamples:lowerSamples);
+ let mask=smooth(.03,.46,offset)*(.70+.30*smooth(.15,.8,.5+2*fbm2(x*.8,z*.8,{seed:16})));
+ mask*=1-smooth(.88,1,Math.max(Math.abs(x)/8.5,Math.abs(z)/11.5));
+ if(Math.abs(x)<2.52&&z>-.76&&z<.34)return 0;
+ if(Math.abs(Math.abs(x)-1.52)<.42&&z<-1&&z>-3.1)return 0;
+ for(const rock of stones)mask*=smooth(rock.r*.45,rock.r,Math.hypot(x-rock.x,z-rock.z));
+ return mask;
+ },wind:{direction:[1,.4],strength:.28,speed:.7}});
+ scene.add(meadow);
+ const distantGrass=makeMeadow({size:[42,47],height:.22,density:100,maxBlades:50000,segments:3,seed:21,
+ color:0x526332,bladeWidth:.018,dry:.16,ground:false,seedHeads:0,heightAt,
+ mask:(x,z)=>smooth(.83,1,Math.max(Math.abs(x)/8.5,Math.abs(z)/11.5))*smooth(.10,.9,
+ closest(x,z,z<-.3?upperSamples:lowerSamples).offset),
+ wind:{direction:[1,.4],strength:.24,speed:.7}});
+ scene.add(distantGrass);
+ const plants=[];
+ for(const [species,x,z,h,r,seed] of [
+ ['willow',-4.4,-3.8,5.8,2.65,37],['birch',4.8,-6.4,6.7,2.0,83],
+ ['oak',-7.5,-8.2,7.0,3.3,52],['birch',1.5,-11.0,5.8,1.9,73],
+ ]) {
+ const tree=makeTree({species,height:h,crownRadius:r,seed,leafDensity:.58,maxLeaves:species==='willow'?5200:3000,
+ wind:{dir:[1,.4],strength:.24,speed:.7},shadows:true});
+ tree.position.set(x,heightAt(x,z)-.06,z);scene.add(tree);plants.push(tree);
+ }
+ for(const [x,z,h,seed] of [[-3.0,-.5,1.25,10],[3.1,-2.2,1.5,18],[-3.1,3.4,.82,14],
+ [4.4,1.5,1.15,48],[-6,-4.8,2.25,63],[3.8,-8.3,2.7,82]]) {
+ const shrub=makeShrub({height:h,crownRadius:h*.67,seed,leafDensity:.42,maxLeaves:1600,
+ wind:{dir:[1,.4],strength:.20,speed:.7}});
+ shrub.position.set(x,heightAt(x,z)-.055,z);scene.add(shrub);plants.push(shrub);
+ }
+ return {scene,cameras:[
+ {name:'basalt_falls',position:[3.3,2.0,4.9],lookAt:[0,.95,.35],fov:43},
+ {name:'falling_film',position:[1.28,1.05,2.42],lookAt:[.02,.95,.48],fov:38},
+ {name:'spillway_lip',position:[2.8,3.2,1.9],lookAt:[0,1.52,-.12],fov:42},
+ {name:'woodland_weir',position:[4.6,2.6,7.0],lookAt:[-.2,1.30,-.4],fov:43},
+ ],update(t,dt){
+ waterfall.userData.update(t,dt);upstream.userData.update(t,dt);downstream.userData.update(t,dt);
+ meadow.userData.update(t,dt);distantGrass.userData.update(t,dt);
+ for(const plant of plants)plant.userData.update(t,dt);
+ }};
+}
diff --git a/harness/examples/graphics_lab/scenes/workshop.js b/harness/examples/graphics_lab/scenes/workshop.js
new file mode 100644
index 00000000..c0a14d64
--- /dev/null
+++ b/harness/examples/graphics_lab/scenes/workshop.js
@@ -0,0 +1,156 @@
+/** A weathered workshop courtyard: masonry, worn metal, cloth and road detail. */
+import * as THREE from 'three';
+import * as MAT from '../lib/materials.js';
+import { clonePatchedMaterial } from '../lib/shader.js';
+import { patchDripStains, patchRust, patchDust } from '../lib/aging.js';
+import { patchMicroBreakup } from '../lib/surface_wear.js';
+import { patchRoadSurface, patchSeamBand, patchTracks } from '../lib/roadway.js';
+import { makeText, loadHelvetiker } from '../lib/signage.js';
+import { sunRig } from '../lib/environment.js';
+import { makeSky } from '../lib/sky.js';
+import { snapshotResources, attachDisposal } from '../lib/lifecycle.js';
+import { mulberry32 } from '../lib/noise.js';
+import { makePaving } from '../lib/paving.js';
+
+export async function createScene() {
+ const scene=new THREE.Scene(),rand=mulberry32(62);
+ const rig=sunRig({mood:'day',elevation:34,azimuth:138,bounds:22,disc:false});
+ rig.sun.shadow.mapSize.set(4096,4096);rig.sun.shadow.normalBias=.012;
+ scene.add(rig.sun,rig.fill);scene.environment=rig.envTex;
+ makeSky(scene,{rig,turbidity:2.8});scene.fog=new THREE.FogExp2(0xc5bba5,.012);
+ const own=material=>clonePatchedMaterial(material);
+ const brick=own(MAT.brick({color:0x795343,bump:.012,roughness:.88}));
+ patchDripStains(brick,{from:3.4,strength:.45,scale:.7,seed:19});
+ patchDust(brick,{strength:.16,seed:9});
+ const stone=own(MAT.travertine({color:0x929082,roughness:.94}));
+ patchMicroBreakup(stone,{scale:.16,strength:.15,seed:13});
+ const wood=own(MAT.weatheredWood({color:0x655341,roughness:.9}));
+ patchDripStains(wood,{strength:.22,scale:.4,seed:23});
+ const iron=new THREE.MeshStandardMaterial({color:0x777b78,roughness:.38,metalness:1});
+ patchRust(iron,{strength:1,scale:.34,seed:8});
+ patchDust(iron,{strength:.12,seed:48});
+ const dark=new THREE.MeshStandardMaterial({color:0x181b1c,roughness:.94});
+
+ // Planar world-metre UVs register courses across separately modelled piers.
+ function box(name,size,position,material,rotation=0) {
+ const g=new THREE.BoxGeometry(...size),p=g.attributes.position,n=g.attributes.normal,uv=g.attributes.uv;
+ for(let i=0;i<p.count;i++){
+ const x=p.getX(i)+position[0],y=p.getY(i)+position[1],z=p.getZ(i)+position[2];
+ if(Math.abs(n.getY(i))>.5)uv.setXY(i,x,z);
+ else if(Math.abs(n.getX(i))>.5)uv.setXY(i,z,y);
+ else uv.setXY(i,x,y);
+ }
+ if(material===wood){
+ const offset=rand(),along=rand();
+ for(let i=0;i<uv.count;i++){
+ const u=uv.getX(i),v=uv.getY(i);
+ uv.setXY(i,(size[0]>size[1]?v:u)+offset,(size[0]>size[1]?u:v)+along);
+ }
+ }
+ const mesh=new THREE.Mesh(g,material);mesh.name=name;mesh.position.set(...position);mesh.rotation.y=rotation;
+ mesh.castShadow=true;mesh.receiveShadow=true;mesh.userData.placement='free';scene.add(mesh);return mesh;
+ }
+ const earth=own(MAT.soil({color:0x665e4c,roughness:.98,repeat:2}));
+ box('CourtyardFoundation',[50,.25,50],[0,-.17,0],earth);
+ box('LeftBrickPier',[3.35,3.65,.42],[-3.325,1.825,-3.25],brick);
+ box('RightBrickPier',[3.35,3.65,.42],[3.325,1.825,-3.25],brick);
+ box('DoorLintelBrick',[3.3,1.05,.42],[0,3.125,-3.25],brick);
+ box('WorkshopSideWall',[.4,3.65,5.8],[-5.0,1.825,-6],brick);
+ box('WorkshopOtherSide',[.4,3.65,5.8],[5.0,1.825,-6],brick);
+ box('ShadowedBackWall',[10,3.5,.3],[0,1.7,-8.8],dark);
+ box('WorkshopRoof',[10.65,.18,6.4],[0,3.8,-6.0],dark);
+ box('RoofStoneCoping',[10.35,.13,.65],[0,3.7,-3.22],stone);
+ box('StoneDoorLintel',[3.65,.25,.62],[0,2.72,-3.14],stone);
+ box('DoorStep',[3.7,.16,1.0],[0,.07,-2.85],stone);
+ for(const x of [-1.75,1.75])box('StoneDoorJamb',[.22,2.65,.6],[x,1.4,-3.13],stone);
+ // A leaf left ajar reveals real interior depth and lets its hinges catch light.
+ const leaf=new THREE.Group();leaf.position.set(-1.61,.16,-3.0);leaf.rotation.y=-.48;
+ for(let i=0;i<7;i++){
+ const board=box('DoorBoard',[.215,2.42,.065],[0,0,0],wood);
+ scene.remove(board);leaf.add(board);board.position.set(.117+i*.23,1.21,0);
+ }
+ for(const y of [.35,1.95]){
+ const strap=box('ForgedDoorStrap',[1.43,.085,.025],[0,0,0],iron);
+ scene.remove(strap);leaf.add(strap);strap.position.set(.74,y,.055);
+ }
+ scene.add(leaf);
+ const shutter=own(MAT.paintedWood({color:0x495a4a,roughness:.83}));
+ patchDripStains(shutter,{strength:.4,scale:.24,seed:12});
+ box('ShutterRecess',[2.2,1.45,.06],[-3.25,1.74,-2.994],dark);
+ for(let i=0;i<10;i++)box('WindowShutterBoard',[.204,1.37,.045],[-4.25+i*.22,1.74,-2.941],shutter);
+ for(const y of [1.22,2.26])box('ShutterBrace',[2.17,.055,.03],[-3.25,y,-2.903],iron);
+ const pipe=new THREE.Mesh(new THREE.CylinderGeometry(.047,.047,3.5,16),iron);
+ pipe.name='Downpipe';pipe.position.set(4.67,1.8,-2.94);pipe.castShadow=true;scene.add(pipe);
+ for(let i=0;i<3;i++)box('InteriorTimberStack',[2.2,.22,.35],[.5,.24+i*.25,-4.6],wood,.08);
+
+ // Real stones give the foreground a walkable profile and joint shadows.
+ const yard=makePaving({size:[6.9,11],stoneSize:.24,joint:.009,thickness:.105,
+ relief:.014,color:0x64625b,jointColor:0x514b3e,roughness:.89,seed:62});
+ yard.position.set(-1.55,.035,2.4);scene.add(yard);
+ const roadMat=new THREE.MeshStandardMaterial({color:0x4c4b46,roughness:.9});
+ patchRoadSurface(roadMat,{aggregate:.62,wear:.68,patches:.28,gutter:.4,halfWidth:1.7,lane:3.4,seed:36});
+ patchSeamBand(roadMat,{width:.26,weeds:.16});
+ const road=box('ServiceLane',[3.4,.075,30],[3.65,-.025,3],roadMat);
+ // Rotate the geometry's frame with the mesh: the road patch sees this axis.
+ road.rotation.y=0;
+ for(let i=0;i<22;i++)box('KerbStone',[.22,.18,.49],[1.86,.035,-2.9+i*.51],stone);
+ const mud=new THREE.MeshStandardMaterial({color:0x5d5140,roughness:.95});
+ patchMicroBreakup(mud,{scale:.13,strength:.22,seed:32});
+ patchTracks(mud,{depth:.8,kind:'foot',count:1,offset:.1,seed:42});
+ box('SoftVerge',[1.65,.052,12],[-5.5,-.015,2.3],mud);
+
+ // Woven canvas has a sagged silhouette, hanging hem and a fine weave finish.
+ const cloth=own(MAT.fabric({color:0x666b4d,repeat:5,bump:.0008,roughness:.94}));
+ const clothGeo=new THREE.PlaneGeometry(3.2,1.25,48,18),cp=clothGeo.attributes.position;
+ for(let i=0;i<cp.count;i++){
+ const x=cp.getX(i),depth=cp.getY(i)+.625;
+ cp.setXYZ(i,x,2.76-depth*.23-.13*Math.cos(x/3.2*Math.PI),-3+depth);
+ }
+ clothGeo.computeVertexNormals();const canopy=new THREE.Mesh(clothGeo,cloth);canopy.name='CanvasAwning';
+ canopy.position.x=-3.25;canopy.castShadow=true;canopy.receiveShadow=true;cloth.side=THREE.DoubleSide;scene.add(canopy);
+ for(const x of [-4.78,-1.72])box('AwningSupport',[.045,.045,1.45],[x,2.59,-2.43],iron);
+ const hemGeometry=new THREE.PlaneGeometry(3.2,.12,48,1),hp=hemGeometry.attributes.position;
+ for(let i=0;i<hp.count;i++){
+ const x=hp.getX(i),drop=hp.getY(i)-.06;
+ hp.setXYZ(i,x,2.4725-.13*Math.cos(x/3.2*Math.PI)+drop,-1.745);
+ }
+ hemGeometry.computeVertexNormals();const hem=new THREE.Mesh(hemGeometry,cloth);hem.position.x=-3.25;
+ hem.name='AwningHem';hem.castShadow=true;scene.add(hem);
+ // A small crate gives the fabric and iron real contact and human scale.
+ for(let level=0;level<3;level++){
+ for(const z of [-.14,.72])box('CrateSideBoard',[1.2,.18,.05],[-2.85,.18+level*.205,z],wood);
+ for(const x of [-3.45,-2.25])box('CrateEndBoard',[.05,.18,.88],[x,.18+level*.205,.29],wood);
+ }
+ for(const x of [-3.4,-2.3])for(const z of [-.1,.68])box('CrateCorner',[.07,.66,.07],[x,.36,z],wood);
+ const drum=new THREE.Mesh(new THREE.CylinderGeometry(.38,.37,.92,64,12),iron);
+ drum.name='WeatheredSteelDrum';drum.position.set(-4.18,.47,-.23);drum.castShadow=true;drum.receiveShadow=true;scene.add(drum);
+ for(const y of [.13,.44,.79]){
+ const hoop=new THREE.Mesh(new THREE.TorusGeometry(.382,.015,8,64),iron);hoop.rotation.x=Math.PI/2;
+ hoop.position.set(-4.18,y,-.23);hoop.castShadow=true;scene.add(hoop);
+ }
+ // Irregular chips settle against the kerb and masonry instead of floating.
+ for(let i=0;i<36;i++){
+ const x=i<20?1.56+rand()*.18:-4.75+rand()*.4,z=-2.5+rand()*9;
+ box('LooseStoneChip',[.025+rand()*.065,.018+rand()*.025,.025+rand()*.06],
+ [x,.055,z],stone,rand()*Math.PI);
+ }
+ const signBacking=box('SignBacking',[2.6,.42,.07],[-3.3,3.17,-2.98],dark);
+ const font=await loadHelvetiker();
+ const sign=await makeText('RIVER WORKSHOP',{font,size:.18,depth:.006,color:0xc3ba97});
+ sign.position.set(-3.3,3.10,signBacking.position.z+.045);scene.add(sign);
+ scene.userData.grade={exposure:1.0,contrast:1.035,saturation:.96};
+ const resources=snapshotResources(scene);resources.add(rig.envTex);
+ // Delegate nested effect ownership so their individual disposal guards
+ // remain correct when a caller removes one before closing the scene.
+ for(const effect of [yard,sign]){
+ for(const resource of snapshotResources(effect))resources.delete(resource);
+ resources.add({dispose:()=>effect.userData.dispose()});
+ }
+ attachDisposal(scene,resources);
+ return {scene,cameras:[
+ {name:'courtyard',position:[7.6,3.6,9.5],lookAt:[-1.0,1.05,-1.2],fov:48},
+ {name:'masonry_and_cloth',position:[-5.15,2.02,.9],lookAt:[-3.12,1.91,-2.65],fov:49},
+ {name:'stone_and_tracks',position:[-.8,.65,6.5],lookAt:[1.2,.15,1.5],fov:51},
+ {name:'rust_and_grain',position:[-3.35,1.05,1.35],lookAt:[-3.7,.75,-.12],fov:45},
+ ],update(){},dispose(){scene.userData.dispose();}};
+}
diff --git a/harness/examples/graphics_lab/serve.mjs b/harness/examples/graphics_lab/serve.mjs
new file mode 100644
index 00000000..a5b21cae
--- /dev/null
+++ b/harness/examples/graphics_lab/serve.mjs
@@ -0,0 +1,15 @@
+#!/usr/bin/env node
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {parseArgs} from 'node:util';
+import {createRequire} from 'node:module';
+const require = createRequire(import.meta.url);
+const {serveDirs} = require('../../runtime_js/serve.cjs');
+const here = path.dirname(fileURLToPath(import.meta.url));
+const {values} = parseArgs({options:{out:{type:'string', default:path.join(here,'output')}}});
+const root = path.resolve(values.out);
+if (!fs.existsSync(path.join(root,'index.html'))) throw new Error('Run build.py first');
+const server = await serveDirs({root, routes:{'/':{body:fs.readFileSync(path.join(root,'index.html'),'utf8')}}});
+console.log(`Graphics Lab: ${server.base}/`);
+for (const signal of ['SIGINT','SIGTERM']) process.on(signal, async()=>{await server.close();process.exit(0);});
diff --git a/harness/examples/graphics_lab/shaders/external_shader.frag b/harness/examples/graphics_lab/shaders/external_shader.frag
new file mode 100644
index 00000000..1de08c4e
--- /dev/null
+++ b/harness/examples/graphics_lab/shaders/external_shader.frag
@@ -0,0 +1,47 @@
+uniform float uTime;
+uniform float uRoughness;
+uniform float uFilmStrength;
+uniform vec3 uBaseReflectance;
+in vec3 alloyObjectPosition;
+in vec3 alloyViewPosition;
+in vec3 alloyViewNormal;
+out vec4 alloyOutput;
+
+void main() {
+ vec3 p = alloyObjectPosition;
+ vec3 n = normalize(alloyViewNormal);
+ vec3 v = normalize(-alloyViewPosition);
+ float forging = alloyNoise(p * 19.0) + 0.4 * alloyNoise(p * 47.0);
+ float brushPhase = p.y * 380.0 + sin(p.x * 4.0) * 5.0;
+ float brushFilter = exp(-0.8 * pow(fwidth(brushPhase), 2.0));
+ float height = forging * 0.0005 + sin(brushPhase) * brushFilter * 0.000035;
+
+ // Surface-gradient normal relief, with a finite grazing-angle fallback.
+ vec3 dx = dFdx(alloyViewPosition), dy = dFdy(alloyViewPosition);
+ vec3 r1 = cross(dy, n), r2 = cross(n, dx);
+ float determinant = dot(dx, r1);
+ if (abs(determinant) > 1e-10) {
+ vec3 gradient = (dFdx(height) * r1 + dFdy(height) * r2) / determinant;
+ n = normalize(n - gradient);
+ }
+ float roughness = clamp(uRoughness + (forging - 0.7) * 0.06, 0.16, 0.7);
+ float phase = p.y * 1.45 + p.x * 0.22 + 0.30 * sin(uTime * 0.55)
+ + pow(clamp(1.0 - dot(n, v), 0.0, 1.0), 1.5) * 1.8;
+ vec3 film = 0.47 + 0.30 * cos(phase * 3.2 + vec3(0.0, 2.0, 4.0));
+ vec3 f0 = mix(uBaseReflectance, film, uFilmStrength);
+ vec3 worldN = normalize(transpose(mat3(viewMatrix)) * n);
+ vec3 worldV = normalize(transpose(mat3(viewMatrix)) * v);
+ vec3 reflected = reflect(-worldV, worldN);
+ vec3 colour = alloyStudio(reflected, roughness) * alloyFresnel(f0, max(dot(n, v), 0.0));
+ colour += alloyGgx(n, v, normalize(mat3(viewMatrix) * vec3(-3, 4, 3)), f0,
+ roughness, vec3(1.6, 1.3, 0.95));
+ colour += alloyGgx(n, v, normalize(mat3(viewMatrix) * vec3(4, 2, -3)), f0,
+ roughness, vec3(0.45, 0.7, 1.3));
+ alloyOutput = vec4(colour, 1.0);
+ // These standard output chunks use the host's fixed tone/exposure policy.
+ // GLSL3 names the fragment output explicitly; no gl_FragColor alias is used.
+ #ifdef TONE_MAPPING
+ alloyOutput.rgb = toneMapping(alloyOutput.rgb);
+ #endif
+ alloyOutput = linearToOutputTexel(alloyOutput);
+}
diff --git a/harness/examples/graphics_lab/shaders/external_shader.vert b/harness/examples/graphics_lab/shaders/external_shader.vert
new file mode 100644
index 00000000..4a6d2b84
--- /dev/null
+++ b/harness/examples/graphics_lab/shaders/external_shader.vert
@@ -0,0 +1,13 @@
+// ShaderMaterial supplies position/normal and the camera/object matrices.
+// glslVersion: THREE.GLSL3 owns the version directive.
+out vec3 alloyObjectPosition;
+out vec3 alloyViewPosition;
+out vec3 alloyViewNormal;
+
+void main() {
+ vec4 viewPosition = modelViewMatrix * vec4(position, 1.0);
+ alloyObjectPosition = position;
+ alloyViewPosition = viewPosition.xyz;
+ alloyViewNormal = normalize(normalMatrix * normal);
+ gl_Position = projectionMatrix * viewPosition;
+}
diff --git a/harness/examples/graphics_lab/shaders/external_shader_common.glsl b/harness/examples/graphics_lab/shaders/external_shader_common.glsl
new file mode 100644
index 00000000..923e05d3
--- /dev/null
+++ b/harness/examples/graphics_lab/shaders/external_shader_common.glsl
@@ -0,0 +1,62 @@
+// Reusable source fragment, explicitly joined before external_shader.frag.
+// A compact direct GGX lobe and authored studio environment. The colour phase
+// is an artistic thin-film accent, not a multilayer optical solver.
+const float ALLOY_PI = 3.141592653589793;
+
+float alloyHash(vec3 p) {
+ p = fract(p * 0.1031);
+ p += dot(p, p.yzx + 33.33);
+ return fract((p.x + p.y) * p.z);
+}
+
+float alloyNoise(vec3 p) {
+ vec3 i = floor(p), f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(mix(alloyHash(i), alloyHash(i + vec3(1, 0, 0)), f.x),
+ mix(alloyHash(i + vec3(0, 1, 0)), alloyHash(i + vec3(1, 1, 0)), f.x), f.y),
+ mix(mix(alloyHash(i + vec3(0, 0, 1)), alloyHash(i + vec3(1, 0, 1)), f.x),
+ mix(alloyHash(i + vec3(0, 1, 1)), alloyHash(i + vec3(1)), f.x), f.y), f.z);
+}
+
+vec3 alloyFresnel(vec3 f0, float cosine) {
+ float x = clamp(1.0 - cosine, 0.0, 1.0);
+ float x2 = x * x;
+ return f0 + (1.0 - f0) * x2 * x2 * x;
+}
+
+vec3 alloyGgx(vec3 n, vec3 v, vec3 l, vec3 f0, float roughness, vec3 radiance) {
+ vec3 halfVector = v + l;
+ vec3 h = halfVector / max(length(halfVector), 0.0001);
+ float nv = max(dot(n, v), 0.0001), nl = max(dot(n, l), 0.0);
+ float nh = max(dot(n, h), 0.0), vh = max(dot(v, h), 0.0);
+ float alpha = roughness * roughness, a2 = alpha * alpha;
+ float denominator = nh * nh * (a2 - 1.0) + 1.0;
+ float distribution = a2 / max(ALLOY_PI * denominator * denominator, 0.00001);
+ float visibility = 0.5 / max(nl * sqrt(nv * nv * (1.0 - a2) + a2)
+ + nv * sqrt(nl * nl * (1.0 - a2) + a2), 0.0001);
+ return radiance * nl * distribution * visibility * alloyFresnel(f0, vh);
+}
+
+float alloySoftbox(vec3 r, vec3 center, vec3 across, vec2 halfSize, float blur) {
+ vec3 axis = normalize(center);
+ vec3 right = normalize(cross(axis, across));
+ vec3 up = cross(right, axis);
+ float facing = dot(r, axis);
+ vec2 uv = vec2(dot(r, right), dot(r, up)) / max(facing, 0.001);
+ vec2 edge = abs(uv) - halfSize;
+ float border = max(edge.x, edge.y);
+ return (1.0 - smoothstep(-blur, blur, border)) * smoothstep(0.0, 0.2, facing);
+}
+
+vec3 alloyStudio(vec3 r, float roughness) {
+ vec3 colour = mix(vec3(0.11, 0.12, 0.14), vec3(0.34, 0.39, 0.46),
+ smoothstep(-0.2, 0.8, r.y));
+ float blur = 0.065 + roughness * roughness * 1.2;
+ colour += vec3(2.8, 2.4, 1.9) * alloySoftbox(r, vec3(-3, 4, 3),
+ vec3(0, 1, 0), vec2(0.22, 0.78), blur);
+ colour += vec3(1.0, 1.55, 2.4) * alloySoftbox(r, vec3(4, 2, -3),
+ vec3(0, 1, 0), vec2(0.12, 0.9), blur);
+ colour += vec3(0.9) * alloySoftbox(r, vec3(0, 5, -1),
+ vec3(1, 0, 0), vec2(0.8, 0.14), blur);
+ return colour;
+}
diff --git a/harness/examples/graphics_lab/verify_media.py b/harness/examples/graphics_lab/verify_media.py
new file mode 100644
index 00000000..0aac340d
--- /dev/null
+++ b/harness/examples/graphics_lab/verify_media.py
@@ -0,0 +1,200 @@
+"""Decode every gallery film and check its retained scene/source correspondence.
+
+From harness/: python examples/graphics_lab/verify_media.py --out /path/to/gallery
+Motion statistics describe decoded pixels; they are not an aesthetic score.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+from pathlib import Path
+
+import imageio_ffmpeg
+import numpy as np
+from PIL import Image, ImageDraw
+
+
+def sha256(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def verify(out: Path, *, allow_legacy: bool = False) -> dict:
+ manifest = json.loads((out / "manifest.json").read_text())
+ libraries = manifest["library_sha256"]
+ actual = {p.name: sha256(p) for p in (out / "src/lib").glob("*.js")}
+ if actual != libraries:
+ raise ValueError("Published library does not match the source manifest")
+ shaders = manifest.get("shader_sha256", {})
+ shader_root = out / "src/shaders"
+ actual = {p.relative_to(shader_root).as_posix(): sha256(p)
+ for p in shader_root.rglob("*")
+ if p.is_file() and p.suffix in {".glsl", ".vert", ".frag"}}
+ if actual != shaders:
+ raise ValueError("Published shaders do not match the source manifest")
+ expected_sources = {}
+ for case in manifest["cases"]:
+ key = case["id"]
+ scene = out / "src/scenes" / f"{key}.js"
+ if sha256(scene) != case["scene_sha256"]:
+ raise ValueError(f"Published scene does not match its manifest: {key}")
+ workspace = out / "cases" / key / "src"
+ wanted = {f"lib/{name}": value for name, value in libraries.items()}
+ wanted.update({f"shaders/{name}": value for name, value in shaders.items()})
+ wanted[f"scenes/{key}.js"] = case["scene_sha256"]
+ wanted["scene.js"] = hashlib.sha256(
+ f"export {{createScene}} from './scenes/{key}.js';\n".encode()).hexdigest()
+ actual = {p.relative_to(workspace).as_posix(): sha256(p)
+ for p in workspace.rglob("*")
+ if p.is_file() and p.suffix in {".js", ".mjs", ".glsl", ".vert", ".frag"}}
+ if actual != wanted:
+ raise ValueError(f"Staged workspace does not match published source: {key}")
+ expected_sources[key] = wanted
+ if not (out / f"{key}.mp4").is_file():
+ raise ValueError(f"Missing gallery film: {key}")
+
+ plan_file = out / "capture-plan.json"
+ planned = {}
+ if plan_file.is_file():
+ entries = json.loads(plan_file.read_text())["films"]
+ planned = {item["file"]: item for item in entries}
+ if len(planned) != len(entries) or set(planned) != {p.name for p in out.glob("*.mp4")}:
+ raise ValueError("Movie files do not match the complete capture plan")
+ evidence = out / "media-verification"
+ evidence.mkdir(exist_ok=True)
+ reports = []
+ for film in sorted(out.glob("*.mp4")):
+ capture = json.loads(film.with_suffix(".capture.json").read_text())
+ owners = [key for key, source in expected_sources.items()
+ if capture.get("source_sha256") == source]
+ if len(owners) != 1:
+ raise ValueError(f"Film has no unique matching source snapshot: {film.name}")
+ if not capture.get("ok") or capture.get("console_errors") or capture.get("shader_errors"):
+ raise ValueError(f"Capture reported errors: {film.name}")
+ key = owners[0]
+ if film.stem in expected_sources and key != film.stem:
+ raise ValueError(f"Primary gallery film belongs to another scene: {film.name}: {key}")
+ if film.name in planned:
+ wanted = planned[film.name]
+ if key != wanted["scene"] or any(capture[field] != wanted[field]
+ for field in ["camera", "fps", "frames"]):
+ raise ValueError(f"Capture differs from its declared plan: {film.name}")
+ video_hash = sha256(film)
+ references = capture.get("reference_frames", [])
+ legacy = not capture.get("video_sha256") or not references
+ if legacy and not allow_legacy:
+ raise ValueError(f"Capture lacks encoded-file/anchor evidence: {film.name}; "
+ "use --allow-legacy only for historical movies")
+ if capture.get("video_sha256") and capture["video_sha256"] != video_hash:
+ raise ValueError(f"Encoded movie differs from its capture digest: {film.name}")
+ anchors = {}
+ for reference in references:
+ file = (out / reference["path"]).resolve()
+ if not file.is_relative_to(out) or sha256(file) != reference["sha256"]:
+ raise ValueError(f"Invalid retained input frame: {film.name}")
+ index = reference["index"]
+ if (not isinstance(index, int) or index < 0 or index >= capture["frames"]
+ or index in anchors or abs(reference["time_s"] - index / capture["fps"]) > 1e-8):
+ raise ValueError(f"Invalid retained frame index/time: {film.name}")
+ anchors[index] = Image.open(file).convert("RGB")
+ if not legacy and set(anchors) != {0, capture["frames"] // 3, 2 * capture["frames"] // 3}:
+ raise ValueError(f"Capture reference frames are incomplete: {film.name}")
+ first_input = (np.asarray(anchors[0].resize((160, 90)), dtype=np.float32)
+ if 0 in anchors else None)
+ views = json.loads((out / "renders" / key / "views.json").read_text())
+ stills = [view for view in views
+ if view["name"] == capture["camera"] and view["time_s"] == 0]
+ if len(stills) != 1:
+ raise ValueError(f"Film has no matching time-zero camera still: {film.name}")
+ still = Image.open(out / "renders" / key / stills[0]["path"]).convert("RGB")
+ frames = imageio_ffmpeg.read_frames(str(film), pix_fmt="rgb24")
+ metadata = next(frames)
+ width, height = metadata["size"]
+ if (width, height) != (capture["width"], capture["height"]):
+ raise ValueError(f"Encoded dimensions differ from capture: {film.name}")
+ if abs(metadata["fps"] - capture["fps"]) > .01:
+ raise ValueError(f"Encoded frame rate differs from capture: {film.name}")
+ selected = {0, capture["frames"] // 3, 2 * capture["frames"] // 3}
+ tiles, previous, motion, first_error, count = [], None, [], None, 0
+ anchor_errors = {}
+ motion_matches = {}
+ try:
+ for count, raw in enumerate(frames, 1):
+ pixels = np.frombuffer(raw, dtype=np.uint8).reshape(height, width, 3)
+ if count == 1:
+ if still.size != (width, height):
+ raise ValueError(f"Matching still has different dimensions: {film.name}")
+ first_error = float(np.abs(pixels.astype(np.float32)
+ - np.asarray(still, dtype=np.float32)).mean())
+ if first_error > 6:
+ raise ValueError(f"First decoded frame differs from its scene still: "
+ f"{film.name}: {first_error:.3f}/255")
+ image = Image.fromarray(pixels)
+ small = np.asarray(image.resize((160, 90)), dtype=np.float32)
+ if count - 1 in anchors:
+ anchor = anchors[count - 1]
+ if anchor.size != (width, height):
+ raise ValueError(f"Retained frame dimensions differ: {film.name}")
+ intended = np.asarray(anchor.resize((160, 90)), dtype=np.float32)
+ error = float(np.abs(small - intended).mean())
+ # Downsampling removes fine chroma-subsampling differences,
+ # while retaining the scene's changing forms and lighting.
+ if error > 1.5:
+ raise ValueError(f"Encoded frame {count - 1} differs from its input: "
+ f"{film.name}: {error:.3f}/255")
+ anchor_errors[count - 1] = error
+ moving = np.max(np.abs(intended - first_input), axis=2) > 4
+ if count > 1 and int(moving.sum()) >= 16:
+ own_error = float(np.abs(small[moving] - intended[moving]).mean())
+ frozen_error = float(np.abs(small[moving] - first_input[moving]).mean())
+ if own_error + .1 >= frozen_error:
+ raise ValueError(f"Encoded frame does not follow captured motion: "
+ f"{film.name}: frame {count - 1}")
+ motion_matches[count - 1] = {"changed_pixels": int(moving.sum()),
+ "intended_frame_error": own_error,
+ "first_frame_error": frozen_error}
+ if previous is not None:
+ motion.append(float(np.abs(small - previous).mean()))
+ previous = small
+ if count - 1 in selected:
+ tiles.append((image.resize((640, 360)), (count - 1) / capture["fps"]))
+ finally:
+ frames.close()
+ if count != capture["frames"]:
+ raise ValueError(f"Decoded frame count differs: {film.name}: "
+ f"{count} versus {capture['frames']}")
+ sheet = Image.new("RGB", (640 * len(tiles), 396), (18, 23, 27))
+ draw = ImageDraw.Draw(sheet)
+ for i, (tile, time) in enumerate(tiles):
+ sheet.paste(tile, (640 * i, 36))
+ draw.text((640 * i + 12, 12), f"{film.stem} / {capture['camera']} / {time:.2f}s",
+ fill="white")
+ sheet.save(evidence / f"{film.stem}.jpg", quality=94)
+ reports.append({"film": film.name, "scene": key, "camera": capture["camera"],
+ "sha256": video_hash, "frames_decoded": count,
+ "capture_binding": "legacy_source_only" if legacy else "encoded_digest_and_input_frames",
+ "input_frame_rgb_mae_255_at_160x90": anchor_errors,
+ "motion_correspondence_at_160x90": motion_matches,
+ "fps": metadata["fps"], "size": [width, height],
+ "first_frame_rgb_mae_255": first_error,
+ "adjacent_frame_mean_rgb_mae_255_at_160x90": float(np.mean(motion))
+ if motion else 0, "source_files_checked": len(expected_sources[key])})
+ print(f"Verified {film.name}: {count} frames, source {key}, "
+ f"first-frame error {first_error:.3f}/255", flush=True)
+ report = {"ok": True, "manifest_sha256": sha256(out / "manifest.json"),
+ "library_modules": len(libraries), "external_shader_files": len(shaders),
+ "gallery_cases": len(expected_sources),
+ "films": reports,
+ "limitations": "Pixel motion includes compression and rendering changes. Static "
+ "studies may have zero motion; these statistics do not certify visual realism."}
+ (evidence / "report.json").write_text(json.dumps(report, indent=2) + "\n")
+ return report
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--out", type=Path, required=True)
+ parser.add_argument("--allow-legacy", action="store_true",
+ help="Allow historical sidecars without encoded-file digests or retained input frames")
+ args = parser.parse_args()
+ verify(args.out.resolve(), allow_legacy=args.allow_legacy)
diff --git a/harness/examples/graphics_lab/viewer.css b/harness/examples/graphics_lab/viewer.css
new file mode 100644
index 00000000..75ef23fb
--- /dev/null
+++ b/harness/examples/graphics_lab/viewer.css
@@ -0,0 +1 @@
+:root{color-scheme:dark;--bg:#10120f;--panel:#1a1d18;--ink:#eef0e4;--dim:#989e91;--line:#353b30;--accent:#d7e9a2}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.6 system-ui,sans-serif}header,footer{display:flex;justify-content:space-between;align-items:center;margin:0 5vw;padding:28px 0;border-bottom:1px solid var(--line);font-size:11px;letter-spacing:1.4px}.brand{font-weight:650;text-decoration:none;color:var(--ink)}.brand span{color:var(--dim);margin-left:10px}.edition{color:var(--dim)}main{max-width:1500px;margin:auto;padding:0 5vw 80px}.intro{padding:65px 0 48px;max-width:690px}.eyebrow{color:var(--accent);font-size:10px;letter-spacing:2px;font-weight:600}h1{font-size:clamp(32px,5vw,58px);letter-spacing:-2px;font-weight:450;margin:16px 0}h2{font-size:34px;font-weight:450;margin:2px 0}.intro>p:last-child,#subtitle,#hint{color:var(--dim);font-size:14px}.intro>p:last-child{max-width:560px}#gallery{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:36px 24px}.card{border:0;padding:0;background:none;text-align:left;color:var(--ink);cursor:pointer}.thumbnail{position:relative;aspect-ratio:16/9;background:var(--panel);overflow:hidden;border-radius:3px}.thumbnail img{width:100%;height:100%;object-fit:cover;transition:transform .45s}.card:hover img{transform:scale(1.035)}.play{position:absolute;right:18px;bottom:18px;border:1px solid #ffffff65;background:#1118;backdrop-filter:blur(6px);width:40px;height:40px;display:grid;place-items:center;border-radius:50%;font-size:13px}.caption{display:flex;gap:17px;padding:17px 0}.number{font:11px monospace;color:var(--dim);padding-top:5px}.caption h3{font-size:20px;font-weight:450;letter-spacing:-.3px;margin:0}.caption p{font-size:12px;margin:3px 0;color:var(--dim)}.stage-heading{display:flex;justify-content:space-between;align-items:center;margin:42px 0 24px}button,select{font:inherit}button.quiet{border:1px solid var(--line);background:none;color:var(--ink);padding:9px 14px;font-size:12px;cursor:pointer}#screen{position:relative;aspect-ratio:16/9;background:#060706;border:1px solid var(--line)}video,#live,canvas{width:100%;height:100%;display:block}#live[hidden],video[hidden],[hidden]{display:none!important}#status{position:absolute;top:45%;left:0;width:100%;text-align:center;pointer-events:none;color:var(--dim)}.toolbar{display:flex;align-items:center;gap:20px;flex-wrap:wrap;padding:18px 0;border-bottom:1px solid var(--line);font-size:12px}.tabs{display:flex;background:var(--panel);padding:4px}.tabs button,.live-controls button{border:0;background:transparent;color:var(--dim);padding:8px 14px;cursor:pointer}.tabs .active{background:var(--line);color:var(--ink)}.toolbar a{margin-left:auto;color:var(--dim);text-decoration:none}.live-controls{display:flex;gap:16px;align-items:center}.live-controls label{display:flex;gap:7px;align-items:center}select{max-width:130px;background:var(--panel);color:var(--ink);border:1px solid var(--line);padding:6px}input[type=range]{width:110px;accent-color:var(--accent)}output{font:11px monospace;color:var(--dim)}#hint{font-size:12px}footer{margin-top:10px;border-top:1px solid var(--line);border-bottom:0;color:var(--dim)}@media(max-width:750px){.edition{display:none}.intro{padding:40px 0 32px}#gallery{grid-template-columns:1fr;gap:24px}h2{font-size:25px}.live-controls{gap:8px;flex-wrap:wrap}.stage-heading{gap:15px}footer{font-size:9px;gap:20px}.toolbar{gap:12px}}
diff --git a/harness/examples/graphics_lab/viewer.js b/harness/examples/graphics_lab/viewer.js
new file mode 100644
index 00000000..57f64ede
--- /dev/null
+++ b/harness/examples/graphics_lab/viewer.js
@@ -0,0 +1,250 @@
+import * as THREE from 'three';
+import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
+import {GLTFLoader} from 'three/addons/loaders/GLTFLoader.js';
+import {makeRenderer} from '/__runtime/lib/browser/renderer.js';
+import {makePostChain} from '/__runtime/lib/browser/post.js';
+
+const $ = (selector) => document.querySelector(selector);
+const manifest = await (await fetch('./manifest.json')).json();
+let current, bundle, camera, controls;
+let running = false, time = 0, last = 0, bootSerial = 0;
+
+for (const item of manifest.cases) {
+ const card = document.createElement('button');
+ card.className = 'card';
+ const thumb = document.createElement('div');
+ thumb.className = 'thumbnail';
+ const img = document.createElement('img');
+ img.src = `./${item.id}.png`;
+ img.alt = item.subtitle;
+ const play = document.createElement('span');
+ play.className = 'play';
+ play.textContent = '▶';
+ thumb.append(img, play);
+ const caption = document.createElement('div');
+ caption.className = 'caption';
+ const num = document.createElement('span');
+ num.className = 'number';
+ num.textContent = item.number;
+ const copy = document.createElement('div');
+ const title = document.createElement('h3');
+ title.textContent = item.title;
+ const subtitle = document.createElement('p');
+ subtitle.textContent = item.subtitle;
+ copy.append(title, subtitle);
+ caption.append(num, copy);
+ card.append(thumb, caption);
+ card.onclick = () => open(item);
+ $('#gallery').append(card);
+}
+
+function disposeBundle(value) {
+ if (!value || value.disposed) return;
+ value.disposed = true;
+ const errors = [];
+ const attempt = operation => {
+ try { operation(); } catch (error) { errors.push(error); }
+ };
+ const result = value.result;
+ attempt(() => {
+ if (typeof result?.dispose === 'function') {
+ // An explicit scene disposer is authoritative about owned resources.
+ result.dispose();
+ } else if (result?.scene?.isObject3D) {
+ const unmanaged = new Set(), protectedResources = new Set(), owners = [];
+ const collect = (object, resources) => {
+ if (object.geometry) resources.add(object.geometry);
+ if (object.isInstancedMesh) resources.add(object);
+ for (const material of [].concat(object.material || [],
+ object.customDepthMaterial || [], object.customDistanceMaterial || [])) {
+ if (material) resources.add(material);
+ }
+ };
+ const visit = object => {
+ if (typeof object.userData?.dispose === 'function') {
+ // Do not cross an ownership boundary: it may contain borrowed assets
+ // or later caller attachments that its disposer deliberately leaves.
+ owners.push(() => object.userData.dispose());
+ object.traverse(child => collect(child, protectedResources));
+ } else {
+ collect(object, unmanaged);
+ object.children.forEach(visit);
+ }
+ };
+ visit(result.scene);
+ owners.forEach(attempt);
+ for (const resource of unmanaged) {
+ // A resource can also be referenced outside the subtree that owns it.
+ // Cached materials and all textures remain borrowed by this fallback.
+ if (!protectedResources.has(resource) && !resource.userData?.shared && !resource.userData?.astraShared) {
+ attempt(() => resource.dispose());
+ }
+ }
+ }
+ });
+ // The production post chain has no disposal API. Release its entire context.
+ // Each new scene gets a NEW canvas; a lost context cannot safely be reused.
+ attempt(() => value.renderer?.dispose());
+ attempt(() => value.renderer?.forceContextLoss());
+ attempt(() => value.canvas?.remove());
+ if (errors.length) console.warn('Scene cleanup failed', new AggregateError(errors, 'Scene cleanup failed'));
+}
+
+function release() {
+ running = false;
+ const previousControls = controls, previousBundle = bundle;
+ controls = null;
+ bundle = null;
+ try { previousControls?.dispose(); }
+ catch (error) { console.warn('Camera controls cleanup failed', error); }
+ disposeBundle(previousBundle);
+}
+
+function open(item) {
+ bootSerial++;
+ release();
+ current = item;
+ time = 0;
+ $('.intro').hidden = true;
+ $('#gallery').hidden = true;
+ $('#stage').hidden = false;
+ $('#title').textContent = item.title;
+ $('#subtitle').textContent = item.subtitle;
+ $('#category').textContent = `${item.number} / ${item.kind.toUpperCase()}`;
+ $('#still').href = `./${item.id}.png`;
+ $('#video').src = `./${item.id}.mp4`;
+ $('#video').poster = `./${item.id}.png`;
+ watch();
+ window.scrollTo({top: 0, behavior: 'smooth'});
+}
+
+function watch() {
+ bootSerial++; // Cancel a pending asynchronous live scene boot.
+ running = false;
+ $('#live').hidden = true;
+ $('#video').hidden = false;
+ $('.live-controls').hidden = true;
+ $('#watch').classList.add('active');
+ $('#explore').classList.remove('active');
+ $('#status').textContent = '';
+ $('#video').play().catch(() => {});
+}
+
+async function explore() {
+ $('#video').pause();
+ $('#video').hidden = true;
+ $('#live').hidden = false;
+ $('.live-controls').hidden = false;
+ $('#explore').classList.add('active');
+ $('#watch').classList.remove('active');
+ $('#pause').textContent = 'Pause';
+ if (bundle) { running = true; return; }
+ $('#status').textContent = 'Preparing scene…';
+ const serial = ++bootSerial;
+ const item = current;
+ let pending;
+ try {
+ const mod = await import(item.module);
+ if (serial !== bootSerial) return;
+ const width = Math.min(1600, Math.round($('#screen').clientWidth));
+ const height = Math.round(width * 9 / 16);
+ const canvas = document.createElement('canvas');
+ canvas.id = 'canvas';
+ const renderer = makeRenderer(canvas, width, height);
+ pending = {canvas, renderer};
+ const manager = new THREE.LoadingManager();
+ const loaders = {
+ gltf: new GLTFLoader(manager), texture: new THREE.TextureLoader(manager),
+ cube: new THREE.CubeTextureLoader(manager), manager,
+ };
+ pending.result = await mod.createScene({THREE, renderer, loaders});
+ if (serial !== bootSerial) { disposeBundle(pending); return; }
+ const {scene, cameras, update} = pending.result || {};
+ if (!scene?.isScene || !cameras?.length || typeof update !== 'function') {
+ throw new Error('Scene does not implement the scene contract');
+ }
+ pending.post = makePostChain(renderer, scene, {width, height});
+ bundle = pending;
+ $('#live').replaceChildren(canvas);
+ camera = new THREE.PerspectiveCamera(45, width / height, .04, 3000);
+ controls = new OrbitControls(camera, canvas);
+ controls.enableDamping = true;
+ $('#camera').replaceChildren();
+ cameras.forEach((spec, index) => {
+ const option = document.createElement('option');
+ option.value = index;
+ option.textContent = spec.name;
+ $('#camera').append(option);
+ });
+ setCamera(0);
+ update(time, 0);
+ pending.post.render(camera);
+ $('#status').textContent = '';
+ running = true;
+ } catch (error) {
+ disposeBundle(pending);
+ if (serial !== bootSerial) return;
+ release();
+ $('#status').textContent = `Scene could not load: ${error.message}`;
+ console.error(error);
+ }
+}
+
+function setCamera(index) {
+ const spec = bundle?.result.cameras[index];
+ if (!spec) return;
+ camera.position.fromArray(spec.position);
+ camera.fov = spec.fov ?? 45;
+ camera.updateProjectionMatrix();
+ controls.target.fromArray(spec.lookAt);
+ controls.update();
+}
+
+$('#watch').onclick = watch;
+$('#explore').onclick = explore;
+$('#camera').onchange = event => setCamera(Number(event.target.value));
+$('#pause').onclick = () => {
+ running = !running;
+ $('#pause').textContent = running ? 'Pause' : 'Resume';
+};
+$('#time').oninput = event => {
+ time = Number(event.target.value);
+ bundle?.result.update(time, 0);
+};
+$('#close').onclick = () => {
+ bootSerial++;
+ release();
+ $('#video').pause();
+ $('#video').removeAttribute('src');
+ $('#stage').hidden = true;
+ $('.intro').hidden = false;
+ $('#gallery').hidden = false;
+};
+$('#video').onerror = () => {
+ // A late film error must not overwrite a live scene's boot failure.
+ if (!$('#video').hidden) $('#status').textContent = 'Choose “Explore live” to view this scene.';
+};
+
+function frame(now) {
+ requestAnimationFrame(frame);
+ const dt = Math.min((now - last) / 1000, .05);
+ last = now;
+ if (!bundle || $('#live').hidden) return;
+ if (running) {
+ time += dt;
+ bundle.result.update(time, dt);
+ }
+ controls.update();
+ bundle.post.refreshGrade();
+ bundle.post.render(camera);
+ $('#time').value = Math.min(time, 20);
+ $('#seconds').textContent = `${time.toFixed(2)} s`;
+}
+requestAnimationFrame(frame);
+
+// Diagnostics used by the browser smoke test.
+window.graphicsLab = {
+ open, explore,
+ get active() { return bundle?.result; },
+ get time() { return time; },
+};
diff --git a/harness/tests/graphics/test_graphics_lab_build.py b/harness/tests/graphics/test_graphics_lab_build.py
new file mode 100644
index 00000000..ea71715e
--- /dev/null
+++ b/harness/tests/graphics/test_graphics_lab_build.py
@@ -0,0 +1,146 @@
+"""A gallery restage must never relabel old media with different source code."""
+from __future__ import annotations
+
+import importlib.util
+import json
+from pathlib import Path
+
+import pytest
+
+BUILDER = Path(__file__).resolve().parents[2] / "examples/graphics_lab/build.py"
+spec = importlib.util.spec_from_file_location("graphics_lab_builder", BUILDER)
+build = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(build)
+
+
+def studio(tmp_path: Path, monkeypatch):
+ source, library, out = tmp_path / "studio", tmp_path / "lib", tmp_path / "out"
+ (source / "scenes").mkdir(parents=True)
+ library.mkdir()
+ (library / "shader.js").write_text("export const version = 1;\n")
+ for key in ("one", "two"):
+ (source / "scenes" / f"{key}.js").write_text(f"export const scene = '{key}';\n")
+ for name in ("index.html", "viewer.js", "viewer.css"):
+ (source / name).write_text("<!--COMPARISON_LINK-->" if name == "index.html" else "")
+ monkeypatch.setattr(build, "HERE", source)
+ monkeypatch.setattr(build, "LIB", library)
+ monkeypatch.setattr(build, "CASES", tuple((key, str(i), key, "Study", "life")
+ for i, key in enumerate(("one", "two"), 1)))
+ return source, library, out
+
+
+def file_snapshot(root: Path) -> dict[str, bytes]:
+ return {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()}
+
+
[email protected]("capture_hashes", [False, True])
+def test_unchanged_selected_rebuild_preserves_other_media(studio, capture_hashes):
+ _, _, out = studio
+ cases = build.stage(out, [])
+ (out / "two.mp4").write_bytes(b"previous film")
+ record = {"ok": True}
+ if capture_hashes:
+ manifest = json.loads((out / "manifest.json").read_text())
+ record["source_sha256"] = build.workspace_hashes(cases[1], manifest["library_sha256"])
+ (out / "two.capture.json").write_text(json.dumps(record))
+ before = file_snapshot(out)
+ selected = build.stage(out, ["one"])
+ assert [case["id"] for case in selected] == ["one"]
+ assert file_snapshot(out) == before
+
+
[email protected]("change", ["library", "unselected_scene"])
+def test_changed_sources_refuse_before_mutating_old_media(studio, change):
+ source, library, out = studio
+ build.stage(out, [])
+ (out / "two.mp4").write_bytes(b"previous film")
+ target = library / "shader.js" if change == "library" else source / "scenes/two.js"
+ target.write_text("export const changed = true;\n")
+ before = file_snapshot(out)
+ with pytest.raises(ValueError, match="new --out"):
+ build.stage(out, ["one"])
+ assert file_snapshot(out) == before
+
+
+def test_capture_hashes_catch_an_already_mislabelled_video(studio):
+ _, library, out = studio
+ cases = build.stage(out, [])
+ old_manifest = json.loads((out / "manifest.json").read_text())
+ captured = build.workspace_hashes(cases[1], old_manifest["library_sha256"])
+ # Simulate the former unsafe builder: newer source/manifest with an old film.
+ (library / "shader.js").write_text("export const version = 2;\n")
+ build.stage(out, [])
+ (out / "two.mp4").write_bytes(b"older film")
+ (out / "two.capture.json").write_text(json.dumps({"ok": True, "source_sha256": captured}))
+ before = file_snapshot(out)
+ with pytest.raises(ValueError, match="capture-time sources"):
+ build.stage(out, ["one"])
+ assert file_snapshot(out) == before
+
+
+def test_missing_case_fails_without_partial_output(studio):
+ source, _, out = studio
+ (source / "scenes/two.js").unlink()
+ with pytest.raises(FileNotFoundError, match="Showcase scene missing"):
+ build.stage(out, ["one"])
+ assert not out.exists()
+
+
+def test_unversioned_media_cannot_acquire_new_source_labels(studio):
+ _, _, out = studio
+ out.mkdir()
+ (out / "one.png").write_bytes(b"unknown old still")
+ before = file_snapshot(out)
+ with pytest.raises(ValueError, match="no source manifest"):
+ build.stage(out, [])
+ assert file_snapshot(out) == before
+
+
+def test_source_only_refresh_removes_obsolete_modules(studio):
+ _, library, out = studio
+ (library / "obsolete.js").write_text("export const old = true;\n")
+ build.stage(out, [])
+ (library / "obsolete.js").unlink()
+ (library / "new.js").write_text("export const current = true;\n")
+ build.stage(out, [])
+ assert not list(out.rglob("obsolete.js"))
+ assert len(list(out.rglob("new.js"))) == 3
+
+
[email protected]("suffix", [".glsl", ".vert", ".frag"])
+def test_external_shader_bytes_are_staged_and_guarded(studio, suffix):
+ source, _, out = studio
+ shader = source / "shaders/nested" / f"surface{suffix}"
+ shader.parent.mkdir(parents=True)
+ shader.write_text("// Independent shader source\nvoid main() {}\n")
+ cases = build.stage(out, [])
+ manifest = json.loads((out / "manifest.json").read_text())
+ shader_key = f"nested/surface{suffix}"
+ assert manifest["shader_sha256"] == {shader_key: build.digest(shader.read_bytes())}
+ for root in [out / "src", out / "cases/one/src", out / "cases/two/src"]:
+ assert (root / "shaders" / shader_key).read_bytes() == shader.read_bytes()
+ captured = build.workspace_hashes(cases[1], manifest["library_sha256"], manifest["shader_sha256"])
+ (out / "two.mp4").write_bytes(b"previous film")
+ (out / "two.capture.json").write_text(json.dumps({"ok": True, "source_sha256": captured}))
+ before = file_snapshot(out)
+ build.stage(out, ["one"])
+ assert file_snapshot(out) == before
+ shader.write_text("// Changed optical response\nvoid main() {}\n")
+ with pytest.raises(ValueError, match="external shader contents changed"):
+ build.stage(out, ["one"])
+ assert file_snapshot(out) == before
+
+
[email protected]("where", ["src", "cases/two/src"])
+def test_corrupted_published_or_staged_shader_refuses_restage(studio, where):
+ source, _, out = studio
+ (source / "shaders").mkdir()
+ (source / "shaders/surface.frag").write_text("void main() {}\n")
+ build.stage(out, [])
+ (out / "two.mp4").write_bytes(b"previous film")
+ (out / where / "shaders/surface.frag").write_text("// Unrecorded shader change\n")
+ before = file_snapshot(out)
+ with pytest.raises(ValueError, match="disagree"):
+ build.stage(out, ["one"])
+ assert file_snapshot(out) == before
diff --git a/harness/tests/graphics/test_graphics_lab_lifecycle.py b/harness/tests/graphics/test_graphics_lab_lifecycle.py
new file mode 100644
index 00000000..87ae259c
--- /dev/null
+++ b/harness/tests/graphics/test_graphics_lab_lifecycle.py
@@ -0,0 +1,139 @@
+"""The live viewer respects effect ownership and releases failed scene contexts."""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from tests.scene_runtime.conftest import needs_browser, run_node_json
+
+pytestmark = [pytest.mark.node, needs_browser]
+LAB = Path(__file__).resolve().parents[2] / "examples/graphics_lab"
+
+FIXTURE = """
+import * as THREE from 'three';
+export async function makeScene(kind,{renderer}) {
+ const stats=window.cleanupStats={};
+ const count=key=>stats[key]=(stats[key]||0)+1;
+ const track=(resource,key)=>{resource.addEventListener('dispose',()=>count(key));return resource;};
+ const originalDispose=renderer.dispose.bind(renderer);
+ renderer.dispose=()=>{count('renderer');originalDispose();if(kind==='throwing')throw Error('Renderer cleanup failure');};
+ const originalLoss=renderer.forceContextLoss.bind(renderer);
+ renderer.forceContextLoss=()=>{count('context');originalLoss();};
+ const canvas=renderer.domElement,originalRemove=canvas.remove.bind(canvas);
+ canvas.remove=()=>{count('canvas');originalRemove();};
+ const scene=new THREE.Scene();
+ const geometry=track(new THREE.BoxGeometry(),'geometry');
+ const material=track(new THREE.MeshBasicMaterial({color:0x558899}),'material');
+ const mesh=new THREE.Mesh(geometry,material);scene.add(mesh);
+ const result={scene,cameras:[{name:'Study',position:[2,2,4],lookAt:[0,0,0]}],update(){}};
+ if(kind==='authoritative') {
+ mesh.userData.dispose=()=>count('childDisposer');
+ const borrowed=track(new THREE.BoxGeometry(),'borrowedGeometry');
+ mesh.add(new THREE.Mesh(borrowed,track(new THREE.MeshBasicMaterial(),'borrowedMaterial')));
+ result.dispose=()=>{count('sceneDisposer');geometry.dispose();material.dispose();};
+ } else if(kind.startsWith('fallback')) {
+ const owner=new THREE.Group();scene.add(owner);owner.add(mesh);
+ owner.userData.dispose=()=>{count('ownerDisposer');geometry.dispose();material.dispose();
+ if(kind==='fallback_failure')throw Error('Effect cleanup failure');};
+ mesh.userData.dispose=()=>count('nestedDisposer');
+ mesh.add(new THREE.Mesh(track(new THREE.BoxGeometry(),'borrowedGeometry'),
+ track(new THREE.MeshBasicMaterial(),'borrowedMaterial')));
+ // A managed resource also used by an unmanaged sibling must not be freed twice.
+ scene.add(new THREE.Mesh(geometry,material));
+ const looseGeometry=track(new THREE.BoxGeometry(),'looseGeometry');
+ const looseMaterial=track(new THREE.MeshBasicMaterial(),'looseMaterial');
+ const texture=track(new THREE.DataTexture(new Uint8Array([255,255,255,255]),1,1),'texture');texture.needsUpdate=true;
+ looseMaterial.map=texture;
+ const loose=new THREE.InstancedMesh(looseGeometry,looseMaterial,1);track(loose,'instances');
+ loose.customDepthMaterial=track(new THREE.MeshDepthMaterial(),'depthMaterial');
+ loose.customDistanceMaterial=track(new THREE.MeshDistanceMaterial(),'distanceMaterial');scene.add(loose);
+ scene.add(new THREE.Mesh(looseGeometry,looseMaterial));
+ const cached=track(new THREE.MeshBasicMaterial(),'cachedMaterial');cached.userData.shared=true;
+ scene.add(new THREE.Mesh(looseGeometry,cached));
+ } else if(kind==='throwing'||kind==='invalid') {
+ result.dispose=()=>{count('sceneDisposer');throw Error('Owned cleanup failure');};
+ if(kind==='invalid')result.scene=null;
+ } else if(kind==='cancelled') {
+ result.dispose=()=>{count('sceneDisposer');geometry.dispose();material.dispose();};
+ await new Promise(resolve=>{window.resolveScene=resolve;});
+ }
+ return result;
+}
+"""
+
+
+def test_live_cleanup_ownership_failures_and_pending_cancellation(tmp_path: Path):
+ for name in ("index.html", "viewer.js", "viewer.css"):
+ (tmp_path / name).write_bytes((LAB / name).read_bytes())
+ cases = []
+ for kind in ("authoritative", "fallback", "fallback_failure", "throwing", "invalid", "cancelled"):
+ (tmp_path / f"{kind}.js").write_text(
+ "import {makeScene} from './fixture.js';\n"
+ f"export const createScene=options=>makeScene('{kind}',options);\n"
+ )
+ cases.append({"id": kind, "title": kind, "subtitle": "Cleanup study",
+ "kind": "test", "number": "01", "module": f"./{kind}.js"})
+ (tmp_path / "fixture.js").write_text(FIXTURE)
+ (tmp_path / "manifest.json").write_text(json.dumps({"cases": cases}))
+ result = run_node_json("""
+import fs from 'node:fs';
+import assert from 'node:assert/strict';
+import {launchBrowser,serveDirs} from './lib/host_env.mjs';
+import {releaseBrowser} from './lib/host_page.mjs';
+const root=ROOT;
+const server=await serveDirs({root,routes:{'/':{body:fs.readFileSync(root+'/index.html','utf8')}}});
+const launched=await launchBrowser({gpu:'auto'});
+let page;
+try {
+ page=await launched.browser.newPage();
+ const errors=[],warnings=[];
+ page.on('pageerror',e=>errors.push(e.message));
+ page.on('console',m=>{if(m.type()==='warn'&&m.text().includes('cleanup failed'))warnings.push(m.text());});
+ await page.goto(server.base,{waitUntil:'networkidle0'});
+ await page.waitForFunction(()=>!!window.graphicsLab);
+ const snapshots={};
+ for(const kind of ['authoritative','fallback','fallback_failure','throwing','invalid','cancelled']) {
+ await page.evaluate(async kind=>{
+ const item=(await (await fetch('./manifest.json')).json()).cases.find(item=>item.id===kind);
+ window.graphicsLab.open(item);
+ window.pendingBoot=window.graphicsLab.explore();
+ },kind);
+ if(kind==='cancelled') {
+ await page.waitForFunction(()=>typeof window.resolveScene==='function');
+ await page.click('#close');
+ await page.evaluate(async()=>{window.resolveScene();await window.pendingBoot;});
+ } else {
+ await page.evaluate(()=>window.pendingBoot);
+ if(kind==='invalid') {
+ await page.$eval('#video',e=>e.dispatchEvent(new Event('error')));
+ assert.match(await page.$eval('#status',e=>e.textContent),/Scene does not implement the scene contract/);
+ }
+ else assert(await page.evaluate(()=>!!window.graphicsLab.active),kind+' did not boot');
+ await page.click('#close');
+ }
+ snapshots[kind]=await page.evaluate(()=>({...window.cleanupStats,active:!!window.graphicsLab.active,canvasCount:document.querySelectorAll('#live canvas').length}));
+ }
+ assert.deepEqual(errors,[]);
+ for(const stats of Object.values(snapshots)) {
+ assert.equal(stats.renderer,1);assert.equal(stats.context,1);assert.equal(stats.canvas,1);
+ assert.equal(stats.active,false);assert.equal(stats.canvasCount,0);
+ }
+ const a=snapshots.authoritative;
+ assert.equal(a.sceneDisposer,1);assert.equal(a.geometry,1);assert.equal(a.material,1);
+ assert.equal(a.childDisposer,undefined);assert.equal(a.borrowedGeometry,undefined);assert.equal(a.borrowedMaterial,undefined);
+ for(const f of [snapshots.fallback,snapshots.fallback_failure]) {
+ for(const key of ['ownerDisposer','geometry','material','looseGeometry','looseMaterial','instances','depthMaterial','distanceMaterial'])assert.equal(f[key],1,key);
+ for(const key of ['nestedDisposer','borrowedGeometry','borrowedMaterial','cachedMaterial','texture'])assert.equal(f[key],undefined,key);
+ }
+ assert.equal(snapshots.throwing.sceneDisposer,1);assert.equal(snapshots.invalid.sceneDisposer,1);
+ assert.equal(snapshots.cancelled.sceneDisposer,1);
+ assert.equal(warnings.length,3);
+ console.log(JSON.stringify({snapshots,warnings:warnings.length,errors}));
+} finally {
+ await page?.close();await releaseBrowser(launched);await server.close();
+}
+""".replace("ROOT", json.dumps(str(tmp_path))), timeout=120)
+ assert len(result["snapshots"]) == 6
+ assert result["errors"] == []
diff --git a/harness/tests/graphics/test_graphics_lab_media.py b/harness/tests/graphics/test_graphics_lab_media.py
new file mode 100644
index 00000000..96f99da2
--- /dev/null
+++ b/harness/tests/graphics/test_graphics_lab_media.py
@@ -0,0 +1,180 @@
+"""Check that exported media retains its source, camera and animation evidence."""
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import shutil
+from pathlib import Path
+
+import numpy as np
+import pytest
+from PIL import Image
+
+ffmpeg = pytest.importorskip("imageio_ffmpeg")
+HERE = Path(__file__).resolve().parents[2] / "examples/graphics_lab"
+
+
+def load_module(name):
+ spec = importlib.util.spec_from_file_location(f"graphics_lab_{name}", HERE / f"{name}.py")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+build, verify, package = [load_module(name) for name in ["build", "verify_media", "package"]]
+
+
+def write_json(path, value):
+ path.write_text(json.dumps(value))
+
+
+def encode(path, frames):
+ writer = ffmpeg.write_frames(str(path), (96, 64), fps=3, codec="libx264",
+ output_params=["-crf", "18"], macro_block_size=1)
+ writer.send(None)
+ try:
+ for frame in frames:
+ writer.send(frame)
+ finally:
+ writer.close()
+
+
+def gallery(tmp_path, monkeypatch):
+ source, library, out = tmp_path / "source", tmp_path / "lib", tmp_path / "out"
+ (source / "scenes").mkdir(parents=True)
+ (source / "shaders").mkdir()
+ library.mkdir()
+ (library / "shader.js").write_text("export const scale = 1;\n")
+ (source / "scenes/smoke.js").write_text("export const kind = 'smoke';\n")
+ for suffix in ["glsl", "vert", "frag"]:
+ (source / "shaders" / f"surface.{suffix}").write_text("void main() {}\n")
+ for name in ["index.html", "viewer.js", "viewer.css"]:
+ (source / name).write_text("")
+ monkeypatch.setattr(build, "HERE", source)
+ monkeypatch.setattr(build, "LIB", library)
+ monkeypatch.setattr(build, "CASES", (("smoke", "01", "Smoke", "Study", "air"),))
+ case = build.stage(out, [])[0]
+ manifest = json.loads((out / "manifest.json").read_text())
+ frames, references = [], []
+ (out / "capture_frames/smoke").mkdir(parents=True)
+ for index in range(9):
+ pixels = np.full((64, 96, 3), [25, 30, 35], dtype=np.uint8)
+ x = 8 + index * 6
+ pixels[21:38, x:x+17] = [190, 110, 55]
+ frames.append(pixels)
+ if index in [0, 3, 6]:
+ file = out / "capture_frames/smoke" / f"frame_{index}.png"
+ Image.fromarray(pixels).save(file)
+ references.append({"index": index, "time_s": index / 3,
+ "path": file.relative_to(out).as_posix(),
+ "sha256": verify.sha256(file)})
+ encode(out / "smoke.mp4", frames)
+ renders = out / "renders/smoke"
+ renders.mkdir(parents=True)
+ Image.fromarray(frames[0]).save(renders / "main_t0.png")
+ shutil.copy2(renders / "main_t0.png", out / "smoke.png")
+ write_json(renders / "views.json", [{"name": "main", "time_s": 0, "path": "main_t0.png"}])
+ record = {"ok": True, "console_errors": [], "shader_errors": [], "camera": "main",
+ "width": 96, "height": 64, "fps": 3, "frames": 9, "seconds": 3,
+ "source_sha256": build.workspace_hashes(case, manifest["library_sha256"],
+ manifest["shader_sha256"]),
+ "video_sha256": verify.sha256(out / "smoke.mp4"), "reference_frames": references}
+ write_json(out / "smoke.capture.json", record)
+ write_json(out / "capture-plan.json", {"films": [
+ {"file": "smoke.mp4", "scene": "smoke", "camera": "main", "fps": 3, "frames": 9}]})
+ return out, frames
+
+
+def test_decoded_animation_matches_retained_inputs_and_external_sources(gallery):
+ out, _ = gallery
+ report = verify.verify(out)
+ assert report["external_shader_files"] == 3
+ film = report["films"][0]
+ assert film["frames_decoded"] == 9
+ assert set(film["motion_correspondence_at_160x90"]) == {3, 6}
+ assert film["capture_binding"] == "encoded_digest_and_input_frames"
+
+
[email protected]("change, message", [
+ ("frozen", "differs from its input|does not follow captured motion"),
+ ("encoded_bytes", "differs from its capture digest"),
+ ("missing_camera", "complete capture plan"),
+ ("fragment", "Published shaders"),
+ ("legacy", "lacks encoded-file/anchor evidence"),
+])
+def test_mislabelled_or_incomplete_media_is_rejected(gallery, change, message):
+ out, frames = gallery
+ record = json.loads((out / "smoke.capture.json").read_text())
+ if change == "frozen":
+ encode(out / "smoke.mp4", [frames[0]] * 9)
+ record["video_sha256"] = verify.sha256(out / "smoke.mp4")
+ write_json(out / "smoke.capture.json", record)
+ elif change == "encoded_bytes":
+ with (out / "smoke.mp4").open("ab") as stream:
+ stream.write(b"changed")
+ elif change == "fragment":
+ (out / "src/shaders/surface.frag").write_text("// Changed after capture\n")
+ elif change == "legacy":
+ record.pop("reference_frames")
+ record.pop("video_sha256")
+ write_json(out / "smoke.capture.json", record)
+ else:
+ plan = json.loads((out / "capture-plan.json").read_text())
+ plan["films"].append({**plan["films"][0], "file": "smoke_close.mp4"})
+ write_json(out / "capture-plan.json", plan)
+ with pytest.raises(ValueError, match=message):
+ verify.verify(out)
+
+
+def six_studies(gallery):
+ out, _ = gallery
+ manifest = json.loads((out / "manifest.json").read_text())
+ template = manifest["cases"][0]
+ record = json.loads((out / "smoke.capture.json").read_text())
+ manifest["cases"] = []
+ for key in ["fire", "ocean", "stream", "sand", "rocks", "meadow"]:
+ scene = f"export const kind = '{key}';\n".encode()
+ case = {**template, "id": key, "module": f"./src/scenes/{key}.js",
+ "scene_sha256": hashlib.sha256(scene).hexdigest()}
+ manifest["cases"].append(case)
+ (out / f"src/scenes/{key}.js").write_bytes(scene)
+ shutil.copy2(out / "smoke.mp4", out / f"{key}.mp4")
+ shutil.copy2(out / "smoke.png", out / f"{key}.png")
+ write_json(out / f"{key}.capture.json", {**record, "source_sha256":
+ build.workspace_hashes(case, manifest["library_sha256"], manifest["shader_sha256"])})
+ write_json(out / "manifest.json", manifest)
+ return out, record
+
+
+def test_transfer_package_keeps_shader_and_capture_inputs(gallery):
+ out, record = six_studies(gallery)
+ result = package.build_package(out, "transfer")
+ folder = Path(result["folder"])
+ for suffix in ["glsl", "vert", "frag"]:
+ assert (folder / f"src/shaders/surface.{suffix}").read_bytes() == b"void main() {}\n"
+ for reference in record["reference_frames"]:
+ assert verify.sha256(folder / reference["path"]) == reference["sha256"]
+ assert result["zip_crc_and_extracted_hashes"] == "pass"
+ with pytest.raises(FileExistsError):
+ package.build_package(out, "transfer")
+
+
[email protected]("changed", ["fire.mp4", "fire.capture.json"])
+def test_concurrent_recapture_cannot_change_verified_package_bytes(gallery, monkeypatch, changed):
+ out, _ = six_studies(gallery)
+ original_copy = shutil.copy2
+ changed_source = out / changed
+
+ def mutate_before_copy(source, target):
+ if source == changed_source:
+ with source.open("ab") as stream:
+ stream.write(b"changed during packaging")
+ return original_copy(source, target)
+
+ monkeypatch.setattr(package.shutil, "copy2", mutate_before_copy)
+ with pytest.raises(ValueError, match="hash mismatch"):
+ package.build_package(out, "inconsistent")
+ assert not (out / "packages/inconsistent.zip").exists()
+ assert not (out / "packages/inconsistent").exists()