Skip to content

Official Codebase of 3DCodeVerse

Python

tests: the effect library's 682 node-probe tests (52 files)

gaoypenga805104387f9
diff --git a/harness/tests/scene_runtime/lib/_probe.py b/harness/tests/scene_runtime/lib/_probe.py
new file mode 100644
index 00000000..1fb2cc99
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/_probe.py
@@ -0,0 +1,102 @@
+"""Node probes for the shipped effect library (``starter/src/lib``).
+
+Ported 2026-09-01 from the scene_multifile_graphics reference's tests/node_probe.py.
+A probe is an ES module run under OUR resolve hook (``runtime_js/lib/resolve_three.mjs``
+maps ``three`` / ``three/addons/*`` to the harness's own install), in a private temp
+dir holding a copy of the library — never a live workspace. ``measure`` returns the
+LAST stdout line of the probe as JSON; ``compile_scene`` compiles every program a
+fixture scene builds through ``runtime_js/check_shaders.mjs`` (headless GPU).
+"""
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+
+import pytest
+
+HARNESS = Path(__file__).resolve().parents[3]
+LIB_DIR = HARNESS / "codeverse" / "languages" / "scene_threejs" / "starter" / "src" / "lib"
+RESOLVE_HOOK = HARNESS / "runtime_js" / "lib" / "resolve_three.mjs"
+NODE_MODULES = HARNESS / "runtime_js" / "node_modules"
+
+pytestmark = pytest.mark.node
+
+
+def _three_ready() -> None:
+ if not (NODE_MODULES / "three" / "package.json").is_file():
+ pytest.skip("runtime_js/node_modules/three missing (npm ci in runtime_js)")
+
+
+def _stage(root: Path, libs: tuple[str, ...]) -> None:
+ (root / "lib").mkdir()
+ # the hub modules every effect imports ride along whatever the test names
+ for name in sorted(set(libs) | {"shader.js", "noise.js", "materials.js"}):
+ shutil.copy(LIB_DIR / name, root / "lib" / name)
+
+
+def measure(script: str, libs: tuple[str, ...] = (), *, timeout_s: float = 120.0) -> dict:
+ """Run ``script`` (an ES module; ``import ... from './lib/x.js'``) and parse its
+ last stdout line as JSON. The script is responsible for ``console.log(JSON...)``."""
+ _three_ready()
+ with tempfile.TemporaryDirectory(prefix="cv3d-libprobe-") as tmp:
+ root = Path(tmp)
+ _stage(root, libs)
+ (root / "probe.mjs").write_text(script, encoding="utf-8")
+ out = subprocess.run(
+ ["node", "--import", str(RESOLVE_HOOK), str(root / "probe.mjs")],
+ capture_output=True, text=True, timeout=timeout_s, cwd=str(root),
+ env={**os.environ, "NODE_PATH": str(NODE_MODULES)},
+ )
+ assert out.returncode == 0, out.stderr[-2000:]
+ lines = [ln for ln in out.stdout.strip().splitlines() if ln.strip()]
+ assert lines, "probe printed nothing"
+ return json.loads(lines[-1])
+
+
+def compile_scene(scene_src: str, libs: tuple[str, ...] = (), *,
+ extra: dict[str, str] | None = None,
+ audit_module: str | None = None,
+ timeout_s: float = 180.0) -> tuple[int, str]:
+ """Compile every program a fixture SCENE builds, on the headless GPU.
+
+ ``scene_src`` is a workspace ``src/scene.js``: it must export
+ ``createScene({THREE, renderer, loaders})`` returning
+ ``{scene, cameras, update}`` with at least one camera, because
+ ``check_shaders.mjs`` boots the workspace through ``openHost`` before it
+ force-compiles. ``extra`` writes further files under ``src/`` (a fixture
+ the scene imports). Returns (exit_code, combined output); 0 == every
+ program compiled, and the LAST line of the output is the JSON report.
+
+ ``audit_module`` scopes the STATIC audit to one staged file (the compile
+ stage still covers everything). Use it when a fixture of your own calls
+ ``patchStandard``: the audit's per-file rule cannot see that shader.js
+ declares and binds ``uTime`` at assembly time, so it reports an
+ undeclared/unbound pair on GLSL that is correct. ``src/lib/`` is already
+ exempt for that reason (``shader_report.mjs``); a fixture is not.
+
+ This replaced a ``shader_check(fixture_src, ...)`` that staged only
+ ``src/fixture.js`` and could therefore never get past
+ ``compile preflight failed: missing src/scene.js`` — every one of the 32
+ module tests that wanted a GPU compile had hand-rolled the same 17-line
+ workaround around it (consolidation, 2026-09-01).
+ """
+ _three_ready()
+ with tempfile.TemporaryDirectory(prefix="cv3d-compile-scene-") as tmp:
+ root = Path(tmp)
+ (root / "src").mkdir()
+ _stage(root / "src", libs)
+ (root / "src" / "scene.js").write_text(scene_src, encoding="utf-8")
+ for rel, text in (extra or {}).items():
+ (root / "src" / rel).write_text(text, encoding="utf-8")
+ out = subprocess.run(
+ ["node", "--import", str(RESOLVE_HOOK), str(HARNESS / "runtime_js" / "check_shaders.mjs"),
+ "--ws", str(root), "--timeout-ms", str(int(timeout_s * 1000))]
+ + (["--module", audit_module] if audit_module else []),
+ capture_output=True, text=True, timeout=timeout_s + 30, cwd=str(HARNESS / "runtime_js"),
+ env={**os.environ, "NODE_PATH": str(NODE_MODULES)},
+ )
+ return out.returncode, (out.stdout + "\n" + out.stderr)[-4000:]
diff --git a/harness/tests/scene_runtime/lib/test_accumulation.py b/harness/tests/scene_runtime/lib/test_accumulation.py
new file mode 100644
index 00000000..66b1c99c
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_accumulation.py
@@ -0,0 +1,892 @@
+"""accumulation.js: one deposit rule, and the chain it lands in.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_accumulation_lib.py). Their renderer-contract assertions are
+dropped; the physics claims, the shared-name contract and the
+option-is-a-uniform law are kept, and the grading this port added is pinned
+here so a later edit cannot quietly flatten either cover back to one value.
+
+These two patches exist to go ON TOP of everything else — a wall that already
+wears `patchTriplanar`, `patchMicroBreakup` and `patchEdgeWear`, a rock that
+already wears the aging marks — because a scene reads as weather only when the
+SAME stuff is on every surface in it. `patchStandard` absorbs a duplicate
+uniform SILENTLY (the second declaration is dropped and that patch then reads
+whatever its neighbour set) while a duplicate main() local is a compile error
+and a duplicate helper THROWS, so the shared contract is asserted first: one
+world base, no name any neighbour owns, every option a uniform rather than
+baked GLSL.
+
+Then the physics each patch claims — deposit along the up vector it was GIVEN,
+nothing on a face past the angle snow slides off, a concave lee holding what a
+convex edge sheds, sand ripples square to the wind — and finally the whole
+five-patch stack on a GPU, which is the only witness that the USE_INSTANCING
+branch compiles at all.
+
+THE PORT'S OWN LAW, and the one regression this file exists to stop: the lip
+(the shade a cover drops on the material just OUTSIDE its edge) is a band
+measured as a FRACTION of the coverage threshold. The reference took a fixed
+0.55 below it, and past a dusting the threshold itself falls under 0.55 — so
+zero deposit landed INSIDE the ramp and every bare wall, soffit and boulder
+flank in the scene picked up a shade it had no snow to justify (measured on
+our host at the shipped 0.05 m depth: 41 184 px of a 1024x576 frame darkened
+by up to 21%, with the melt hole printed through the wall behind it).
+"""
+from __future__ import annotations
+
+import json
+import math
+import re
+from collections import Counter
+
+import pytest
+from _probe import LIB_DIR, compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "terrain_shade.js", "waterside.js", "surface_wear.js",
+ "aging.js", "accumulation.js")
+
+_LIB_SRC = (LIB_DIR / "accumulation.js").read_text(encoding="utf-8")
+
+# The patch only exists inside onBeforeCompile, so every probe hands it
+# the two chunks patchStandard replaces and reads back what it wrote.
+_PRELUDE = """
+import * as THREE from 'three';
+import { patchSnow, patchSand } from './lib/accumulation.js';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+import { patchShoreWet, patchShoreFoam } from './lib/waterside.js';
+import { patchDripStains, patchRust, patchDust } from './lib/aging.js';
+
+const std = (o = {}) => new THREE.MeshStandardMaterial(
+ Object.assign({ color: 0x8b8478, roughness: 0.7 }, o));
+
+function compile(mat) {
+ const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+ };
+ mat.onBeforeCompile(shader);
+ return shader;
+}
+
+const count = (src, needle) => src.split(needle).length - 1;
+"""
+
+# The showcase subject, cut down: a slab, a wall on a footing with a return
+# (so there is an INSIDE CORNER), a sill, an asymmetric pitched roof (28 deg
+# one side, 62 the other, so the angle snow slides off is IN the fixture), a
+# forked branch and two boulders. The stone material carries ALL FIVE
+# patches, and the cobbles are instanced on that same material because a real
+# instanced program is the only thing that compiles the USE_INSTANCING branch.
+_SCENE = """
+import * as THREE from 'three';
+import { patchTriplanar } from './lib/terrain_shade.js';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+import { patchSnow, patchSand } from './lib/accumulation.js';
+
+export const BOUNDS = { min: [-12, 0, -12], max: [12, 8, 12] };
+export function heightAt() { return 0; }
+
+const WIND = [0.35, 0, -0.85];
+
+let s = 12345;
+const rnd = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+
+function boulder(r) {
+ const g = new THREE.SphereGeometry(r, 24, 16);
+ const p = g.attributes.position;
+ const v = new THREE.Vector3();
+ for (let i = 0; i < p.count; i++) {
+ v.fromBufferAttribute(p, i);
+ const n = Math.sin(v.x * 5.1 + 1.3) * Math.sin(v.y * 4.3)
+ * Math.sin(v.z * 6.1 + 0.7);
+ v.multiplyScalar(1 + n * 0.16);
+ p.setXYZ(i, v.x, v.y * 0.78, v.z);
+ }
+ g.computeVertexNormals();
+ return g;
+}
+
+export function build() {
+ const g = new THREE.Group();
+ const put = (geo, mat, x, y, z, rx = 0) => {
+ const m = new THREE.Mesh(geo, mat);
+ m.position.set(x, y, z);
+ m.rotation.x = rx;
+ g.add(m);
+ return m;
+ };
+ const stone = new THREE.MeshStandardMaterial({
+ color: 0x6a6155, roughness: 0.85,
+ });
+ const timber = new THREE.MeshStandardMaterial({
+ color: 0x40342a, roughness: 0.80,
+ });
+
+ put(new THREE.BoxGeometry(9, 0.25, 7), stone, 0, 0.125, 0);
+ put(new THREE.BoxGeometry(5.8, 0.4, 1.15), stone, 0, 0.45, -2.2);
+ put(new THREE.BoxGeometry(5.0, 2.7, 0.55), stone, 0, 2.0, -2.2);
+ put(new THREE.BoxGeometry(0.5, 1.8, 2.2), stone, -2.2, 1.6, -0.6);
+ put(new THREE.BoxGeometry(1.9, 0.14, 0.8), stone, -1.1, 2.05, -1.95);
+ put(new THREE.BoxGeometry(1.5, 1.1, 0.30), timber, -1.1, 2.68, -2.05);
+ put(new THREE.BoxGeometry(2.1, 0.20, 0.72), stone, -1.1, 3.30, -1.99);
+
+ const ridgeY = 4.35;
+ const gable = (deg, len, dir) => {
+ const a = deg * Math.PI / 180;
+ put(new THREE.BoxGeometry(5.6, 0.16, len), timber,
+ 0, ridgeY - Math.sin(a) * len / 2,
+ -2.2 + dir * Math.cos(a) * len / 2, dir > 0 ? a : -a);
+ };
+ gable(28, 2.6, 1);
+ gable(62, 2.6, -1);
+ put(new THREE.BoxGeometry(5.7, 0.18, 0.22), timber, 0, ridgeY + 0.05, -2.2);
+ put(boulder(0.85), stone, 2.9, 0.87, 1.1);
+ put(boulder(0.42), stone, 1.85, 0.55, 1.75);
+
+ const limb = (a, b, r) => {
+ const d = new THREE.Vector3().subVectors(b, a);
+ const m = put(new THREE.CylinderGeometry(r * 0.75, r, d.length(), 12),
+ timber, 0, 0, 0);
+ m.position.copy(a).addScaledVector(d, 0.5);
+ m.quaternion.setFromUnitVectors(
+ new THREE.Vector3(0, 1, 0), d.clone().normalize());
+ };
+ const V = (x, y, z) => new THREE.Vector3(x, y, z);
+ limb(V(-2.5, 0.2, 0.9), V(-1.9, 1.95, -1.6), 0.075);
+ limb(V(-1.9, 1.95, -1.6), V(-2.6, 2.75, -0.9), 0.05);
+ limb(V(-2.1, 1.35, -0.4), V(-1.35, 1.75, 0.35), 0.038);
+
+ const cobble = new THREE.InstancedMesh(boulder(0.17), stone, 40);
+ const mx = new THREE.Matrix4();
+ for (let i = 0; i < 40; i++) {
+ mx.compose(
+ new THREE.Vector3((rnd() * 2 - 1) * 4.0, 0.30, 0.4 + rnd() * 2.8),
+ new THREE.Quaternion().setFromEuler(
+ new THREE.Euler(rnd(), rnd() * 3, rnd())),
+ new THREE.Vector3(1, 0.7 + rnd() * 0.6, 1));
+ cobble.setMatrixAt(i, mx);
+ }
+ cobble.instanceMatrix.needsUpdate = true;
+ g.add(cobble);
+
+ for (const [mat, seed] of [[stone, 3], [timber, 9]]) {
+ patchTriplanar(mat, { scale: 0.8 });
+ patchMicroBreakup(mat, { seed, strength: 0.12 });
+ patchEdgeWear(mat, { seed, strength: 0.30, width: 0.25 });
+ patchSnow(mat, {
+ depth: 0.06, wind: WIND, seed,
+ melt: { amount: 0.2, at: [-1.1, 2.7, -1.75], radius: 1.1 },
+ });
+ patchSand(mat, { amount: 0.55, wind: WIND, seed });
+ }
+ return g;
+}
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ const sun = new THREE.DirectionalLight(0xfff0d8, 3.0);
+ sun.position.set(6, 9, 4);
+ scene.add(sun);
+ scene.add(new THREE.HemisphereLight(0xbfd4ee, 0x6a5a44, 0.6));
+ scene.add(build());
+ const cameras = [
+ { name: 'yard', position: [9, 5, 11], lookAt: [0, 2, 0], fov: 45 },
+ ];
+ return { scene, cameras, update() {} };
+}
+"""
+
+
+def _probe(body: str) -> dict:
+ return measure(_PRELUDE + body, _LIBS)
+
+
+def _find(pattern: str, src: str) -> re.Match:
+ m = re.search(pattern, src)
+ assert m, f"{pattern} not in\n{src}"
+ return m
+
+
+def _main_body(src: str) -> str:
+ return src[src.index("void main"):]
+
+
+def _unguarded(src: str) -> str:
+ """Drop `#ifndef X ... #endif` blocks, which may repeat verbatim.
+
+ terrain_shade ships astraFbmUnit from two patches behind one guard, so the
+ TEXT carries it twice and the preprocessor keeps one. Only an unguarded
+ repeat is a redefinition.
+ """
+ return re.sub(r"#ifndef\b.*?#endif", "", src, flags=re.S)
+
+
+def test_both_patches_plus_the_three_wear_patches_compile_on_one_material():
+ """The stack this library exists to join, on our GPU: snow and sand on the
+ SAME material that already carries a triplanar, a micro breakup and an edge
+ wear, in an asset that also puts that material on an InstancedMesh. Only a
+ real instanced draw compiles the USE_INSTANCING branch of the world base
+ (two programs for two materials that share one cache key is exactly that
+ second, instanced program), and only a real compile proves four libraries'
+ varyings, helpers and main() locals survive concatenation."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out
+ report = json.loads(out.strip().splitlines()[-1])
+ assert report["errors"] == [], report
+ assert report["compile"]["gpu"], "this claim is only worth a real GPU"
+ # Both materials wear the same chain, so they SHARE a cache key: the
+ # extra program is the instanced one, and it is the whole point.
+ assert report["compile"]["custom_materials"] >= 2, report
+ assert report["compile"]["programs"] >= 2, report
+
+
+def test_the_two_patches_chain_without_losing_each_other():
+ """Snow and sand on one material is not exotic — a drift of one and a bank
+ of the other meet on the same ground in any half-thawed scene.
+ patchStandard chains them, but it repeats whatever it is handed: the shared
+ world base and its three helpers must be emitted ONCE (a second function
+ body throws), the base must run FIRST or every fragment body reads a
+ varying nobody wrote, and re-applying a patch has to retune its uniforms
+ rather than inject a second copy of its code."""
+ out = _probe("""
+const m = std();
+patchSnow(m, { depth: 0.03 });
+patchSand(m, { amount: 0.2 });
+patchSnow(m, { depth: 0.12 });
+const s = compile(m);
+const sandOnly = std();
+patchSand(sandOnly);
+console.log(JSON.stringify({
+ key: m.customProgramCacheKey(), sandKey: sandOnly.customProgramCacheKey(),
+ snow: s.fragmentShader.includes('diffuseColor.rgb = mix(diffuseColor.rgb,'
+ + ' snCol, snAmt);'),
+ sand: s.fragmentShader.includes('diffuseColor.rgb = mix(diffuseColor.rgb,'
+ + ' sdCol, sdAmt);'),
+ depth: m.userData.uniforms.uSnowDepth.value,
+ amount: m.userData.uniforms.uSandAmt.value,
+ worldBody: count(s.vertexShader, 'vec4 acP ='),
+ axesFn: count(s.fragmentShader, 'vec3 astraAccAxes(vec3 n) {'),
+ noiseFn: count(s.fragmentShader, 'float astraAccNoise('),
+ curvFn: count(s.fragmentShader, 'float astraAccCurv('),
+ snowLine: count(s.fragmentShader, 'float snD ='),
+ varyVs: count(s.vertexShader, 'varying vec3 vAstraWorld;'),
+ varyFs: count(s.fragmentShader, 'varying vec3 vAstraWorldN;'),
+ baseFirst: s.fragmentShader.indexOf('vec3 astraAccAxes')
+ < s.fragmentShader.indexOf('vec3 snN ='),
+}));
+""")
+ assert out["snow"] and out["sand"], "a patch was lost"
+ assert out["worldBody"] == 1 and out["axesFn"] == 1
+ assert out["noiseFn"] == 1 and out["curvFn"] == 1
+ assert out["varyVs"] == 1 and out["varyFs"] == 1
+ assert out["baseFirst"], "a fragment body runs before the base helpers"
+ # Every option is a uniform, so re-applying retunes in place.
+ assert out["snowLine"] == 1 and out["depth"] == 0.12
+ assert out["amount"] == 0.2
+ assert out["key"] == "astra:acc:base+acc:snow+acc:sand", out["key"]
+ # A longer chain must not collide with a shorter one's program.
+ assert out["sandKey"] == "astra:acc:base+acc:sand"
+
+
+def test_the_deposit_follows_the_up_vector_it_was_given():
+ """Gravity is an OPTION here, not world Y: a tilted asset, a listing hull
+ or a scene authored Z-up must deposit on the faces that really point up,
+ and the sand wedge must be deepest at the foot measured along that same
+ axis. So both `up`s are uniforms — two materials with different ups share
+ one compiled program — every cosine and every height is taken against them,
+ nothing reads `.y` at all, and a degenerate vector falls back to +Y rather
+ than painting NaN."""
+ out = _probe("""
+const yUp = std();
+patchSnow(yUp); patchSand(yUp);
+const zUp = std();
+patchSnow(zUp, { up: new THREE.Vector3(0, 0, 4), depth: 0.2 });
+patchSand(zUp, { up: [0, 0, 4], amount: 0.9 });
+const arrUp = std();
+patchSnow(arrUp, { up: [3, 4, 0] });
+const dead = std();
+patchSnow(dead, { up: [0, 0, 0] });
+patchSand(dead, { up: [0, 0, 0] });
+const sa = compile(yUp), sb = compile(zUp);
+const u = (m, n) => m.userData.uniforms[n].value.toArray();
+console.log(JSON.stringify({
+ sameKey: yUp.customProgramCacheKey() === zUp.customProgramCacheKey(),
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ snowY: u(yUp, 'uSnowUp'), snowZ: u(zUp, 'uSnowUp'),
+ sandY: u(yUp, 'uSandUp'), sandZ: u(zUp, 'uSandUp'),
+ arr: u(arrUp, 'uSnowUp'),
+ deadSnow: u(dead, 'uSnowUp'), deadSand: u(dead, 'uSandUp'),
+ fs: sa.fragmentShader,
+}));
+""")
+ assert out["sameKey"] and out["sameFs"], "the up vector was baked in"
+ assert out["snowY"] == [0, 1, 0] and out["sandY"] == [0, 1, 0]
+ assert out["snowZ"] == [0, 0, 1], "an unnormalised up must be normalised"
+ assert out["sandZ"] == [0, 0, 1]
+ assert [round(v, 4) for v in out["arr"]] == [0.6, 0.8, 0]
+ assert out["deadSnow"] == [0, 1, 0], "a zero up must fall back, not NaN"
+ assert out["deadSand"] == [0, 1, 0]
+ body = _main_body(out["fs"])
+ # Snow: the deposit cosine and the thaw height are both against up.
+ _find(r"vec3 snUp = normalize\(uSnowUp\);", body)
+ _find(r"float snC = dot\(snN, snUp\);", body)
+ _find(r"float snH = dot\(vAstraWorld, snUp\)", body)
+ # Sand: the wedge's height and the lies-on-top term, likewise.
+ _find(r"vec3 sdUp = normalize\(uSandUp\);", body)
+ _find(r"float sdRise = 1\.0 - smoothstep\(0\.0, sdTop,\s*"
+ r"max\(dot\(vAstraWorld, sdUp\), 0\.0\)\);", body)
+ _find(r"float sdLie = smoothstep\(-?[\d.]+, [\d.]+,"
+ r" dot\(sdN, sdUp\)\);", body)
+ # Nothing may take world Y for up, and nothing may need a UV.
+ assert "vAstraWorld.y" not in body and ".y" not in body.replace(
+ "uSnowWarm.xyz", "").replace("gl_FragCoord.xy", "")
+ assert "vUv" not in body
+
+
+def test_a_steep_face_keeps_no_snow_whatever_the_field_says():
+ """Snow slides off. A face past roughly 58 degrees holds none, and that is
+ the single strongest cue that a white roof is snow rather than paint — a
+ 28-degree pitch white and a 62-degree pitch bare in the same frame. So the
+ gate must be MULTIPLICATIVE: the noise that tears the edge is a positive
+ FACTOR on the deposit, never an addend that could push a wall's zero over
+ the threshold, and melt may only ever subtract. A vertical wall and a
+ soffit are the same case."""
+ out = _probe("""
+const m = std();
+patchSnow(m, { depth: 0.06 });
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ body = _main_body(out["fs"])
+ slide = _find(r"float snLay = smoothstep\((-?[\d.]+), ([\d.]+), snC\)\s*"
+ r"\* mix\(([\d.]+), 1\.0, clamp\(snC, 0\.0, 1\.0\)\);",
+ body)
+ lo, hi, floor_ = (float(g) for g in slide.groups())
+ # cos of the angle it is all gone by: 0.45 is 63 deg, 0.75 is 41.
+ assert 0.45 <= lo <= 0.75, (
+ f"snow slides off at {math.degrees(math.acos(lo)):.0f} deg")
+ assert lo < hi <= 0.95, "a shallow pitch must reach the full fall"
+ assert 0 < floor_ <= 1, "a pitch holds less than a flat, never more"
+ # The whole deposit is a PRODUCT, so any zero factor is the end of it;
+ # the field is a strictly positive multiplier.
+ field = _find(r"float snD = snLay \* snHold \* snScour"
+ r" \* \(([\d.]+) \+ ([\d.]+) \* snG\);", body)
+ assert float(field.group(1)) > 0
+ # Melt only ever takes away, and the threshold never reaches zero, so a
+ # face with no deposit can never cross it.
+ _find(r"snD -= snThaw \* [\d.]+ \+ snWarm \* [\d.]+;", body)
+ thr = _find(r"float snT = mix\(([\d.]+), ([\d.]+), snCov\);", body)
+ assert float(thr.group(1)) > float(thr.group(2)) > 0, thr.groups()
+ _find(r"float snK = smoothstep\(snT - [\d.]+ - snAA,"
+ r" snT \+ [\d.]+ \+ snAA, snD\);", body)
+ # ...and the edge is torn by its own screen gradient, not ruled.
+ _find(r"float snAA = clamp\(fwidth\(snD\), 0\.0, [\d.]+\);", body)
+
+
+def test_a_lee_holds_more_than_an_edge_does():
+ """What separates a deposit from a coat of paint is that it is not where
+ the surface sticks out. A convex edge sheds and a concave lee holds, for
+ snow and for sand alike — and sand fills the concavities FIRST, which is
+ why a lightly sanded floor shows sand only in its corners and joints. The
+ estimate is the surface's own SIGNED curvature in 1/m (the world normal's
+ screen derivative over the world-space length of that pixel step), so it
+ holds still under distance and resolution; and the radius it looks for
+ scales with the deposit, because a deeper fall buries a bigger feature.
+
+ Sand's shed window starts LATER than its fill's on our host: at the
+ reference's 0.5/2.5 every cobble in a drift came out bare while the sand
+ ran on around it, which reads as a deflation pavement rather than a yard
+ that has been blown into."""
+ out = _probe("""
+const m = std();
+patchSnow(m, { depth: 0.06 });
+patchSand(m, { amount: 0.45 });
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ body = _main_body(fs)
+ # Curvature: the normal's derivative over the position's, signed.
+ _find(r"float astraAccCurv\(vec3 n, vec3 p\) \{\s*"
+ r"vec3 dx = dFdx\(p\), dy = dFdy\(p\);\s*"
+ r"float d = dot\(dx, dx\) \+ dot\(dy, dy\);\s*"
+ r"return \(dot\(dFdx\(n\), dx\) \+ dot\(dFdy\(n\), dy\)\)"
+ r" / max\(d, 1e-12\);", fs)
+ # Snow: the convex half SUBTRACTS, the concave half ADDS, and the radius
+ # it looks for is set by how deep the fall is.
+ _find(r"float snR = 1\.0 / max\(uSnowDepth \* [\d.]+, [\d.]+\);", body)
+ hold = _find(r"float snHold = 1\.0"
+ r" - ([\d.]+) \* smoothstep\(snR \* [\d.]+, snR \* [\d.]+,"
+ r" snCv\)\s*"
+ r"\+ ([\d.]+) \* smoothstep\(snR \* [\d.]+, snR \* [\d.]+,"
+ r" -snCv\);", body)
+ assert float(hold.group(1)) > 0 and float(hold.group(2)) > 0
+ _find(r"float snD = snLay \* snHold \*", body)
+ # Sand: the same two halves, and the concave one is what lets a low
+ # `amount` show sand in the corners and nowhere else.
+ _find(r"float sdR = 1\.0 / max\(uSandAmt \* [\d.]+ \+ [\d.]+,"
+ r" [\d.]+\);", body)
+ fill = _find(r"float sdFill = smoothstep\(sdR \* ([\d.]+),"
+ r" sdR \* ([\d.]+), -sdCv\);", body)
+ shed = _find(r"float sdShed = smoothstep\(sdR \* ([\d.]+),"
+ r" sdR \* ([\d.]+), sdCv\);", body)
+ # A stone is not a rib: the flank of anything rounder than the fill's own
+ # radius must still take sand.
+ assert float(shed.group(1)) > float(fill.group(1)), (
+ "sand sheds off a curve as readily as it fills one")
+ assert float(shed.group(2)) > float(fill.group(2))
+ lay = _find(r"float sdLay = clamp\(\(max\(sdLie \* [\d.]+, sdBank\)\s*"
+ r"\+ sdFill \* ([\d.]+)\) \* sdRise\s*"
+ r"- sdShed \* ([\d.]+), 0\.0, [\d.]+\);", body)
+ assert float(lay.group(2)) < 0.5, "the shed must not out-argue the wedge"
+
+
+def test_sand_ripples_run_across_the_wind_and_not_along_it():
+ """Aeolian ripples lie SQUARE to the flow: their crests are lines of
+ constant distance along the wind, so the phase must advance along the wind
+ axis and along nothing else. Get that backwards and the sand is combed the
+ way a river would comb it, which reads as flow rather than as wind. The
+ crest holds a little more sand than the trough (the ripple is in the
+ COVERAGE, not only in the tone), the lee face of each crest is steeper than
+ its windward one, the whole thing dies with the wind's strength, and it is
+ dropped once a pixel spans one period — past that it is not a ripple, it is
+ static."""
+ out = _probe("""
+const m = std();
+patchSand(m, { amount: 0.45, wind: [0.6, 0, 0.8] });
+const still = std();
+patchSand(still, { wind: [0, 0, 0] });
+const long_ = std();
+patchSand(long_, { wind: [4, 0, 3] });
+console.log(JSON.stringify({
+ fs: compile(m).fragmentShader,
+ wind: m.userData.uniforms.uSandWind.value.toArray(),
+ still: still.userData.uniforms.uSandWind.value.toArray(),
+ clamped: long_.userData.uniforms.uSandWind.value.toArray(),
+}));
+""")
+ body = _main_body(out["fs"])
+ # The wind axis, its strength its LENGTH, and never a normalize() of a
+ # zero vector.
+ _find(r"float sdWl = clamp\(length\(uSandWind\), 0\.0, 1\.0\);", body)
+ _find(r"vec3 sdWv = uSandWind / max\(length\(uSandWind\), 1e-4\);", body)
+ # THE CLAIM: the phase is the distance ALONG the wind, so the crests are
+ # the lines square to it.
+ _find(r"float sdPh = dot\(vAstraWorld, sdWv\) / sdLam"
+ r" \+ \(sdG - 0\.5\) \* [\d.]+;", body)
+ lam = _find(r"float sdLam = mix\(([\d.]+), ([\d.]+), uSandAmt\);", body)
+ lo, hi = float(lam.group(1)), float(lam.group(2))
+ assert 0.02 <= lo < hi <= 1.0, "a ripple is a decimetre thing"
+ # Skewed, faded and gone with the wind.
+ rip = _find(r"float sdRip = sin\(sdPh \+ ([\d.]+) \* sin\(sdPh\)\)"
+ r" \* sdFade \* sdWl\s*\* mix\([\d.]+, 1\.0, sdLie\);", body)
+ assert float(rip.group(1)) > 0, "an unskewed ripple is a sine wave"
+ _find(r"float sdFade = 1\.0 - smoothstep\([\d.]+, [\d.]+,\s*"
+ r"length\(fwidth\(vAstraWorld\)\) / sdLam\);", body)
+ # In the coverage AND in the tone: a ripple that is only a stripe of
+ # colour is a decal on flat sand.
+ _find(r"float sdD = sdLay \* \([\d.]+ \+ [\d.]+ \* sdG\)"
+ r" \+ sdRip \* [\d.]+;", body)
+ # ...and the crest is sun-bleached WARM against a cool trough, not one
+ # brightness up and down: a mono ripple is a painted stripe.
+ tint = _find(r"sdCol \*= vec3\(1\.0\) \+ sdRip"
+ r" \* vec3\(([\d.]+), ([\d.]+), ([\d.]+)\);", body)
+ r_, g_, b_ = (float(v) for v in tint.groups())
+ assert r_ > g_ > b_ > 0, (r_, g_, b_)
+ # The wind is a uniform vector with its strength in its length: a unit
+ # wind is full strength, a zero wind has no drift axis at all.
+ assert [round(v, 4) for v in out["wind"]] == [0.6, 0, 0.8]
+ assert out["still"] == [0, 0, 0]
+ assert [round(v, 4) for v in out["clamped"]] == [0.8, 0, 0.6]
+
+
+def test_no_patch_declares_a_name_its_neighbours_own():
+ """The silent failure this library is most exposed to: these two ride the
+ same materials as surface_wear, terrain_shade, waterside and aging, and
+ patchStandard DROPS a repeated uniform or varying and keeps the first — so
+ a shared name would leave one patch reading the other's value with nothing
+ reported. A repeated main() local is a compile error instead, and a
+ repeated helper throws. So the uniform sets must be disjoint (uTime
+ excepted, the shared clock), and a material wearing all ELEVEN patches must
+ declare every name exactly once."""
+ out = _probe("""
+const acc = std();
+patchSnow(acc);
+patchSand(acc);
+const nbr = std();
+patchTriplanar(nbr);
+patchSlopeSplat(nbr, { snowLine: 30 });
+patchShoreWet(nbr);
+patchShoreFoam(nbr);
+patchMicroBreakup(nbr);
+patchEdgeWear(nbr);
+patchDripStains(nbr);
+patchRust(nbr);
+patchDust(nbr);
+const all = std();
+patchTriplanar(all);
+patchSlopeSplat(all, { snowLine: 30 });
+patchShoreWet(all);
+patchShoreFoam(all);
+patchMicroBreakup(all);
+patchEdgeWear(all);
+patchDripStains(all);
+patchRust(all);
+patchDust(all);
+patchSnow(all);
+patchSand(all);
+const s = compile(all);
+console.log(JSON.stringify({
+ accU: Object.keys(acc.userData.uniforms),
+ nbrU: Object.keys(nbr.userData.uniforms),
+ vs: s.vertexShader, fs: s.fragmentShader,
+}));
+""")
+ shared = set(out["accU"]) & set(out["nbrU"])
+ assert shared == {"uTime"}, shared
+ for stage in ("vs", "fs"):
+ src = out[stage]
+ decls = re.findall(
+ r"^\s*(?:uniform|varying)\s+(?:lowp |mediump |highp )?"
+ r"[a-z0-9]+\s+(\w+)\s*;", src, re.M)
+ dupes = [n for n, c in Counter(decls).items() if c > 1]
+ assert not dupes, f"{stage} declares {dupes} twice"
+ fns = re.findall(r"^(?:float|vec[234]|int)\s+(\w+)\s*\(",
+ _unguarded(src), re.M)
+ assert not [n for n, c in Counter(fns).items() if c > 1]
+ locals_ = re.findall(
+ r"^\s*(?:float|vec[234]|int|mat[234])\s+(\w+)\s*=",
+ _main_body(src), re.M)
+ clash = [n for n, c in Counter(locals_).items() if c > 1]
+ assert not clash, f"{stage} main() declares {clash} twice"
+ # Named as the neighbours name them on purpose: ONE world position is
+ # written for the whole chain, not one per library.
+ assert "vAstraWorld" in out["vs"] and "vAstraWorld" in out["fs"]
+ # ...and the base folds in the instance transform, or every copy of a
+ # scattered cobble takes its weather from the mesh ORIGIN.
+ body = _main_body(out["vs"])
+ assert "#ifdef USE_INSTANCING" in body
+ _find(r"acP = instanceMatrix \* acP;", body)
+ _find(r"acN = mat3\(instanceMatrix\) \* acN;", body)
+ _find(r"vAstraWorld = \(modelMatrix \* acP\)\.xyz;", body)
+ assert "attribute mat4 instanceMatrix" not in out["vs"]
+ # fwidth, dFdx, gl_FragCoord and astraStroke are fragment-only, and the
+ # util block ships in both stages: they may be DEFINED in the vertex
+ # shader, never called from it.
+ assert "fwidth(" not in body and "dFdx(" not in body
+ assert "gl_FragCoord" not in body
+
+
+def test_an_option_is_a_uniform_and_never_baked_into_the_source():
+ """three caches programs by key and the FIRST material to compile a key
+ decides the GLSL every material sharing it gets. Two materials that differ
+ only in options must therefore compile to the same source, or the second
+ silently wears the first's weather — here that would mean one roof's snow
+ depth, one desert's wind direction and one thaw line imposed on every other
+ surface in the scene. Same key, byte-identical GLSL, different uniform
+ values."""
+ out = _probe("""
+const a = std();
+patchSnow(a, { depth: 0.05, seed: 1 });
+patchSand(a, { amount: 0.45, seed: 1 });
+const b = std();
+patchSnow(b, { depth: 0.42, seed: 99, up: [0, 0, 1], wind: [0.5, 0, 0.5],
+ color: new THREE.Color(0x112233),
+ melt: { amount: 0.8, at: [3, 2, 1], radius: 2.5 } });
+patchSand(b, { amount: 0.95, seed: 99, up: [0, 0, 1], wind: [0, 0, -1],
+ color: new THREE.Color(0x445566) });
+const sa = compile(a), sb = compile(b);
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ sameKey: a.customProgramCacheKey() === b.customProgramCacheKey(),
+ sameVs: sa.vertexShader === sb.vertexShader,
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ aSnow: [u(a).uSnowDepth.value, u(a).uSnowMelt.value,
+ u(a).uSnowWarm.value.toArray()],
+ bSnow: [u(b).uSnowDepth.value, u(b).uSnowMelt.value,
+ u(b).uSnowWarm.value.toArray()],
+ aSand: [u(a).uSandAmt.value, u(a).uSandWind.value.toArray()],
+ bSand: [u(b).uSandAmt.value, u(b).uSandWind.value.toArray()],
+ colors: [u(b).uSnowColor.value.getHex(), u(b).uSandColor.value.getHex()],
+}));
+""")
+ assert out["sameKey"] and out["sameVs"] and out["sameFs"]
+ assert out["aSnow"] == [0.05, 0, [0, 0, 0, 0]]
+ # A warm point is a uniform vec4 too, so the flue that melts a hole
+ # around itself does not need its own compiled program.
+ assert out["bSnow"] == [0.42, 0.8, [3, 2, 1, 2.5]]
+ assert out["aSand"] == [0.45, [1, 0, 0]]
+ assert out["bSand"] == [0.95, [0, 0, -1]]
+ assert out["colors"] == [0x112233, 0x445566]
+
+
+def test_one_seed_lays_the_same_weather_every_time():
+ """A render is re-run — for a fix round, for a video, for the judge — and
+ the drifts must not move between takes. The seed reaches the GPU only as a
+ noise-space OFFSET (a uniform, because baking it would hand material one's
+ seed to every material sharing the key), so one seed must give one set of
+ offsets, two seeds must not land on the same drifts, and snow must be
+ decorrelated from sand or every dune would sit under a snowdrift. The
+ offsets must also differ from surface_wear's and aging's for the same seed,
+ or the drifts would ride that library's blotches."""
+ out = _probe("""
+const mk = (seed) => {
+ const m = std();
+ patchSnow(m, { seed });
+ patchSand(m, { seed });
+ patchMicroBreakup(m, { seed });
+ patchDust(m, { seed });
+ return m;
+};
+const a = mk(7), b = mk(7), c = mk(8);
+const u = (m, n) => m.userData.uniforms[n].value.toArray();
+console.log(JSON.stringify({
+ aSnow: u(a, 'uSnowSeed'), bSnow: u(b, 'uSnowSeed'), cSnow: u(c, 'uSnowSeed'),
+ aSand: u(a, 'uSandSeed'), cSand: u(c, 'uSandSeed'),
+ aMicro: u(a, 'uMicroSeed'), aDust: u(a, 'uDustSeed'),
+ sameSrc: compile(a).fragmentShader === compile(c).fragmentShader,
+}));
+""")
+ assert out["aSnow"] == out["bSnow"], "the same seed moved the drifts"
+ assert out["aSnow"] != out["cSnow"] and out["aSand"] != out["cSand"]
+ assert out["aSnow"] != out["aSand"], "the dunes sit under the drifts"
+ assert out["aSnow"] != out["aMicro"] and out["aSnow"] != out["aDust"]
+ assert out["aSand"] != out["aMicro"] and out["aSand"] != out["aDust"]
+ assert all(0 <= v <= 56 for v in out["aSnow"] + out["aSand"])
+ # Same GLSL for both seeds: the seed is a uniform, not source.
+ assert out["sameSrc"]
+ assert "Math.random" not in _LIB_SRC
+
+
+def test_both_covers_take_the_gloss_over_through_compose_roughness():
+ """`fragmentBody` lands after <color_fragment> and therefore BEFORE
+ <roughnessmap_fragment> declares roughnessFactor, so neither patch can
+ touch a per-pixel gloss — and a snowed pane of glass that keeps its mirror
+ finish is the tell. Both therefore move the MATERIAL's roughness toward
+ the cover's own, by how much of the surface they took over, through
+ composeRoughness: one factor each, so any order and any number of
+ re-applications land on the same number, and a thawed-out snow patch gives
+ the material's finish back."""
+ out = _probe("""
+const shiny = std({ roughness: 0.2 });
+patchSnow(shiny, { depth: 0.05 });
+const snowR = shiny.roughness;
+patchSnow(shiny, { depth: 0.05 });
+const twice = shiny.roughness;
+const sandy = std({ roughness: 0.2 });
+patchSand(sandy, { amount: 0.45 });
+const sandR = sandy.roughness;
+const both = std({ roughness: 0.2 });
+patchSnow(both, { depth: 0.05 });
+patchSand(both, { amount: 0.45 });
+const thawed = std({ roughness: 0.2 });
+patchSnow(thawed, { depth: 0.05, melt: 1 });
+const rough = std({ roughness: 0.95 });
+patchSand(rough, { amount: 1 });
+patchSnow(rough, { depth: 0.3 });
+const buried = std({ roughness: 0.2 });
+patchSand(buried, { amount: 1 });
+const basic = new THREE.MeshBasicMaterial({ color: 0x445566 });
+patchSnow(basic);
+patchSand(basic);
+console.log(JSON.stringify({
+ snowR, twice, sandR, thawed: thawed.roughness, rough: rough.roughness,
+ buried: buried.roughness,
+ both: both.roughness,
+ base: both.userData.astraRoughness.base,
+ factors: Object.keys(both.userData.astraRoughness.factors).sort(),
+ basicRough: basic.roughness === undefined,
+ basicPatched: basic.userData.astraPatches.map((p) => p.name),
+}));
+""")
+ assert out["base"] == 0.2, "the authored value is the one to compose on"
+ assert sorted(out["factors"]) == sorted(["acc:snow", "acc:sand"])
+ # Snow is a diffuse cover with only the faintest sheen (0.86 here, not the
+ # reference's 0.72: with no post chain a glossy white cover adds a specular
+ # lobe on top of an already-clipped diffuse and the fall goes to a card);
+ # sand is the mattest thing in any scene. Both move a polished surface
+ # toward their own.
+ assert abs(out["snowR"] - (0.2 + 0.65 * (0.86 - 0.2))) < 1e-9, out
+ assert abs(out["sandR"] - (0.2 + 0.315 * (0.94 - 0.2))) < 1e-9, out
+ assert out["twice"] == out["snowR"], "re-applying compounded the gloss"
+ assert out["both"] > out["snowR"], "two covers, two factors"
+ # A cover that has melted away gives the finish back.
+ assert abs(out["thawed"] - 0.2) < 1e-9
+ # Two factors compose by MULTIPLYING (composeRoughness's contract), so a
+ # fully matte cover on an already-rough material still lands inside the
+ # range instead of running off the top of it.
+ assert 0.5 <= out["rough"] <= 1.0, out["rough"]
+ assert abs(out["buried"] - (0.2 + 0.70 * (0.94 - 0.2))) < 1e-9, out
+ # A material with no roughness at all still takes the albedo patch.
+ assert out["basicRough"]
+ assert out["basicPatched"] == ["acc:base", "acc:snow", "acc:sand"]
+
+
+def test_melt_gives_the_material_back_from_the_bottom_up():
+ """A wall's footing goes bare while its coping stays white: the foot of
+ anything is warmer (ground heat, splash, the traffic past it), so a thaw is
+ a LINE that climbs. A fragment cannot see the object it belongs to, so the
+ line is measured from the plane through the world origin — which is exactly
+ where the turntable makes an asset rest — and it is ragged, because it
+ rides the same field the deposit's edge does. `melt` also takes an
+ `at`/`radius`, which eats a hole around one warm world point: a flue, a
+ lamp, a vent. Both are uniforms, so a thaw can run over a shot without
+ recompiling anything."""
+ out = _probe("""
+const dry = std();
+patchSnow(dry);
+const half = std();
+patchSnow(half, { melt: 0.5 });
+const flue = std();
+patchSnow(flue, { melt: { amount: 0.1, at: [2, 3, 4], radius: 1.5 } });
+const bare = std();
+patchSnow(bare, { melt: { amount: 0.4 } });
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ sameFs: compile(dry).fragmentShader === compile(half).fragmentShader,
+ fs: compile(dry).fragmentShader,
+ dry: [u(dry).uSnowMelt.value, u(dry).uSnowWarm.value.toArray()],
+ half: u(half).uSnowMelt.value,
+ flue: [u(flue).uSnowMelt.value, u(flue).uSnowWarm.value.toArray()],
+ bare: [u(bare).uSnowMelt.value, u(bare).uSnowWarm.value.toArray()],
+ over: (() => { const m = std(); patchSnow(m, { melt: 4 });
+ return m.userData.uniforms.uSnowMelt.value; })(),
+}));
+""")
+ assert out["sameFs"], "the thaw line was baked in"
+ # No melt is no warm point either: a zero radius is OFF, not a zero-metre
+ # hole at the world origin.
+ assert out["dry"] == [0, [0, 0, 0, 0]]
+ assert out["half"] == 0.5 and out["over"] == 1
+ assert out["flue"] == [0.1, [2, 3, 4, 1.5]]
+ assert out["bare"] == [0.4, [0, 0, 0, 0]], "no `at` must not melt a hole"
+ body = _main_body(out["fs"])
+ # The line climbs with melt, from BELOW the resting plane (so melt 0 thaws
+ # nothing at all) to well above a storey.
+ line = _find(r"float snLine = mix\((-[\d.]+), ([\d.]+), uSnowMelt\);",
+ body)
+ assert float(line.group(1)) < 0 < float(line.group(2))
+ _find(r"float snThaw = 1\.0 - smoothstep\(snLine - [\d.]+,"
+ r" snLine \+ [\d.]+, snH\);", body)
+ # Ragged, on the same field that tears the deposit's own edge.
+ _find(r"float snH = dot\(vAstraWorld, snUp\) \+ \(snG - 0\.5\)"
+ r" \* [\d.]+;", body)
+ # The warm hole is a distance from a world point, switched OFF by a zero
+ # radius rather than by a branch.
+ _find(r"float snWarm = \(1\.0 - smoothstep\(snWr \* [\d.]+, snWr,\s*"
+ r"length\(vAstraWorld - uSnowWarm\.xyz\)\)\)\s*"
+ r"\* step\(1e-4, uSnowWarm\.w\);", body)
+
+
+def test_the_cover_shades_only_the_material_it_actually_stops_against():
+ """THE PORT'S REGRESSION TEST. Neither patch can displace geometry, so the
+ only thickness either layer has is the soft shade it drops on the material
+ just OUTSIDE its edge — and "just outside" has to mean it. The reference
+ took a fixed 0.55 below the coverage threshold, but that threshold FALLS as
+ the deposit deepens (0.92 for a dusting, 0.18 for a burying fall), so past
+ a dusting the band's floor went negative and a surface with ZERO deposit
+ sat inside the ramp: on our host at the shipped 0.05 m depth every vertical
+ wall, soffit and boulder flank in the frame came back up to 21% darker,
+ with the melt hole's own falloff printed through the bare wall behind it.
+
+ So the band is a FRACTION of the threshold: strictly positive at every
+ depth, and zero where there is no deposit at all."""
+ out = _probe("""
+const m = std();
+patchSnow(m, { depth: 0.05 });
+patchSand(m, { amount: 0.5 });
+const s = compile(m);
+console.log(JSON.stringify({ fs: s.fragmentShader, vs: s.vertexShader }));
+""")
+ body = _main_body(out["fs"])
+ for pre in ("sn", "sd"):
+ lip = _find(rf"float {pre}Lip = \(1\.0 - {pre}K\)"
+ rf" \* smoothstep\({pre}T \* ([\d.]+),"
+ rf" {pre}T - ([\d.]+),\s*{pre}D\);", body)
+ frac_, top = float(lip.group(1)), float(lip.group(2))
+ assert 0 < frac_ < 1, f"{pre}Lip's floor must scale with {pre}T"
+ assert frac_ * 0.18 > 0 and top < 0.18, (
+ f"{pre}Lip's band must stay inside the smallest threshold")
+ _find(rf"diffuseColor\.rgb \*= 1\.0 - ([\d.]+) \* {pre}Lip;", body)
+ # No fixed offset anywhere: that is the shape of the bug.
+ assert "smoothstep(snT - 0.55" not in body
+ assert "smoothstep(sdT - 0.55" not in body
+ # Thin snow lets the substrate through; deep snow does not.
+ thin = _find(r"float snThin = mix\(([\d.]+), 1\.0,"
+ r" smoothstep\([\d.]+, [\d.]+, snD\)\);", body)
+ assert 0 < float(thin.group(1)) < 1
+ _find(r"float snAmt = clamp\(snK \* snThin", body)
+ # Nothing is displaced, and the vertex stage does no work beyond the world
+ # position: the base is the whole of it.
+ vbody = _main_body(out["vs"])
+ assert "transformed +=" not in vbody and "transformed *=" not in vbody
+
+
+def test_neither_cover_is_one_flat_value():
+ """The aesthetic law this port added, pinned so an edit cannot flatten it.
+ Our host tone-maps ACES at exposure 1.0 with NO post chain, so a cover
+ shaded across the top of the curve renders as one card whatever field is
+ under it (measured: the reference's 0.85-linear white gave a snowed roof
+ 8 bits of luminance spread over 60 px and a mean saturation of 0.017). So
+ each cover carries: a default albedo under the shoulder, a tonal swing wide
+ enough to survive the curve, a SECOND finer field for the tone that is
+ faded out before it can alias, hue break at TWO scales, and a dither
+ against the banding the first three would otherwise put on a big flat
+ panel."""
+ out = _probe("""
+const m = std();
+patchSnow(m, { depth: 0.06 });
+patchSand(m, { amount: 0.5 });
+console.log(JSON.stringify({
+ fs: compile(m).fragmentShader,
+ snow: m.userData.uniforms.uSnowColor.value.toArray(),
+ sand: m.userData.uniforms.uSandColor.value.toArray(),
+}));
+""")
+ body = _main_body(out["fs"])
+ # Linear albedos under the shoulder: snow is the brightest thing a scene
+ # holds and still has to stay inside the range a dielectric can have.
+ assert 0.45 <= max(out["snow"]) <= 0.80, out["snow"]
+ assert min(out["snow"]) > 0.4, "a snow default must not read grey"
+ assert 0.20 <= max(out["sand"]) <= 0.60, out["sand"]
+ assert out["sand"][0] > out["sand"][1] > out["sand"][2], "ochre, not grey"
+ for pre, col, lo_max in (("sn", "uSnowColor", 0.60),
+ ("sd", "uSandColor", 0.75)):
+ tone = _find(rf"vec3 {pre}Col = mix\({col} \* ([\d.]+),"
+ rf" {col} \* ([\d.]+),\s*"
+ rf"smoothstep\([\d.]+, [\d.]+, {pre}Tn\)\);", body)
+ lo, hi = float(tone.group(1)), float(tone.group(2))
+ assert lo <= lo_max and hi >= 1.0 and hi / lo >= 1.6, (pre, lo, hi)
+ # The tone's own finer field, faded out before it can alias.
+ _find(rf"float {pre}Fad = 1\.0 - smoothstep\([\d.]+, [\d.]+,\s*"
+ rf"length\(fwidth\(vAstraWorld\)\)\);", body)
+ _find(rf"float {pre}F = astraAccNoise\({pre}P \* [\d.]+"
+ rf" \+ [\d.]+, {pre}W\);", body)
+ _find(rf"float {pre}Tn = clamp\(mix\({pre}G,"
+ rf" {pre}G \* [\d.]+ \+ {pre}F \* [\d.]+, {pre}Fad\),\s*"
+ rf"0\.0, 1\.0\);", body)
+ # Hue break at TWO scales: one field the width of a yard is still one
+ # flat tint on a roof.
+ breaks = re.findall(
+ rf"{pre}Col = astraHueBreak\({pre}Col, vAstraWorld\.xz"
+ rf"(?: \+ [\d.]+)?, ([\d.]+), ([\d.]+)\);", body)
+ assert len(breaks) == 2, breaks
+ (s0, w0), (s1, w1) = ((float(a), float(b)) for a, b in breaks)
+ assert s1 > s0 * 4, "the second break must be a tighter field"
+ assert 0 < w1 < w0, "the tight one swings less, or it stops reading"
+ # ...and a dither, because there is no post chain to add one.
+ _find(rf"{pre}Col \+= \(astraHash21\(gl_FragCoord\.xy\) - 0\.5\)"
+ rf" \* [\d.]+;", body)
+ # Snow's cold half rides the PACK, not just the rare concave lee: a drift
+ # scatters sky into itself while a scoured lane hands the substrate back.
+ _find(r"float snPack = clamp\(smoothstep\([\d.]+, [\d.]+, snD\)\s*"
+ r"\+ clamp\(snHold - 1\.0, 0\.0, 1\.0\) \* [\d.]+,\s*"
+ r"0\.0, 1\.0\);", body)
+ warm_cold = _find(
+ r"snCol \*= mix\(vec3\(([\d.]+), ([\d.]+), ([\d.]+)\),"
+ r" vec3\(([\d.]+), ([\d.]+), ([\d.]+)\),\s*snPack\);", body)
+ wr, wg, wb, cr, cg, cb = (float(v) for v in warm_cold.groups())
+ assert wr > wg > wb, "the scoured lane must be the WARM end"
+ assert cb > cg > cr, "the deep pack must be the COLD end"
diff --git a/harness/tests/scene_runtime/lib/test_aging.py b/harness/tests/scene_runtime/lib/test_aging.py
new file mode 100644
index 00000000..94ab29e4
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_aging.py
@@ -0,0 +1,760 @@
+"""aging.js: the three weather marks, and the chain they land in.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_aging_lib.py). Their renderer-contract assertions are dropped;
+the physics claims, the shared-name contract and the option-is-a-uniform law
+are kept, and the tone structure this port added (a rim/body/core triple on
+the runs, three tones on the rust, two on the dust) is pinned here so a later
+edit cannot quietly flatten an effect back to one colour.
+
+These patches exist to go ON TOP of something — a wall that already wears
+`patchMicroBreakup` and `patchEdgeWear`, a bank that already wears a triplanar
+and a waterline. `patchStandard` absorbs a duplicate uniform SILENTLY (the
+second declaration is dropped and that patch then reads whatever its neighbour
+set) while a duplicate local inside main is a compile error, so the shared
+contract is asserted first: one world base, no name any neighbour owns, every
+option a uniform rather than baked GLSL.
+"""
+from __future__ import annotations
+
+import json
+import re
+from collections import Counter
+
+import pytest
+from _probe import LIB_DIR, compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "terrain_shade.js", "waterside.js", "surface_wear.js",
+ "aging.js")
+
+_LIB_SRC = (LIB_DIR / "aging.js").read_text(encoding="utf-8")
+
+# The patch only exists inside onBeforeCompile, so every probe hands it
+# the two chunks patchStandard replaces and reads back what it wrote.
+_PRELUDE = """
+import * as THREE from 'three';
+import { patchDripStains, patchRust, patchDust } from './lib/aging.js';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+import { patchShoreWet, patchShoreFoam } from './lib/waterside.js';
+
+const std = (o = {}) => new THREE.MeshStandardMaterial(
+ Object.assign({ color: 0x8b8478, roughness: 0.7 }, o));
+
+function compile(mat) {
+ const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+ };
+ mat.onBeforeCompile(shader);
+ return shader;
+}
+
+const count = (src, needle) => src.split(needle).length - 1;
+"""
+
+# The showcase subject, cut down, as a workspace SCENE: a wall with a
+# ledge, a pipe, a tank, a leaning panel and a slab — and the wall
+# material carries ALL FIVE patches, which is the stack this library
+# ships to land in. The pebbles are instanced because that is the only
+# way the USE_INSTANCING branch of the world base is ever compiled, and
+# the scene sets fog and a casting sun so the fog and shadow branches of
+# every patched program are real code rather than dead #ifdefs.
+_SCENE = """
+import * as THREE from 'three';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+import { patchDripStains, patchRust, patchDust } from './lib/aging.js';
+
+const SILL = 3.4;
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 12, 20] };
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ const sun = new THREE.DirectionalLight(0xfff0d6, 2.5);
+ sun.position.set(5, 8, 7);
+ sun.castShadow = true;
+ scene.add(sun);
+ const g = new THREE.Group();
+ const concrete = new THREE.MeshStandardMaterial({
+ color: 0x8b8478, roughness: 0.85,
+ });
+ const slab = new THREE.MeshStandardMaterial({
+ color: 0x7c766c, roughness: 0.9, flatShading: true,
+ });
+ const steel = new THREE.MeshStandardMaterial({
+ color: 0x6a7278, roughness: 0.45, metalness: 0.25,
+ });
+
+ const put = (geo, mat, x, y, z) => {
+ const m = new THREE.Mesh(geo, mat);
+ m.position.set(x, y, z);
+ m.castShadow = true;
+ m.receiveShadow = true;
+ g.add(m);
+ return m;
+ };
+ put(new THREE.BoxGeometry(14, 0.3, 9), slab, 0, 0.15, 0);
+ put(new THREE.BoxGeometry(10, 3.4, 0.5), concrete, 0, 1.7, -2.6);
+ put(new THREE.BoxGeometry(10.6, 0.3, 1.1), concrete, 0, 3.55, -2.3);
+ // A leaning panel: the runs must come down WORLD Y on it too.
+ put(new THREE.BoxGeometry(3, 3, 0.3), concrete, 5.4, 1.8, 1.2)
+ .rotation.z = 0.5;
+ put(new THREE.CylinderGeometry(0.18, 0.18, 4.6, 24), steel, 3.8, 2.3, -1.9);
+ put(new THREE.CylinderGeometry(1.3, 1.3, 2.6, 40), steel, -3.6, 1.6, 1.2);
+ put(new THREE.TorusGeometry(1.3, 0.09, 14, 40), steel, -3.6, 2.9, 1.2)
+ .rotation.x = Math.PI / 2;
+
+ const pebble = new THREE.InstancedMesh(
+ new THREE.IcosahedronGeometry(0.2, 3), slab, 24);
+ const m = new THREE.Matrix4();
+ let s = 7;
+ const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+ for (let i = 0; i < 24; i++) {
+ m.compose(
+ new THREE.Vector3((rand() * 2 - 1) * 5, 0.45, (rand() * 2 - 1) * 3.5),
+ new THREE.Quaternion().setFromEuler(
+ new THREE.Euler(rand(), rand() * 3, rand())),
+ new THREE.Vector3(1, 0.8 + rand() * 0.5, 1));
+ pebble.setMatrixAt(i, m);
+ }
+ pebble.instanceMatrix.needsUpdate = true;
+ pebble.frustumCulled = false;
+ pebble.castShadow = true;
+ g.add(pebble);
+
+ patchDripStains(concrete, { from: SILL, strength: 0.38, seed: 3 });
+ patchRust(concrete, { strength: 0.22, scale: 2.4, seed: 3 });
+ patchDust(concrete, { strength: 0.28, seed: 3 });
+ patchDripStains(slab, { strength: 0.3, seed: 5 });
+ patchDust(slab, { strength: 0.35, seed: 5 });
+ patchRust(steel, { strength: 0.55, scale: 0.9, seed: 11 });
+ patchDripStains(steel, { strength: 0.3, scale: 0.35, seed: 11 });
+ patchDust(steel, { strength: 0.25, seed: 11 });
+ for (const [mat, seed] of [[concrete, 3], [slab, 5], [steel, 11]]) {
+ patchMicroBreakup(mat, { seed });
+ patchEdgeWear(mat, { seed });
+ }
+ scene.add(g);
+ // A camera is not decoration here: the host reports `ok: false` with an
+ // EMPTY error when `cameras` is empty, so a scene with none fails the
+ // compile preflight before a program is built (reported upstream).
+ return {
+ scene,
+ cameras: [{ name: 'hero', position: [12, 5, 14], lookAt: [0, 2, 0],
+ fov: 45 }],
+ update() {},
+ };
+}
+"""
+
+
+def _probe(body: str) -> dict:
+ return measure(_PRELUDE + body, _LIBS)
+
+
+def _find(pattern: str, src: str) -> re.Match:
+ m = re.search(pattern, src)
+ assert m, f"{pattern} not in\n{src}"
+ return m
+
+
+def _main_body(src: str) -> str:
+ return src[src.index("void main"):]
+
+
+def _unguarded(src: str) -> str:
+ """Drop ``#ifndef X ... #endif`` blocks, which may repeat verbatim.
+
+ terrain_shade ships astraFbmUnit from two patches behind one guard, so the
+ TEXT carries it twice and the preprocessor keeps one. Only an unguarded
+ repeat is a redefinition.
+ """
+ return re.sub(r"#ifndef\b.*?#endif", "", src, flags=re.S)
+
+
+def test_all_three_plus_both_wear_patches_compile_on_one_material():
+ """The stack this library exists to join, on our GPU: drips, rust and dust
+ on the SAME material that already carries `patchMicroBreakup` and
+ `patchEdgeWear`, in a scene that also puts an aged material on an
+ InstancedMesh and on a leaning panel. Only a real instanced program
+ compiles the USE_INSTANCING branch of the world base, and only a real
+ compile proves two libraries' varyings, helpers and main() locals survive
+ being concatenated into one shader."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out
+ report = json.loads(out.strip().splitlines()[-1])
+ assert report["ok"] and report["errors"] == [], report
+ # Three patched built-ins, and more programs than that: the slab
+ # material compiled twice (once per instancing state) and every
+ # caster compiled a depth program as well.
+ assert report["compile"]["custom_materials"] >= 3, report
+ assert report["compile"]["programs"] >= 4, report
+ assert report["compile"]["gpu"], report
+
+
+def test_the_three_patches_chain_without_losing_each_other():
+ """All three on one material is the ordinary case — a wall that streaks but
+ never dusts is half a wall. patchStandard chains them, but it repeats
+ whatever it is handed: the shared world base and its three helpers must be
+ emitted ONCE (a second function body is a compile error), the base must run
+ FIRST or every fragment body reads a varying nobody wrote, and re-applying
+ a patch has to retune its uniforms instead of injecting a second copy."""
+ out = _probe("""
+const m = std();
+patchDripStains(m, { strength: 0.2 });
+patchRust(m, { strength: 0.5 });
+patchDust(m, { strength: 0.1 });
+patchDripStains(m, { strength: 0.44 });
+const s = compile(m);
+const dripOnly = std();
+patchDripStains(dripOnly);
+console.log(JSON.stringify({
+ key: m.customProgramCacheKey(), dripKey: dripOnly.customProgramCacheKey(),
+ drip: s.fragmentShader.includes('mix(diffuseColor.rgb, drDirt, drAmt)'),
+ rust: s.fragmentShader.includes('mix(diffuseColor.rgb, rsCol, rsAmt)'),
+ dust: s.fragmentShader.includes('duK * uDustAmt'),
+ dripAmt: m.userData.uniforms.uDripAmt.value,
+ rustAmt: m.userData.uniforms.uRustAmt.value,
+ dustAmt: m.userData.uniforms.uDustAmt.value,
+ worldBody: count(s.vertexShader, 'vec4 agP ='),
+ axesFn: count(s.fragmentShader, 'vec3 astraAgeAxes(vec3 n) {'),
+ streakFn: count(s.fragmentShader, 'float astraAgeStreak('),
+ curvFn: count(s.fragmentShader, 'float astraAgeCurv('),
+ dripLine: count(s.fragmentShader, 'float drF ='),
+ varyVs: count(s.vertexShader, 'varying vec3 vAstraWorld;'),
+ varyFs: count(s.fragmentShader, 'varying vec3 vAstraWorldN;'),
+}));
+""")
+ assert out["drip"] and out["rust"] and out["dust"], "a patch was lost"
+ assert out["worldBody"] == 1 and out["axesFn"] == 1
+ assert out["streakFn"] == 1 and out["curvFn"] == 1
+ assert out["varyVs"] == 1 and out["varyFs"] == 1
+ # Every option is a uniform, so re-applying retunes in place.
+ assert out["dripLine"] == 1 and out["dripAmt"] == 0.44
+ assert out["rustAmt"] == 0.5 and out["dustAmt"] == 0.1
+ assert out["key"] == ("astra:aging:base+aging:drip+aging:rust"
+ "+aging:dust"), out["key"]
+ # A longer chain must not collide with a shorter one's program.
+ assert out["dripKey"] == "astra:aging:base+aging:drip"
+
+
+def test_no_patch_declares_a_name_its_neighbours_own():
+ """The silent failure this library is most exposed to: these three ride the
+ same materials as surface_wear, terrain_shade and waterside, and
+ patchStandard DROPS a repeated uniform or varying and keeps the first — so
+ a shared name would leave one patch reading the other's value with nothing
+ reported. A repeated local inside main is a compile error instead, and a
+ repeated helper is a redefinition. So the uniform sets must be disjoint
+ (uTime excepted, the shared clock), and a material wearing all NINE patches
+ must declare every name exactly once."""
+ out = _probe("""
+const age = std();
+patchDripStains(age);
+patchRust(age);
+patchDust(age);
+const nbr = std();
+patchTriplanar(nbr);
+patchSlopeSplat(nbr, { snowLine: 30 });
+patchShoreWet(nbr);
+patchShoreFoam(nbr);
+patchMicroBreakup(nbr);
+patchEdgeWear(nbr);
+const all = std();
+patchTriplanar(all);
+patchSlopeSplat(all, { snowLine: 30 });
+patchShoreWet(all);
+patchShoreFoam(all);
+patchMicroBreakup(all);
+patchEdgeWear(all);
+patchDripStains(all);
+patchRust(all);
+patchDust(all);
+const s = compile(all);
+console.log(JSON.stringify({
+ ageU: Object.keys(age.userData.uniforms),
+ nbrU: Object.keys(nbr.userData.uniforms),
+ vs: s.vertexShader, fs: s.fragmentShader,
+}));
+""")
+ shared = set(out["ageU"]) & set(out["nbrU"])
+ assert shared == {"uTime"}, shared
+ for stage in ("vs", "fs"):
+ src = out[stage]
+ decls = re.findall(
+ r"^\s*(?:uniform|varying)\s+(?:lowp |mediump |highp )?"
+ r"[a-z0-9]+\s+(\w+)\s*;", src, re.M)
+ dupes = [n for n, c in Counter(decls).items() if c > 1]
+ assert not dupes, f"{stage} declares {dupes} twice"
+ fns = re.findall(r"^(?:float|vec[234]|int)\s+(\w+)\s*\(",
+ _unguarded(src), re.M)
+ assert not [n for n, c in Counter(fns).items() if c > 1]
+ locals_ = re.findall(
+ r"^\s*(?:float|vec[234]|int|mat[234])\s+(\w+)\s*=",
+ _main_body(src), re.M)
+ clash = [n for n, c in Counter(locals_).items() if c > 1]
+ assert not clash, f"{stage} main() declares {clash} twice"
+ # Named as the neighbours name them on purpose: ONE world position is
+ # written for the whole chain, not one per library.
+ assert "vAstraWorld" in out["vs"] and "vAstraWorld" in out["fs"]
+ # ...and the base folds in the instance transform, or every copy of a
+ # scattered rock weathers from the mesh ORIGIN.
+ body = _main_body(out["vs"])
+ assert "#ifdef USE_INSTANCING" in body
+ _find(r"agP = instanceMatrix \* agP;", body)
+ _find(r"vAstraWorld = \(modelMatrix \* agP\)\.xyz;", body)
+ assert "attribute mat4 instanceMatrix" not in out["vs"]
+ # fwidth and astraStroke are fragment-only, and the util block ships in
+ # both stages: they may be DEFINED in the vertex shader, never called.
+ assert "fwidth(" not in body and "dFdx(" not in body
+
+
+def test_the_runs_come_down_world_y_whatever_the_surface_is_doing():
+ """The whole claim of the drip patch. A planar UV would streak a wall and
+ smear a pipe; an object-space axis would tilt with the mesh. So the field
+ is projected on the three WORLD planes, and the two upright projections
+ both take world Y as their second axis — compressed by a lift, which is
+ what makes a feature many times taller than it is wide. The projection a
+ fragment gets is chosen by the world NORMAL, so orientation decides WHICH
+ plane, and never which way is down. Nothing here may read a UV."""
+ out = _probe("""
+const m = std();
+patchDripStains(m, { scale: 0.6 });
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ # The vertical axis of both upright projections is p.y — world Y over
+ # `scale` — and the up-facing one gets no lift at all.
+ _find(r"float astraAgeStreak\(vec3 p, vec3 w, float lift\) \{\s*"
+ r"return astraNoise2\(vec2\(p\.z, p\.y \* lift\) \+ [\d.]+\)"
+ r" \* w\.x\s*"
+ r"\+ astraNoise2\(p\.xz \+ [\d.]+\) \* w\.y\s*"
+ r"\+ astraNoise2\(vec2\(p\.x, p\.y \* lift\) \+ [\d.]+\)"
+ r" \* w\.z;", fs)
+ body = _main_body(fs)
+ # World position over the scale, and weights from the world normal: a
+ # leaning panel picks a different plane, not a different down.
+ _find(r"vec3 drP = vAstraWorld / uDripScale \+ uDripSeed;", body)
+ _find(r"vec3 drN = normalize\(vAstraWorldN\);", body)
+ _find(r"vec3 drW = astraAgeAxes\(drN\);", body)
+ lift = _find(r"float drA = astraAgeStreak\(drP, drW, ([\d.]+)\);", body)
+ assert 0.02 <= float(lift.group(1)) <= 0.2, "the runs are not stretched"
+ # The drag sample sits HIGHER in world Y and is faded in, which is what
+ # tapers a run downward instead of ending it in a line.
+ drag = _find(r"float drB = astraAgeStreak\(drP \+ vec3\(0\.0, ([\d.]+),"
+ r" 0\.0\), drW, [\d.]+\);", body)
+ assert float(drag.group(1)) > 0
+ _find(r"float drF = max\(drA, drB \* 0\.\d+\)", body)
+ # Only faces that can shed take a run: a level top and a level soffit
+ # both get nothing.
+ _find(r"float drFlow = 1\.0 - smoothstep\([\d.]+, [\d.]+,"
+ r" abs\(drN\.y\)\);", body)
+ assert "vUv" not in body and "uv" not in body
+
+
+def test_a_run_is_a_pale_rim_around_a_dark_core_not_one_smudge():
+ """What this port changed, and the reason the runs read at all. Three
+ cuts on one field, not two: the outer rim takes the surface's OWN albedo
+ lifted (rain leaches a wall before it dirties it, and a colour named here
+ would belong to no wall in particular), the body and the core take the
+ grime. The rim must be the band the body does NOT cover, or the two mixes
+ land on the same pixels and cancel — which is exactly what the first
+ attempt did, and it lost contrast instead of gaining it.
+
+ The fwidth cap is the other half: it is a PIXEL guard, and at the old 0.5
+ it swallowed both threshold bands on any grazing surface and turned every
+ run into an airbrushed smear."""
+ out = _probe("""
+const m = std();
+patchDripStains(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ body = _main_body(out["fs"])
+ aa = _find(r"float drAA = clamp\(fwidth\(drF\), 0\.0, ([\d.]+)\);", body)
+ assert float(aa.group(1)) <= 0.10, "the AA cap can swallow a band whole"
+ lo = _find(r"float drWash = smoothstep\(([\d.]+) - drAA,"
+ r" ([\d.]+) \+ drAA, drF\);", body)
+ mid = _find(r"float drBody = smoothstep\(([\d.]+) - drAA,"
+ r" ([\d.]+) \+ drAA, drF\);", body)
+ hi = _find(r"float drCore = smoothstep\(([\d.]+) - drAA,"
+ r" ([\d.]+) \+ drAA, drF\);", body)
+ # Three bands stacked, each strictly inside the last.
+ assert (float(lo.group(1)) < float(mid.group(1)) < float(hi.group(1))
+ and float(lo.group(2)) <= float(mid.group(1))
+ and float(mid.group(2)) <= float(hi.group(1)))
+ # The rim is the wash MINUS the body — the frame, never the fill.
+ _find(r"float drRim = drWash \* \(1\.0 - drBody\);", body)
+ # The pale side is the surface's own colour lifted, not a colour named
+ # in this file: it has to belong to whatever it is running on.
+ salt = _find(r"vec3 drSalt = diffuseColor\.rgb \* ([\d.]+)"
+ r" \+ ([\d.]+);", body)
+ assert float(salt.group(1)) > 1.0 and float(salt.group(2)) > 0
+ _find(r"mix\(diffuseColor\.rgb, drSalt,\s*clamp\(drRim \* [\d.]+"
+ r" \* drG, 0\.0, 1\.0\)\)", body)
+ # ...and the dark side is the grime, hue-broken so two runs off one
+ # sill are never the same brown.
+ _find(r"vec3 drDirt = astraHueBreak\(uDripColor,", body)
+ _find(r"float drAmt = clamp\(\([\d.]+ \* drBody \+ [\d.]+ \* drCore\)"
+ r" \* drG,\s*0\.0, 1\.0\);", body)
+ _find(r"mix\(diffuseColor\.rgb, drDirt, drAmt\);", body)
+
+
+def test_a_sill_puts_the_runs_under_an_edge_instead_of_everywhere():
+ """Water comes over a lip; it does not appear evenly down a facade. A
+ fragment cannot see the surface above it, so the lip is `from`, a world Y —
+ and the gate is a WORLD Y DIFFERENCE, so it holds on a wall, a pipe and a
+ leaning panel alike. Each run starts a little lower than its neighbour and
+ dies at its own length, both from the field, so no ruled line appears
+ across the wall. Omitting `from` must not bake a different shader: it is
+ the same GLSL with the gate uniform at zero."""
+ out = _probe("""
+const sill = std();
+patchDripStains(sill, { from: 3.8 });
+const open = std();
+patchDripStains(open, { scale: 2.5, strength: 0.9 });
+const sa = compile(sill), sb = compile(open);
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ sameKey: sill.customProgramCacheKey() === open.customProgramCacheKey(),
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ fs: sa.fragmentShader,
+ sillFrom: u(sill).uDripFrom.value, sillGate: u(sill).uDripGate.value,
+ openFrom: u(open).uDripFrom.value, openGate: u(open).uDripGate.value,
+ openScale: u(open).uDripScale.value, openAmt: u(open).uDripAmt.value,
+}));
+""")
+ assert out["sameKey"] and out["sameFs"], "the sill was baked in"
+ assert out["sillFrom"] == 3.8 and out["sillGate"] == 1
+ assert out["openGate"] == 0, "no sill must not gate"
+ assert out["openScale"] == 2.5 and out["openAmt"] == 0.9
+ body = _main_body(out["fs"])
+ # Metres BELOW the sill, jittered per run so the tops stagger.
+ height = _find(r"float (\w+) = uDripFrom - vAstraWorld\.y"
+ r" - drB \* uDripScale;", body)
+ length = _find(r"float (\w+) = mix\([\d.]+, [\d.]+, drA\)"
+ r" \* uDripScale;", body)
+ gate = _find(rf"float (\w+) = smoothstep\(0\.0, uDripScale \* [\d.]+,"
+ rf" {height.group(1)}\)\s*"
+ rf"\* \(1\.0 - smoothstep\({length.group(1)} \* [\d.]+,"
+ rf" {length.group(1)}, {height.group(1)}\)\);", body)
+ # mix, not an if: the ungated case runs the same instructions, and the
+ # sill, the shedding test and the strength ride ONE factor so the rim
+ # and the grime cannot drift apart.
+ _find(rf"float drG = mix\(1\.0, {gate.group(1)}, uDripGate\)"
+ r" \* drFlow \* uDripAmt;", body)
+
+
+def test_rust_needs_the_water_to_sit_somewhere_and_bleeds_down():
+ """Corrosion sprayed evenly is a red object. It has to start where water
+ cannot leave — what faces up, and the concave lee a shape shelters — and
+ then continue DOWN the face below. The bleed is the map being read from
+ world XZ only: a vertical column of surface shares one value, so what eats
+ a rim goes on eating the side under it, which is the one way a fragment
+ that cannot see upward knows what drained onto it. The lee is the SIGNED
+ curvature: the convex half is where wear happens, not where water sits."""
+ out = _probe("""
+const m = std();
+patchRust(m, { scale: 1.2 });
+console.log(JSON.stringify({
+ fs: compile(m).fragmentShader,
+ scale: m.userData.uniforms.uRustScale.value,
+ color: m.userData.uniforms.uRustColor.value.getHex(),
+}));
+""")
+ fs = out["fs"]
+ body = _main_body(fs)
+ # The patch map: world XZ, no Y at all.
+ field = _find(r"float (\w+) = astraFbm2\((\w+)\.xz, \d\);", body)
+ _find(rf"vec3 {field.group(2)} = vAstraWorld / uRustScale"
+ r" \+ uRustSeed;", body)
+ # Signed curvature from the surface's own derivatives, and only the
+ # CONCAVE half counts.
+ curv = _find(r"float (\w+) = astraAgeCurv\(rsN, vAstraWorld\);", body)
+ _find(r"float astraAgeCurv\(vec3 n, vec3 p\) \{\s*"
+ r"vec3 dx = dFdx\(p\), dy = dFdy\(p\);", fs)
+ radius = _find(r"float (\w+) = 1\.0 / uRustScale;", body)
+ lee = _find(rf"float (\w+) = smoothstep\({radius.group(1)} \* [\d.]+,"
+ rf" {radius.group(1)} \* [\d.]+, -{curv.group(1)}\);", body)
+ # Pooling: up-facing plus that lee, together.
+ sit = _find(rf"float (\w+) = clamp\(smoothstep\(-?[\d.]+, [\d.]+,"
+ rf" rsN\.y\)\s*\+ {lee.group(1)} \* [\d.]+, 0\.0, 1\.0\);",
+ body)
+ # The run: on the faces that shed, ended by a field whose vertical
+ # period is metres and which is dragged downward.
+ _find(r"vec3 (\w+) = vec3\(rsP\.x, vAstraWorld\.y \* [\d.]+,"
+ r" rsP\.z\) \* [\d.]+;", body)
+ _find(r"float rsH = astraAgeStreak\(rsQ \+ vec3\(0\.0, [\d.]+, 0\.0\),"
+ r" rsA, [\d.]+\);", body)
+ _find(r"float rsB = max\(rsG, rsH \* 0\.\d+\);", body)
+ down = _find(r"float (\w+) = 1\.0 - smoothstep\([\d.]+, [\d.]+,"
+ r" abs\(rsN\.y\)\);", body)
+ run = _find(rf"float (\w+) = {down.group(1)}\s*"
+ r"\* \([\d.]+ \+ [\d.]+ \* smoothstep\([\d.]+, [\d.]+,"
+ r" rsB\)\);", body)
+ _find(rf"clamp\({sit.group(1)} \+ {run.group(1)}, 0\.0, 1\.0\)", body)
+ assert out["scale"] == 1.2
+ # An iron oxide: red-dominant, not a bright orange — and with a blue
+ # channel it can actually use. 0x70320f put blue at 0.005 linear, so
+ # the pit tone under it went to black and the patch read as a bruise.
+ r, g, b = (out["color"] >> 16, (out["color"] >> 8) & 255,
+ out["color"] & 255)
+ assert r > g > b and 0x50 <= r <= 0xa0, hex(out["color"])
+ assert b >= 0x20, hex(out["color"])
+
+
+def test_rust_is_three_tones_graded_by_the_field_not_one_flat_orange():
+ """What this port changed on the rust. A single colour scaled 0.45..1.05
+ gives a small subject — a 2.6 m tank, a pipe — one dark bruise: the tone
+ has no hue anywhere, so on anything cool-coloured it reads as a shadow.
+ Corrosion is a stack, so three tones ride the streak field: a near-black
+ pitted crust in its lee, the oxide through the body, an ochre bloom where
+ the crust is thinnest. All three are derived from the one `color` option,
+ so a caller still tunes it with one value."""
+ out = _probe("""
+const m = std();
+patchRust(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ body = _main_body(out["fs"])
+ # Hue-broken across the patch: not one brown for the whole tank.
+ _find(r"vec3 rsBase = astraHueBreak\(uRustColor, rsP\.xz,"
+ r" [\d.]+, [\d.]+\);", body)
+ pit = _find(r"vec3 rsPit = rsBase \* vec3\(([\d.]+), ([\d.]+),"
+ r" ([\d.]+)\);", body)
+ glow = _find(r"vec3 rsGlow = min\(rsBase \* vec3\(([\d.]+), ([\d.]+),"
+ r" ([\d.]+)\), vec3\(([\d.]+)\)\);", body)
+ # The pit is darker than the oxide, the bloom lighter, and the bloom
+ # is warmer than the oxide — it lifts green more than red, which is
+ # what turns an iron red into an ochre rather than a pink.
+ assert all(float(pit.group(i)) < 1.0 for i in (1, 2, 3))
+ assert all(float(glow.group(i)) > 1.0 for i in (1, 2, 3))
+ assert float(glow.group(2)) > float(glow.group(1))
+ # ...and it stays a plausible albedo: nothing here is emissive.
+ assert float(glow.group(4)) <= 0.85
+ # Graded ACROSS the patch by the streak field, not confined to the
+ # boundary — the boundary of a small patch is a few pixels wide.
+ _find(r"vec3 rsCol = mix\(rsPit, rsBase, smoothstep\([\d.]+, [\d.]+,"
+ r" rsB\)\);", body)
+ _find(r"rsCol = mix\(rsCol, rsGlow, smoothstep\([\d.]+, [\d.]+, rsB\)"
+ r" \* [\d.]+\s*\+ clamp\(rsK \* \(1\.0 - rsK\) \* [\d.]+,"
+ r" 0\.0, 1\.0\) \* [\d.]+\);", body)
+ _find(r"diffuseColor\.rgb = mix\(diffuseColor\.rgb, rsCol, rsAmt\);",
+ body)
+
+
+def test_dust_settles_along_the_up_vector_it_was_given():
+ """Dust is gravity, and gravity is an option here: a listing hull, a tipped
+ crate or a scene authored Z-up dusts the faces that actually point up, not
+ the ones with a positive world Y. So `up` is a UNIFORM — two materials
+ with different ups share one compiled program — the film is a cosine
+ against it, and a degenerate vector falls back to +Y rather than painting
+ NaN over the object."""
+ out = _probe("""
+const yUp = std();
+patchDust(yUp);
+const zUp = std();
+patchDust(zUp, { up: new THREE.Vector3(0, 0, 4), strength: 0.9 });
+const arrUp = std();
+patchDust(arrUp, { up: [3, 4, 0] });
+const dead = std();
+patchDust(dead, { up: [0, 0, 0] });
+const sa = compile(yUp), sb = compile(zUp);
+const u = (m) => m.userData.uniforms.uDustUp.value.toArray();
+console.log(JSON.stringify({
+ sameKey: yUp.customProgramCacheKey() === zUp.customProgramCacheKey(),
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ y: u(yUp), z: u(zUp), arr: u(arrUp), dead: u(dead),
+ amt: zUp.userData.uniforms.uDustAmt.value,
+ fs: sa.fragmentShader,
+}));
+""")
+ assert out["sameKey"] and out["sameFs"], "the up vector was baked in"
+ assert out["y"] == [0, 1, 0]
+ assert out["z"] == [0, 0, 1], "an unnormalised up must be normalised"
+ assert [round(v, 4) for v in out["arr"]] == [0.6, 0.8, 0]
+ assert out["dead"] == [0, 1, 0], "a zero up must fall back, not NaN"
+ assert out["amt"] == 0.9
+ body = _main_body(out["fs"])
+ lay = _find(r"float (\w+) = smoothstep\([\d.]+, [\d.]+,\s*"
+ r"dot\(duN, normalize\(uDustUp\)\)\);", body)
+ # Swept off what sticks out, held in what is sheltered — the same
+ # signed curvature, read the other way round.
+ hold = _find(r"float (\w+) = 1\.0 - [\d.]+ \* smoothstep\([\d.]+,"
+ r" [\d.]+, duC\)\s*\+ [\d.]+ \* smoothstep\([\d.]+,"
+ r" [\d.]+, -duC\);", body)
+ _find(rf"float (\w+) = clamp\({lay.group(1)} \* {hold.group(1)}", body)
+ _find(r"mix\(diffuseColor\.rgb, duCol,\s*duK \* uDustAmt\)", body)
+
+
+def test_the_dust_film_is_two_tones_at_one_value():
+ """What this port changed on the dust. One grey mixed over every upward
+ face is a coat of paint: the coarse grit that fell out first is warm, the
+ fine powder the sky keeps lighting is cool, and they split on the same
+ field that already sets the coverage. The two tones must sit at the SAME
+ value, so the film still lightens a surface evenly and only the hue moves
+ under it — a warm/cool pair with a value difference would read as a stain
+ instead of a settling."""
+ out = _probe("""
+const m = std();
+patchDust(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ body = _main_body(out["fs"])
+ _find(r"vec3 duCol = astraHueBreak\(uDustColor, duP\.xz,"
+ r" [\d.]+, [\d.]+\);", body)
+ pair = _find(r"duCol = mix\(duCol \* vec3\(([\d.]+), ([\d.]+), ([\d.]+)\),"
+ r"\s*duCol \* vec3\(([\d.]+), ([\d.]+), ([\d.]+)\),"
+ r"\s*smoothstep\([\d.]+, [\d.]+, duB\)\);", body)
+ veil = [float(pair.group(i)) for i in (1, 2, 3)]
+ drift = [float(pair.group(i)) for i in (4, 5, 6)]
+ # The veil is the cool one, the drift the warm one.
+ assert veil[2] > veil[0] and drift[0] > drift[2]
+ # Same value: Rec.709 luminance of the two multipliers within 3%.
+ def lum(c):
+ return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
+ assert abs(lum(veil) - lum(drift)) < 0.03, (veil, drift)
+ # A pale settled film, never a dark one: the option is an albedo.
+ assert all(0.7 <= v <= 1.3 for v in veil + drift)
+
+
+def test_an_option_is_a_uniform_and_never_baked_into_the_source():
+ """three caches programs by key and the FIRST material to compile a key
+ decides the GLSL every material sharing it gets. Two materials that differ
+ only in options must therefore compile to the same source, or the second
+ silently wears the first's settings — for these three that would mean one
+ building's sill height, patch size and dust colour imposed on every other.
+ Same key, byte-identical GLSL, different uniform values."""
+ out = _probe("""
+const a = std();
+patchDripStains(a, { strength: 0.35, scale: 0.6, seed: 1 });
+patchRust(a, { strength: 0.4, scale: 1.2, seed: 1 });
+patchDust(a, { strength: 0.3, seed: 1 });
+const b = std();
+patchDripStains(b, { strength: 0.9, scale: 4, from: -12.5, seed: 99,
+ color: new THREE.Color(0x112233) });
+patchRust(b, { strength: 0.05, scale: 0.2, seed: 99,
+ color: new THREE.Color(0x445566) });
+patchDust(b, { strength: 0.8, seed: 99, up: [0, -1, 0],
+ color: new THREE.Color(0x778899) });
+const sa = compile(a), sb = compile(b);
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ sameKey: a.customProgramCacheKey() === b.customProgramCacheKey(),
+ sameVs: sa.vertexShader === sb.vertexShader,
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ aDrip: [u(a).uDripAmt.value, u(a).uDripScale.value, u(a).uDripFrom.value],
+ bDrip: [u(b).uDripAmt.value, u(b).uDripScale.value, u(b).uDripFrom.value],
+ aRust: [u(a).uRustAmt.value, u(a).uRustScale.value],
+ bRust: [u(b).uRustAmt.value, u(b).uRustScale.value],
+ aDust: [u(a).uDustAmt.value, u(a).uDustUp.value.toArray()],
+ bDust: [u(b).uDustAmt.value, u(b).uDustUp.value.toArray()],
+ colors: [u(b).uDripColor.value.getHex(), u(b).uRustColor.value.getHex(),
+ u(b).uDustColor.value.getHex()],
+}));
+""")
+ assert out["sameKey"] and out["sameVs"] and out["sameFs"]
+ assert out["aDrip"] == [0.35, 0.6, 0] and out["bDrip"] == [0.9, 4, -12.5]
+ assert out["aRust"] == [0.4, 1.2] and out["bRust"] == [0.05, 0.2]
+ assert out["aDust"] == [0.3, [0, 1, 0]]
+ assert out["bDust"] == [0.8, [0, -1, 0]]
+ assert out["colors"] == [0x112233, 0x445566, 0x778899]
+
+
+def test_one_seed_lays_the_same_weather_every_time():
+ """A render is re-run — for a fix round, for a video, for the judge — and
+ the weather must not move between takes. The seed reaches the GPU only as
+ a noise-space OFFSET (a uniform, because baking it would hand material
+ one's seed to every material sharing the key), so one seed must give one
+ set of offsets, two seeds must not land on the same patches, and the three
+ effects must be decorrelated from each other or every run would come down
+ the middle of a rust patch. The offsets must also differ from
+ surface_wear's for the same seed, or the stains would ride that library's
+ blotches."""
+ out = _probe("""
+const mk = (seed) => {
+ const m = std();
+ patchDripStains(m, { seed });
+ patchRust(m, { seed });
+ patchDust(m, { seed });
+ patchMicroBreakup(m, { seed });
+ return m;
+};
+const a = mk(7), b = mk(7), c = mk(8);
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ aDrip: u(a).uDripSeed.value.toArray(),
+ bDrip: u(b).uDripSeed.value.toArray(),
+ cDrip: u(c).uDripSeed.value.toArray(),
+ aRust: u(a).uRustSeed.value.toArray(),
+ cRust: u(c).uRustSeed.value.toArray(),
+ aDust: u(a).uDustSeed.value.toArray(),
+ aMicro: u(a).uMicroSeed.value.toArray(),
+ sameSrc: compile(a).fragmentShader === compile(c).fragmentShader,
+}));
+""")
+ assert out["aDrip"] == out["bDrip"], "the same seed moved the runs"
+ assert out["aRust"] != out["cRust"] and out["aDrip"] != out["cDrip"]
+ assert out["aDrip"] != out["aRust"] != out["aDust"] != out["aDrip"]
+ assert out["aDrip"] != out["aMicro"], "stains ride the breakup's blobs"
+ assert all(0 <= v <= 48 for v in out["aDrip"] + out["aRust"])
+ # Same GLSL for both seeds: the seed is a uniform, not source.
+ assert out["sameSrc"]
+ assert "Math.random" not in _LIB_SRC
+
+
+def test_every_effect_is_matte_and_composes_on_the_material():
+ """`fragmentBody` lands after <color_fragment> and therefore BEFORE
+ <roughnessmap_fragment> declares roughnessFactor, so no patch here can
+ touch a per-pixel gloss. Dirt, rust and dust are all matte, so each RAISES
+ the material's roughness — through composeRoughness, so the three own one
+ factor each and a refine round that re-runs the same build cannot compound
+ them into a chalk. A factor is also capped at what leaves the surface
+ fully rough, since roughness means nothing past 1.
+
+ The factors this port raised: at the old 0.22 a fully rusted steel tank
+ moved from roughness 0.45 to 0.50 and went on mirroring the sky, which
+ washed the oxide out of the frame. A crust is matte, so a full-strength
+ rust now buys real roughness."""
+ out = _probe("""
+const m = std({ roughness: 0.5 });
+patchDust(m, { strength: 1 });
+const r1 = m.roughness;
+patchRust(m, { strength: 1 });
+const r2 = m.roughness;
+patchRust(m, { strength: 1 });
+const r3 = m.roughness;
+patchRust(m, { strength: 0 });
+const r4 = m.roughness;
+const hard = std({ roughness: 0.95 });
+patchDust(hard, { strength: 1 });
+const tank = std({ roughness: 0.45, metalness: 0.25 });
+patchRust(tank, { strength: 1 });
+const basic = new THREE.MeshBasicMaterial({ color: 0x445566 });
+patchDripStains(basic);
+patchDust(basic);
+console.log(JSON.stringify({
+ r1, r2, r3, r4, base: m.userData.astraRoughness.base,
+ factors: Object.keys(m.userData.astraRoughness.factors).sort(),
+ hard: hard.roughness, tank: tank.roughness,
+ basicRough: basic.roughness === undefined,
+ basicPatched: !!basic.userData.astraPatches.length,
+}));
+""")
+ # Every patch raises roughness and none of them re-bases the others.
+ assert out["base"] == 0.5
+ assert out["r1"] > 0.5 and out["r2"] > out["r1"]
+ assert out["r3"] == out["r2"], "re-applying compounded the roughening"
+ assert out["r4"] == out["r1"], "strength 0 must remove the factor"
+ assert out["factors"] == ["aging:dust", "aging:rust"]
+ # A surface that already starts rough cannot be pushed past 1.
+ assert out["hard"] == pytest.approx(1.0)
+ # ...and a semi-gloss tank goes properly matte under full corrosion.
+ assert out["tank"] >= 0.7, out["tank"]
+ # A material with no roughness at all is patched and left alone.
+ assert out["basicRough"] and out["basicPatched"]
diff --git a/harness/tests/scene_runtime/lib/test_atmosphere.py b/harness/tests/scene_runtime/lib/test_atmosphere.py
new file mode 100644
index 00000000..e21aa9aa
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_atmosphere.py
@@ -0,0 +1,764 @@
+"""atmosphere.js — the two distance cues geometry alone cannot give.
+
+`scene.fog` is a function of camera distance, so it veils a figure's
+head as much as its boots: a fog BANK has to be geometry with a height
+profile, and the failure mode of that idea is a milky SLAB with a lid, a
+rectangular edge and a contour line wherever a sheet crosses something
+standing in it. FogExp2 also dims without shifting hue, so a correctly
+built far field still reads as a saturated tabletop model.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_atmosphere_lib.py). Their renderer-contract assertions are
+kept (shader.js still ships the depth + fog chunks here), and the port
+adds what THIS renderer needed: the colour of the air is read off the
+scene (`scene.environment`, its fog, its lights) instead of being a
+baked daylight white, which on a night rig painted the ground under the
+bank (69,66,64) against a (26,36,64) sky — the brightest thing in frame.
+"""
+from __future__ import annotations
+
+import json
+
+import pytest
+from _probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("atmosphere.js", "environment.js", "sky.js")
+
+
+def _measure(script: str) -> dict:
+ return measure(script, _LIBS)
+
+
+def test_the_bank_is_a_stack_packed_at_the_ground_not_a_slab():
+ """One box of fog is a slab; a stack of sheets whose spacing tightens
+ toward the ground is what puts the extinction in the first metre,
+ where the wading happens."""
+ out = _measure("""
+import * as THREE from 'three';
+import { makeHeightFog } from './lib/atmosphere.js';
+const g = makeHeightFog({ extent: 60, top: 4, density: 0.75, seed: 5 });
+const mesh = g.children[0];
+const geo = mesh.geometry;
+const hs = [...new Set(Array.from(geo.attributes.aH.array))]
+ .sort((a, b) => a - b);
+const pos = geo.attributes.position.array;
+let minX = 1e9, maxX = -1e9;
+for (let i = 0; i < pos.length; i += 3) {
+ minX = Math.min(minX, pos[i]);
+ maxX = Math.max(maxX, pos[i]);
+}
+const u = mesh.material.uniforms;
+console.log(JSON.stringify({
+ name: g.name, meshName: mesh.name, children: g.children.length,
+ sheets: hs.length, lowest: hs[0], highest: hs[hs.length - 1],
+ firstGap: hs[1] - hs[0], lastGap: hs[hs.length - 1] - hs[hs.length - 2],
+ spanX: maxX - minX,
+ transparent: mesh.material.transparent,
+ depthWrite: mesh.material.depthWrite,
+ doubleSide: mesh.material.side === THREE.DoubleSide,
+ radius: u.uRadius.value, top: u.uTop.value, density: u.uDensity.value,
+ hasTick: typeof g.userData.tick === 'function',
+}));
+""")
+ assert out["name"] == "HeightFog" and out["children"] == 1
+ # A sheet's plane crosses anything vertical along a horizontal line,
+ # and the number of sheets in front changes across it: the sheet
+ # count IS the quantisation of the height integral. At the
+ # reference's 12 a crate standing in the bank wore six hard contour
+ # bands on this renderer.
+ assert out["sheets"] >= 20, "the sheet count is the step size"
+ # Off the soil (no z-fight with the ground) but low enough that the
+ # bottom of the bank is the ground.
+ assert 0 < out["lowest"] < 0.1
+ assert out["highest"] == 4, "the top sheet sits exactly at `top`"
+ assert out["firstGap"] < out["lastGap"] * 0.5, (
+ "sheets must pack toward the ground where the fog is dense")
+ assert out["spanX"] == 60
+ # A fog bank that writes depth erases whatever it is standing in.
+ assert out["transparent"] and not out["depthWrite"]
+ assert out["doubleSide"], "the bank is seen from above and inside"
+ assert out["radius"] * 2 == out["spanX"], (
+ "the feather radius is the inscribed circle: any larger and the "
+ "square footprint reaches full opacity at its own corner")
+ assert out["hasTick"]
+
+
+def test_the_bank_follows_the_terrain_and_is_free_when_it_is_flat():
+ """A flat sheet stack over relief hangs in the air on the high
+ ground and buries the low ground; over flat ground the same
+ tessellation is pure waste, since every variation is per fragment."""
+ out = _measure("""
+import { makeHeightFog } from './lib/atmosphere.js';
+const hAt = (x, z) => Math.sin(x * 0.15) * 2 + Math.cos(z * 0.1);
+const t = makeHeightFog({ extent: 40, top: 3, heightAt: hAt, seed: 2 });
+const f = makeHeightFog({ extent: 40, top: 3, seed: 2 });
+const gt = t.children[0].geometry, gf = f.children[0].geometry;
+const p = gt.attributes.position.array, h = gt.attributes.aH.array;
+let worst = 0, relief = 0, lowest = 1e9;
+for (let i = 0, k = 0; i < p.length; i += 3, k++) {
+ worst = Math.max(worst, Math.abs(p[i + 1] - (hAt(p[i], p[i + 2]) + h[k])));
+ if (h[k] === h[0]) {
+ relief = Math.max(relief, p[i + 1]);
+ lowest = Math.min(lowest, p[i + 1]);
+ }
+}
+const pf = gf.attributes.position.array, hf = gf.attributes.aH.array;
+let flatWorst = 0;
+for (let i = 0, k = 0; i < pf.length; i += 3, k++) {
+ flatWorst = Math.max(flatWorst, Math.abs(pf[i + 1] - hf[k]));
+}
+console.log(JSON.stringify({
+ worst, flatWorst, bottomRelief: relief - lowest,
+ terrainVerts: gt.attributes.position.count,
+ flatVerts: gf.attributes.position.count,
+ sheets: new Set(Array.from(hf)).size,
+}));
+""")
+ # Float32 storage, so exactly is 1e-5 in metres — 10 microns.
+ assert out["worst"] < 1e-5, "every vertex sits heightAt(x, z) + aH up"
+ assert out["flatWorst"] < 1e-5, "with no heightAt the sheets are flat"
+ assert out["bottomRelief"] > 3, "the bottom sheet really rides relief"
+ assert out["terrainVerts"] > 5000, "relief needs tessellation"
+ # Four corners per sheet: flat ground pays for no subdivision at all.
+ assert out["flatVerts"] == out["sheets"] * 4
+
+
+def test_the_bank_is_the_air_a_ray_flies_through_not_a_stack_of_alphas():
+ """A stack of horizontal sheets is seen EDGE-ON, so a ray crosses
+ every one of them however near the ground it lands: sheets at a
+ constant alpha composite to the same near-opaque value for every ray
+ alike, near, far, steep or grazing. Each sheet instead carries the
+ slab of column it samples and charges Beer-Lambert on the METRES of
+ air the view ray crosses in it, so the ground keeps its own colour
+ underfoot and the band thickens down the valley."""
+ out = _measure("""
+import { makeHeightFog } from './lib/atmosphere.js';
+
+// CPU mirror of the fragment math, over the REAL geometry and
+// uniforms; the source assertions below pin that the GLSL is this.
+const smoothstep = (a, b, x) => {
+ const t = Math.min(1, Math.max(0, (x - a) / (b - a)));
+ return t * t * (3 - 2 * t);
+};
+function sheets(g) {
+ const geo = g.children[0].geometry;
+ const h = geo.attributes.aH.array, dh = geo.attributes.aDH.array;
+ const seen = new Map();
+ for (let i = 0; i < h.length; i++) {
+ if (!seen.has(h[i])) seen.set(h[i], dh[i]);
+ }
+ return [...seen.entries()].sort((a, b) => a[0] - b[0]);
+}
+// Opacity of a ray from an eye `up` metres over the ground to ground
+// `dist` metres away, noise at its mid value.
+function opacity(g, dist, up) {
+ const u = g.children[0].material.uniforms;
+ const sigma = -Math.log(1 - Math.min(u.uDensity.value, 0.995)) / 10;
+ const climb = Math.max(up / dist, 1e-3);
+ let T = 1;
+ for (const [h, dh] of sheets(g)) {
+ const prof = Math.exp(-h / u.uScale.value)
+ * (1 - smoothstep(u.uTop.value * 0.45, u.uTop.value, h));
+ const breakup = 1 - 0.5 * smoothstep(0.10, 0.85, h / u.uTop.value);
+ const air = Math.min(dh / climb, dist) * prof;
+ T *= Math.exp(-sigma * air * breakup * 1.0);
+ }
+ return 1 - T;
+}
+const g = makeHeightFog({ extent: 60, height: 1.6, seed: 7 });
+const wide = makeHeightFog({ extent: 200, height: 1.6, seed: 7 });
+const m = g.children[0].material;
+console.log(JSON.stringify({
+ height: m.uniforms.uTop.value,
+ topStillWorks: makeHeightFog({ top: 2.5 }).children[0]
+ .material.uniforms.uTop.value,
+ column: sheets(g).reduce((s, [, dh]) => s + dh, 0),
+ near: opacity(g, 8, 5.2),
+ mid: opacity(g, 20, 5.2),
+ far: opacity(g, 80, 5.2),
+ horizon: opacity(g, 200, 5.2),
+ // The dial is a property of the AIR, so the same density in a bank
+ // three times the size is the same veil.
+ wideFar: opacity(wide, 80, 5.2),
+ fs: m.fragmentShader,
+}));
+""")
+ assert out["height"] == 1.6, (
+ "`height` is what every other lib here calls this (watermist, "
+ "rain, grass); ignoring it shipped a 4 m bank to a caller who "
+ "asked for 1.6 m")
+ assert out["topStillWorks"] == 2.5, "`top` is the old name, kept"
+ assert abs(out["column"] - 1.6) < 1e-6, (
+ "the slabs must partition [0, height] exactly once — a gap "
+ "loses air and an overlap counts it twice")
+ # The fix, as a number: a ray that lands 8 m from the eye crosses
+ # every sheet and must still collect only a wisp.
+ assert out["near"] < 0.10, (
+ "ground fog is invisible at your feet; a constant per-sheet "
+ "alpha put it at 0.9932 here")
+ assert out["far"] > 0.45 and out["horizon"] > 0.75, (
+ "and solid down the valley — the fog must not be fixed by "
+ "making it invisible")
+ assert out["far"] > out["mid"] > out["near"], "monotone with distance"
+ assert out["far"] / out["near"] > 5, (
+ "the whole cue is the RATIO: a constant alpha gave near and far "
+ "the same 0.9932")
+ assert abs(out["wideFar"] - out["far"]) < 1e-6, (
+ "`density` is extinction per metre of air, so it means the "
+ "same veil at any extent")
+ fs = out["fs"]
+ # The three terms that make the alpha an integral instead of a
+ # sticker: the view ray, the slab, and Beer-Lambert over the two.
+ assert "vec3 ray = vWorld - cameraPosition;" in fs
+ assert "float air = min(vDH / climb, dist) * prof * edge;" in fs, (
+ "a sheet charges its own slab crossed at the ray's slope, and "
+ "never more air than the ray has flown")
+ assert "float a = 1.0 - exp(-sigma * air" in fs, (
+ "composited alphas must telescope to exp(-sum of taus), or the "
+ "sheets behind the first each take another bite")
+
+
+def test_the_sheets_stay_out_of_the_ambient_occlusion_buffer():
+ """A depth+normal prepass (GTAOPass, and the side track's post chain
+ here) rebuilds the scene with an OVERRIDE material, which sees a
+ stack of transparent sheets as a stack of solid floors centimetres
+ apart, each occluding the next: measured at 50/255 of darkening on
+ ground the fog was not even touching, edged by its own footprint."""
+ out = _measure("""
+import * as THREE from 'three';
+import { makeHeightFog } from './lib/atmosphere.js';
+const mesh = makeHeightFog({ extent: 60, height: 1.6 }).children[0];
+const geo = mesh.geometry;
+const own = mesh.material;
+const alien = new THREE.MeshNormalMaterial();
+mesh.onBeforeRender(null, null, null, geo, alien);
+const hidden = geo.drawRange.count;
+mesh.onAfterRender(null, null, null, geo, alien);
+const restored = geo.drawRange.count;
+mesh.onBeforeRender(null, null, null, geo, own);
+// Infinity is three's own "draw all of it" and does not survive JSON.
+console.log(JSON.stringify({
+ hidden, restored: restored === Infinity,
+ drawn: geo.drawRange.count === Infinity,
+}));
+""")
+ assert out["hidden"] == 0, "no sheet may reach the G-buffer"
+ assert out["drawn"], "and every sheet is drawn in the real pass"
+ assert out["restored"], (
+ "restored after EVERY pass, or a raycast or a later frame "
+ "inherits an empty draw range from whichever pass ran last")
+
+
+def test_the_bank_thins_to_nothing_feathers_its_rim_and_hides_its_sheets():
+ """The three ways this geometry betrays itself: a top edge that stops
+ at a value (a lid), a footprint edge that stops at full opacity (a
+ rectangle across the frame), and one constant alpha per sheet (a
+ contour line across everything standing in it). All three are fixed
+ in the fragment stage — the profile is windowed to zero at uTop, the
+ rim by uRadius, and the alpha is broken up by noise WITH A FLOOR at
+ the ground plus a screen-space dither."""
+ out = _measure("""
+import { makeHeightFog } from './lib/atmosphere.js';
+const m = makeHeightFog({ extent: 60, top: 4 }).children[0].material;
+console.log(JSON.stringify({ vs: m.vertexShader, fs: m.fragmentShader }));
+""")
+ fs, vs = out["fs"], out["vs"]
+ assert "smoothstep(uTop * 0.45, uTop, vH)" in fs, (
+ "the height profile must reach exactly zero at uTop")
+ assert "length(vPos.xz) / uRadius" in fs, "the rim must be feathered"
+ assert "astraFbm2" in fs, "an unbroken layer is a slab"
+ assert "vH * 0.31" in fs, (
+ "the noise domain must shift with height or every sheet wears "
+ "the same blotches and the stack prints as one surface")
+ assert "float low = 0.55 + 0.90 * n;" in fs, (
+ "a flat 1.0 at the ground is where the contour bands were: the "
+ "densest sheets were the ones with no variation at all")
+ assert "astraHash21(gl_FragCoord.xy)" in fs, (
+ "and a dither over what the noise leaves, or the eye finds the "
+ "residual step anyway")
+ # The alpha is the whole effect: a fog sheet written opaque is a lid.
+ assert "clamp(a, 0.0, 1.0)" in fs
+ # fwidth is fragment-only and the util block ships in both stages;
+ # the bank must not reach for it in the vertex shader.
+ assert "fwidth" not in vs.split("void main")[1]
+ for chunk in ("logdepthbuf_pars_vertex", "logdepthbuf_vertex",
+ "fog_pars_vertex", "fog_vertex"):
+ assert f"#include <{chunk}>" in vs, chunk
+ for chunk in ("logdepthbuf_pars_fragment", "logdepthbuf_fragment",
+ "fog_pars_fragment", "fog_fragment"):
+ assert f"#include <{chunk}>" in fs, chunk
+
+
+def test_the_drift_is_seeded_and_runs_off_one_tick():
+ """Math.random is banned — a re-render must not reshuffle the bank —
+ and an un-advanced uTime is a frozen frame that reads as a broken
+ effect."""
+ out = _measure("""
+import { makeHeightFog } from './lib/atmosphere.js';
+const off = (g) => g.children[0].material.uniforms.uOffset.value.toArray();
+const a = makeHeightFog({ seed: 3 }), b = makeHeightFog({ seed: 3 });
+const c = makeHeightFog({ seed: 9 });
+const g = makeHeightFog({});
+const u = g.children[0].material.uniforms;
+const before = u.uTime.value;
+const n = g.userData.tick(7.5);
+console.log(JSON.stringify({
+ same: JSON.stringify(off(a)) === JSON.stringify(off(b)),
+ differs: JSON.stringify(off(a)) !== JSON.stringify(off(c)),
+ before, after: u.uTime.value, ticked: n,
+ extent: u.uRadius.value * 2, top: u.uTop.value,
+ density: u.uDensity.value,
+}));
+""")
+ assert out["same"], "same seed, same bank"
+ assert out["differs"], "a different seed must move the noise"
+ assert out["before"] == 0 and out["after"] == 7.5
+ assert out["ticked"] == 1
+ # The documented defaults, which the scene author is told to trust.
+ assert out["extent"] == 60 and out["top"] == 4
+ assert out["density"] == 0.75
+
+
+def test_the_bank_takes_its_colour_from_the_scene_it_stands_in():
+ """The port's real bug. A bank at a baked-in daylight white
+ (0xdce9f2) is in-scattered NOON light, and on the night rig it
+ rendered a slab of milk: the ground under it read (69,66,64) against
+ a (26,36,64) sky, the brightest thing in the frame. The colour of
+ fog is the radiance of the air, and the scene already carries it —
+ `sunRig` bakes the graded sky into `scene.environment`, so the band
+ from the horizon to 25 degrees up IS the answer, in every mood."""
+ out = _measure("""
+import * as THREE from 'three';
+import { makeHeightFog } from './lib/atmosphere.js';
+import { sunRig } from './lib/environment.js';
+const lum = (c) => 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
+function scene(elevation, fogHex) {
+ const s = new THREE.Scene();
+ const rig = sunRig({ azimuth: 215, elevation });
+ s.add(rig.sun); s.add(rig.fill);
+ s.environment = rig.envTex;
+ s.fog = new THREE.FogExp2(fogHex, 0.0035);
+ return { s, rig };
+}
+const day = scene(38, 0xcfd8e6);
+const night = scene(-20, 0x0b0f1a);
+const u = (o) => o.children[0].material.uniforms;
+const dayU = u(makeHeightFog({ scene: day.s, height: 2.2 }));
+const nightU = u(makeHeightFog({ scene: night.s, height: 2.2 }));
+const bare = u(makeHeightFog({ height: 2.2 }));
+const forced = u(makeHeightFog({ scene: night.s, color: 0xff0000 }));
+// No environment at all: the fog colour, floored by the fill.
+const noEnv = new THREE.Scene();
+noEnv.add(night.rig.fill.clone());
+noEnv.fog = new THREE.FogExp2(0x0b0f1a, 0.0035);
+const noEnvU = u(makeHeightFog({ scene: noEnv, height: 2.2 }));
+console.log(JSON.stringify({
+ dayLum: lum(dayU.uColor.value), nightLum: lum(nightU.uColor.value),
+ bareLum: lum(bare.uColor.value),
+ fogLum: lum(new THREE.Color(0x0b0f1a)),
+ noEnvLum: lum(noEnvU.uColor.value),
+ dayRB: dayU.uColor.value.r / dayU.uColor.value.b,
+ nightRB: nightU.uColor.value.r / nightU.uColor.value.b,
+ forced: forced.uColor.value.toArray(),
+ // The key light: its direction, its warmth, its strength.
+ daySun: dayU.uSunDir.value.toArray().map((v) => Math.round(v * 1000) / 1000),
+ moon: nightU.uSunDir.value.toArray().map((v) => Math.round(v * 1000) / 1000),
+ authored: night.rig.sunDir.toArray().map((v) => Math.round(v * 1000) / 1000),
+ dayAmt: dayU.uSunAmt.value, nightAmt: nightU.uSunAmt.value,
+ bareAmt: bare.uSunAmt.value,
+ dayBeam: lum(dayU.uBeam.value), nightBeam: lum(nightU.uBeam.value),
+ bareBeam: lum(bare.uBeam.value),
+ sunWarm: dayU.uSunTint.value.r / dayU.uSunTint.value.b,
+ ambCool: dayU.uAmbTint.value.r / dayU.uAmbTint.value.b,
+ overrideAmt: u(makeHeightFog({ scene: day.s, sunAmount: 0.2 }))
+ .uSunAmt.value,
+ overrideDir: u(makeHeightFog({ scene: day.s, sunDir: [0, 0, 3] }))
+ .uSunDir.value.toArray(),
+}));
+""")
+ # Twenty to one between noon and midnight air, off the same bake.
+ assert out["dayLum"] > 0.5, "day air is bright"
+ assert 0.02 < out["nightLum"] < 0.08, (
+ "night air is dark but LIT — the night mood's own fog colour "
+ f"({out['fogLum']:.4f}) is set to swallow the far field and is "
+ "seven times too dark to be the air in front of the camera")
+ assert out["nightLum"] > out["fogLum"] * 4
+ # Blue, both times, because the sky is: never the neutral white the
+ # far-field fog tint carries.
+ assert out["dayRB"] < 0.75 and out["nightRB"] < 0.75
+ assert 0.4 < out["bareLum"] < 1.0, "no scene: the day horizon"
+ # No environment to read, so the fog colour, lifted off the floor by
+ # the fill rather than used raw.
+ assert out["noEnvLum"] > out["fogLum"] * 3
+ assert out["forced"][0] > 0.9 and out["forced"][2] < 0.05, (
+ "an explicit `color` still wins outright")
+ # A SET sun is a moon rig: the light that reaches the air is above
+ # the horizon even when the authored sun is not.
+ assert out["daySun"][1] > 0.5 and out["moon"][1] > 0.5
+ assert out["authored"][1] < 0, (
+ "and the authored sunDir at night points under the ground — "
+ "reading the scene's own light is what gets this right")
+ assert out["dayAmt"] > out["nightAmt"] > 0
+ assert out["dayBeam"] > out["nightBeam"] > 0, (
+ "the beam is the key light's own radiance in the air")
+ assert out["bareAmt"] == 0 and out["bareBeam"] == 0, (
+ "with no light to read there is no in-scatter to invent")
+ assert out["sunWarm"] > 1.2, "the sun side of the bank is warm"
+ assert out["ambCool"] < 0.5, "and the shadow side takes the fill"
+ assert abs(out["overrideAmt"] - 0.2) < 1e-6
+ assert out["overrideDir"] == [0, 0, 1], "an authored sunDir is used"
+
+
+def test_the_bank_moves_with_the_light_and_up_its_own_height():
+ """One flat value over the whole bank is the tell of painted fog.
+ Real air is warm and bright looking through it toward the key light
+ (droplets scatter hard forward), cool looking away, and brighter at
+ the top of the bank than in the shadowed soil at the bottom."""
+ out = _measure("""
+import { makeHeightFog } from './lib/atmosphere.js';
+const fs = makeHeightFog({}).children[0].material.fragmentShader;
+console.log(JSON.stringify({ fs }));
+""")
+ fs = out["fs"]
+ assert "float ct = clamp(dot(V, uSunDir), -1.0, 1.0);" in fs, (
+ "the phase is a function of the VIEW ray against the light")
+ assert "hgD * sqrt(hgD)" in fs, "Henyey-Greenstein, not a cosine lobe"
+ assert ", 0.75, 2.6);" in fs, (
+ "clamped: single-scattering HG runs to 16x forward and 0.4x "
+ "back, and fog is thick enough that multiple scattering fills "
+ "the backward half in")
+ assert "mix(shadeC, litC, sunMix) + uBeam * phase" in fs, (
+ "the beam ADDS: the sky in uColor outruns the moon twenty to "
+ "one by day and two to one at night, so a multiplier tuned for "
+ "one mood is invisible in the other")
+ assert "mix(0.88, 1.25, smoothstep(0.0, 0.75, vH / uTop))" in fs, (
+ "and the bank is lit from above, so its top is the bright face")
+ assert "astraHueBreak(tint, p, 0.55, 0.30)" in fs, (
+ "patch-to-patch hue spread on the SAME field the density uses, "
+ "so the warm and cool blooms sit on the thick and thin air")
+
+
+def test_aerial_perspective_shifts_hue_at_constant_brightness():
+ """The cue is colour, not exposure. Mixing toward the raw sky colour
+ would also brighten every distant surface, which is the same lever
+ FogExp2 is already pulling — the two would fight. Tinting the
+ fragment's OWN luminance with the sky's chromaticity leaves the
+ dimming to fog, so the two compose."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchAerialPerspective } from './lib/atmosphere.js';
+const m = patchAerialPerspective(new THREE.MeshStandardMaterial(),
+ { skyColor: new THREE.Color(0xf2c17e), start: 40, end: 600 });
+const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n' +
+ '#include <fog_fragment>\\n}',
+ uniforms: {},
+};
+m.onBeforeCompile(shader);
+const s = shader.uniforms.uAerialSky.value;
+const raw = new THREE.Color(0xf2c17e);
+const lum = (c) => c.r * 0.2126 + c.g * 0.7152 + c.b * 0.0722;
+console.log(JSON.stringify({
+ skyLum: lum(s),
+ hueKept: Math.abs(s.r / s.b - raw.r / raw.b),
+ ownLum: shader.uniforms.uAerialLum.value, rawLum: lum(raw),
+ fs: shader.fragmentShader, vs: shader.vertexShader,
+ fog: m.fog !== false,
+}));
+""")
+ assert abs(out["skyLum"] - 1.0) < 1e-6, (
+ "the sky uniform is normalised to unit luminance, so "
+ "uAerialSky * L returns exactly the fragment's own brightness")
+ assert out["hueKept"] < 1e-6, "only the brightness is normalised away"
+ assert abs(out["ownLum"] - out["rawLum"]) < 1e-6, (
+ "and the brightness it was normalised BY is kept, because the "
+ "airlight lift needs the sky's real luminance")
+ fs = out["fs"]
+ # Order is the composition: albedo -> lighting -> three's fog.
+ assert fs.index("<color_fragment>") < fs.index("diffuseColor.rgb = mix")
+ assert fs.index("diffuseColor.rgb = mix") < fs.index("<fog_fragment>")
+ assert "gl_FragColor" not in fs, (
+ "writing the final colour would bypass lighting and the fog "
+ "chunk — the patch belongs on the albedo")
+ assert out["fog"], "the material's own fog flag is untouched"
+
+
+def test_airlight_lifts_the_far_field_and_never_dims_it():
+ """What pure luminance preservation cannot reach: air GLOWS, so a
+ shadowed far surface loses contrast from below, not only in hue.
+ Measured here on a ridge 70 m out — (67,88,100), a dark slab that
+ read as a hole in the frame, against (113,136,157) with the lift.
+ One-sided on purpose: pulling the other way would dim every far
+ surface brighter than the sky, which is the extinction half, and
+ three's fog is already doing that."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchAerialPerspective } from './lib/atmosphere.js';
+const m = patchAerialPerspective(new THREE.MeshStandardMaterial());
+const soft = patchAerialPerspective(new THREE.MeshStandardMaterial(),
+ { lift: 0 });
+const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+};
+m.onBeforeCompile(shader);
+console.log(JSON.stringify({
+ lift: shader.uniforms.uAerialLift.value,
+ off: soft.userData.uniforms.uAerialLift.value,
+ fs: shader.fragmentShader,
+}));
+""")
+ assert 0.2 <= out["lift"] <= 0.5, "a default that lifts, not floods"
+ assert out["off"] == 0, "`lift: 0` is the reference's pure hue shift"
+ assert ("float aerialB = aerialL\n"
+ " + uAerialLift * max(0.0, uAerialLum - aerialL);"
+ in out["fs"]), "max(0.0, ...): airlight only ever adds"
+
+
+def test_distance_is_the_same_ruler_three_uses_for_fog():
+ """three's fog measures view-space Z (`vFogDepth = -mvPosition.z`).
+ Any other measure makes the hue shift and the fog disagree about
+ where 'far' is. And <begin_vertex> runs BEFORE instancing, so an
+ InstancedMesh whose matrix is ignored gives every one of its
+ hundreds of copies the distance of the mesh origin."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchAerialPerspective } from './lib/atmosphere.js';
+const m = patchAerialPerspective(new THREE.MeshStandardMaterial());
+const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+};
+m.onBeforeCompile(shader);
+console.log(JSON.stringify({
+ vs: shader.vertexShader,
+ start: shader.uniforms.uAerialStart.value,
+ end: shader.uniforms.uAerialEnd.value,
+ k: shader.uniforms.uAerialK.value,
+}));
+""")
+ vs = out["vs"]
+ assert "vAerialDepth = -(modelViewMatrix * aerialP).z;" in vs
+ assert "#ifdef USE_INSTANCING" in vs and "instanceMatrix" in vs
+ for line in vs.splitlines():
+ if line.strip().startswith("#"):
+ assert line == line.strip(), "a directive must own its line"
+ assert out["start"] == 40 and out["end"] == 600 and out["k"] == 0.8
+
+
+def test_the_defaults_agree_with_the_scene_the_lib_ships_with():
+ """A hue shift toward a colour the sky is not is worse than none:
+ the far field would drift away from the horizon it is supposed to
+ dissolve into. With no scene to read the default sky is
+ `worldShell`'s day horizon and the ramp ends at one e-fold of that
+ mood's own fog density; with one, both come off the scene."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchAerialPerspective } from './lib/atmosphere.js';
+import { worldShell, sunRig } from './lib/environment.js';
+const { fog } = worldShell({});
+const lum = (c) => c.r * 0.2126 + c.g * 0.7152 + c.b * 0.0722;
+const compile = (m) => {
+ const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+ };
+ m.onBeforeCompile(shader);
+ return shader.uniforms;
+};
+const bare = compile(patchAerialPerspective(new THREE.MeshStandardMaterial()));
+const s = bare.uAerialSky.value;
+const h = fog.color.clone().multiplyScalar(1 / lum(fog.color));
+
+// With a scene: the scene's own fog, and its own density.
+const day = new THREE.Scene();
+const rig = sunRig({ azimuth: 215, elevation: 38 });
+day.add(rig.sun); day.add(rig.fill);
+day.environment = rig.envTex;
+day.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+const scened = compile(patchAerialPerspective(
+ new THREE.MeshStandardMaterial(), { scene: day }));
+// Night: the mood's fog is set to swallow the far field, so used raw it
+// takes every distant surface to black with it.
+const night = new THREE.Scene();
+const nrig = sunRig({ azimuth: 215, elevation: -20 });
+night.add(nrig.sun); night.add(nrig.fill);
+night.environment = nrig.envTex;
+night.fog = new THREE.FogExp2(0x0b0f1a, 0.0035);
+const dark = compile(patchAerialPerspective(
+ new THREE.MeshStandardMaterial(), { scene: night }));
+console.log(JSON.stringify({
+ dr: Math.abs(s.r - h.r), dg: Math.abs(s.g - h.g), db: Math.abs(s.b - h.b),
+ efolds: bare.uAerialEnd.value * fog.density,
+ start: bare.uAerialStart.value,
+ scenedEnd: scened.uAerialEnd.value,
+ scenedLum: scened.uAerialLum.value,
+ sceneFogLum: lum(new THREE.Color(0xcfd8e6)),
+ nightLum: dark.uAerialLum.value,
+ nightFogLum: lum(new THREE.Color(0x0b0f1a)),
+ nightRB: dark.uAerialSky.value.r / dark.uAerialSky.value.b,
+}));
+""")
+ for k in ("dr", "dg", "db"):
+ assert out[k] < 1e-6, "the default sky IS worldShell's horizon"
+ assert 0.9 < out["efolds"] < 1.3, (
+ "the shift must finish about where the day mood's FogExp2 has "
+ "taken over (1/0.0018 m), or one cue outruns the other")
+ # Nothing inside 40 m shifts: aerial perspective is a far-field cue,
+ # and shifting the foreground is what makes a scene look hazy.
+ assert out["start"] == 40
+ assert abs(out["scenedEnd"] - 1 / 0.0035) < 1e-6, (
+ "given a scene, the ramp ends at ONE e-fold of ITS fog, not of "
+ "the mood the library happens to ship with")
+ assert abs(out["scenedLum"] - out["sceneFogLum"]) < 1e-6, (
+ "and by day the scene's own fog colour is the airlight, "
+ "untouched")
+ assert out["nightLum"] > out["nightFogLum"] * 3, (
+ "at night it is floored by the radiance of the air, or the far "
+ "field crushes to a black-blue silhouette: measured (9,23,50) "
+ "under a (26,36,64) sky")
+ assert out["nightRB"] < 0.6, "and what it is floored to is sky blue"
+
+
+def test_one_program_serves_every_patched_material():
+ """three caches programs by material type plus this key, so a key
+ per material would compile the identical GLSL over and over. The
+ uniforms must still be per material, or the last call would retune
+ every surface in the scene."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchAerialPerspective } from './lib/atmosphere.js';
+const a = patchAerialPerspective(new THREE.MeshStandardMaterial(),
+ { start: 10, end: 200, strength: 0.4 });
+const b = patchAerialPerspective(new THREE.MeshStandardMaterial(),
+ { start: 80, end: 900 });
+console.log(JSON.stringify({
+ keyA: a.customProgramCacheKey(), keyB: b.customProgramCacheKey(),
+ sharedMap: a.userData.uniforms === b.userData.uniforms,
+ kA: a.userData.uniforms.uAerialK.value,
+ kB: b.userData.uniforms.uAerialK.value,
+ endA: a.userData.uniforms.uAerialEnd.value,
+ endB: b.userData.uniforms.uAerialEnd.value,
+ flagged: a.userData.astraShader === true,
+}));
+""")
+ assert out["keyA"] == out["keyB"], "identical GLSL, one program"
+ assert not out["sharedMap"], "every material keeps its own uniforms"
+ assert out["kA"] == 0.4 and out["kB"] == 0.8
+ assert out["endA"] == 200 and out["endB"] == 900
+ assert out["flagged"], "tickShaders must be able to find it"
+
+
+def test_the_environment_is_read_once_per_bake():
+ """`patchAerialPerspective` is called once per material, and a scene
+ with fifty materials would otherwise re-read a quarter of the
+ equirect fifty times. Cached on the TEXTURE, and never handed out:
+ every caller of the scene reader mutates what it gets."""
+ out = _measure("""
+import * as THREE from 'three';
+import { makeHeightFog } from './lib/atmosphere.js';
+import { sunRig } from './lib/environment.js';
+const s = new THREE.Scene();
+const rig = sunRig({ azimuth: 215, elevation: 38 });
+s.add(rig.sun); s.add(rig.fill);
+s.environment = rig.envTex;
+const first = makeHeightFog({ scene: s }).children[0]
+ .material.uniforms.uColor.value.clone();
+// A caller that mutates its own colour must not move anyone else's.
+const mine = makeHeightFog({ scene: s }).children[0].material.uniforms.uColor;
+mine.value.multiplyScalar(0.01);
+const again = makeHeightFog({ scene: s }).children[0]
+ .material.uniforms.uColor.value;
+const t0 = performance.now();
+for (let i = 0; i < 40; i++) makeHeightFog({ scene: s });
+const ms = performance.now() - t0;
+console.log(JSON.stringify({
+ stable: Math.abs(first.r - again.r) < 1e-9
+ && Math.abs(first.b - again.b) < 1e-9,
+ msPer: ms / 40,
+}));
+""")
+ assert out["stable"], "the cached radiance is cloned on the way out"
+ # 2 300 texels read and sorted per call is ~1 ms; the cache makes the
+ # whole build cheaper than one geometry.
+ assert out["msPer"] < 5
+
+
+_SCENE = """
+import * as THREE from 'three';
+import { makeHeightFog, patchAerialPerspective } from './lib/atmosphere.js';
+
+export const BOUNDS = { min: [-80, 0, -80], max: [80, 20, 80] };
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ scene.add(new THREE.HemisphereLight(0x9db8e8, 0x8a7f6a, 1.4));
+ const sun = new THREE.DirectionalLight(0xfff0d8, 5.4);
+ sun.position.set(-90, 86, -63);
+ sun.castShadow = true;
+ scene.add(sun);
+ const g = new THREE.Group();
+ const heightAt = (x, z) => Math.sin(x * 0.06) * 1.2 + Math.cos(z * 0.05);
+
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(160, 160, 40, 40),
+ new THREE.MeshStandardMaterial({ color: 0x6b7a5a }));
+ ground.rotation.x = -Math.PI / 2;
+ patchAerialPerspective(ground.material, { scene, start: 30, end: 500 });
+ g.add(ground);
+
+ // Instanced: the one case where <begin_vertex> alone would give every
+ // copy the distance of the mesh origin.
+ const posts = new THREE.InstancedMesh(
+ new THREE.CylinderGeometry(0.2, 0.2, 3, 8),
+ new THREE.MeshStandardMaterial({ color: 0x8a7f6a }), 12);
+ const m4 = new THREE.Matrix4();
+ for (let i = 0; i < 12; i++) {
+ m4.makeTranslation(i * 4 - 22, 1.5, -6);
+ posts.setMatrixAt(i, m4);
+ }
+ patchAerialPerspective(posts.material, { scene, strength: 0.6 });
+ g.add(posts);
+
+ // Both ways in: the bank reads the scene, and an authored sunDir
+ // (as a plain array, which is what a scene author has to hand)
+ // overrides it.
+ const fog = makeHeightFog({ scene, extent: 60, top: 4, heightAt, seed: 4 });
+ const authored = makeHeightFog({ extent: 40, height: 2, seed: 5,
+ sunDir: [0.4, 0.7, -0.5], sunAmount: 0.9 });
+ authored.position.set(60, 0, 0);
+ g.add(fog, authored);
+ scene.add(g);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [18, 6, 24], lookAt: [0, 2, 0] }],
+ update(t) { fog.userData.tick(t); authored.userData.tick(t); },
+ };
+}
+"""
+
+
+def test_both_exports_compile_on_the_gpu():
+ """The one thing no source assertion can answer. Runs the same
+ wrapper the authoring agent runs, on the renderer flags the
+ framework renders with: the custom attribute, the height varying,
+ the instancing ifdef and the patched standard material all have to
+ survive three's assembly."""
+ code, out = compile_scene(_SCENE, ("atmosphere.js",))
+ assert code == 0, out
+ assert "ERROR" not in out, out
+ report = json.loads(out.strip().splitlines()[-1])
+ assert report["ok"] and report["errors"] == [], report
+ # Two banks (one ShaderMaterial each) and two patched built-ins.
+ assert report["compile"]["custom_materials"] >= 4, report
+ assert report["compile"]["gpu"], report
+ # A transparent layer without the fog chunks keeps full contrast
+ # while the world recedes — the sticker look, on the one object in
+ # the scene whose whole job is to recede.
+ assert "no fog chunks" not in out
diff --git a/harness/tests/scene_runtime/lib/test_building.py b/harness/tests/scene_runtime/lib/test_building.py
new file mode 100644
index 00000000..7cce63ef
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_building.py
@@ -0,0 +1,792 @@
+"""building.js — facades ship with real openings, because a painted window is a box.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_building_lib.py). Their geometry claims are pinned exactly as they
+were: real gaps at window height, a cornice that overhangs, a dielectric
+glazing, the origin/size contract, a city-affordable triangle count, and the
+casement's recessed pane, projecting sill, hinged shutters and lit card.
+
+Nothing here asserts THEIR renderer contract. What the port added instead are
+the four things the reference never measured and our showcase render caught on
+this host:
+
+* ``cottage()`` merged its window frames, sills and door surround into the
+ ROOF mesh (``trimMat`` was built and then discarded with ``void trimMat``),
+ so every cottage window was a terracotta rectangle painted on a white wall;
+* its panes sat INSIDE the solid wall box, invisible — which also meant the
+ ``lit`` path it exists for produced glow nothing could see at night;
+* its gable end walls were built upside down (``rotateX(+PI/2)`` puts the
+ 3-gon's apex at y = -1), so two corners stuck out through the roof slopes;
+* ``block({lit})`` made the whole 22 m interior shell emissive, lighting every
+ window in the building from one box — ``lit: 0.4`` still came out a lantern.
+
+building.js builds no custom shaders (every material is a stock
+Standard/Physical), so the reference's ``scene_check`` GPU cases would prove
+nothing here; the real compile is covered by the showcase render and by the
+windows.js port, which patches these meshes.
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("building.js", "materials.js")
+
+_PRELUDE = """
+import * as THREE from 'three';
+import { block, cottage, tower, casement, roofClutter, cityFabric }
+ from './lib/building.js';
+
+const mk = (s0) => { let s = s0;
+ return () => (s = (s * 16807) % 2147483647) / 2147483647; };
+
+/** Named parts of a built asset: triangles, world box, material facts. */
+function census(root) {
+ root.updateMatrixWorld(true);
+ const parts = {};
+ let tris = 0;
+ root.traverse((o) => {
+ if (!o.isMesh) return;
+ const n = o.geometry.index ? o.geometry.index.count / 3
+ : o.geometry.attributes.position.count / 3;
+ tris += n;
+ const b = new THREE.Box3().setFromObject(o);
+ const c = o.material.color ? o.material.color.getHex() : 0;
+ parts[o.name] = {
+ tris: n,
+ box: [b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z],
+ material: o.material.type,
+ metalness: o.material.metalness,
+ transparent: !!o.material.transparent,
+ albedo: Math.max(c >> 16 & 255, c >> 8 & 255, c & 255) / 255,
+ emissive: o.material.emissive ? o.material.emissive.getHex() : null,
+ emissiveIntensity: o.material.emissiveIntensity,
+ };
+ });
+ return { parts, tris };
+}
+
+/** Name of the first mesh a ray meets, or null. */
+function firstHit(root, from, dir) {
+ const meshes = [];
+ root.traverse((o) => { if (o.isMesh) meshes.push(o); });
+ const hit = new THREE.Raycaster(
+ new THREE.Vector3().fromArray(from),
+ new THREE.Vector3().fromArray(dir).normalize(), 0, 400)
+ .intersectObjects(meshes, true);
+ return hit.length ? hit[0].object.name : null;
+}
+
+/** Texels per metre per triangle: p10/p50/p90 over one merged mesh. */
+function texelDensity(geo) {
+ const pos = geo.attributes.position, uv = geo.attributes.uv;
+ const idx = geo.index;
+ const n = idx ? idx.count : pos.count;
+ const A = new THREE.Vector3(), B = new THREE.Vector3(), C = new THREE.Vector3();
+ const dens = [];
+ for (let i = 0; i < n; i += 3) {
+ const a = idx ? idx.getX(i) : i;
+ const b = idx ? idx.getX(i + 1) : i + 1;
+ const c = idx ? idx.getX(i + 2) : i + 2;
+ A.fromBufferAttribute(pos, a);
+ B.fromBufferAttribute(pos, b);
+ C.fromBufferAttribute(pos, c);
+ const wa = B.clone().sub(A).cross(C.clone().sub(A)).length() * 0.5;
+ const ua = Math.abs((uv.getX(b) - uv.getX(a)) * (uv.getY(c) - uv.getY(a))
+ - (uv.getX(c) - uv.getX(a)) * (uv.getY(b) - uv.getY(a)))
+ * 0.5;
+ if (wa > 1e-6 && ua > 1e-12) dens.push(Math.sqrt(ua / wa));
+ }
+ dens.sort((p, q) => p - q);
+ const q = (f) => dens[Math.floor(f * (dens.length - 1))];
+ return { p10: q(0.1), p50: q(0.5), p90: q(0.9), n: dens.length };
+}
+"""
+
+
+def _measure(script: str) -> dict:
+ return measure(_PRELUDE + script, _LIBS)
+
+
+# --------------------------------------------------------------- the block
+
[email protected](scope="module")
+def facade() -> dict:
+ """One node launch, shared by every test that reads a plain block."""
+ return _measure("""
+const b = block({ w: 14, d: 12, h: 24, rand: mk(11), style: 'brick' });
+const { parts, tris } = census(b);
+const whole = new THREE.Box3().setFromObject(b);
+
+// Sweep rays horizontally across the facade at window height. On a solid
+// box EVERY ray hits the wall; with real openings the ones aimed at a bay
+// pass the wall plane and land on the dark reveal behind.
+const wallMesh = [];
+b.traverse((o) => { if (o.isMesh && o.name === 'Walls') wallMesh.push(o); });
+let clear = 0, fired = 0;
+for (let i = 0; i < 60; i++) {
+ const x = -6.6 + (13.2 * i) / 59;
+ const ray = new THREE.Raycaster(
+ new THREE.Vector3(x, 14.6, 40), new THREE.Vector3(0, 0, -1), 0, 200);
+ fired++;
+ if (ray.intersectObjects(wallMesh, true).length === 0) clear++;
+}
+
+// Every distinct wall colour a STREET of one style produces. One rand
+// stream, the way cityFabric feeds a district -- a caller who seeds a
+// fresh Lehmer PRNG per building gets a near-zero first draw from every
+// one of them and lands them all in the same bucket.
+const tints = new Set();
+const street = mk(11);
+for (let i = 0; i < 12; i++) {
+ block({ w: 14, d: 12, h: 20, style: 'brick', rand: street })
+ .traverse((o) => { if (o.isMesh && o.name === 'Walls')
+ tints.add(o.material.color.getHex()); });
+}
+// The brightest non-emissive albedo anywhere in the module.
+let peak = 0, peakName = '';
+for (const style of ['brick', 'masonry', 'stone', 'glass']) {
+ for (const s of [3, 11, 29, 77]) {
+ block({ w: 14, d: 12, h: 20, style, rand: mk(s) }).traverse((o) => {
+ if (!o.isMesh || o.material.transparent) return;
+ const c = o.material.color.getHex();
+ const a = Math.max(c >> 16 & 255, c >> 8 & 255, c & 255) / 255;
+ if (a > peak) { peak = a; peakName = style + '/' + o.name; }
+ });
+ }
+}
+for (const s of [3, 11, 29]) {
+ cottage({ rand: mk(s), dormers: 1 }).traverse((o) => {
+ if (!o.isMesh || o.material.transparent) return;
+ const c = o.material.color.getHex();
+ const a = Math.max(c >> 16 & 255, c >> 8 & 255, c & 255) / 255;
+ if (a > peak) { peak = a; peakName = 'cottage/' + o.name; }
+ });
+}
+
+const walls = b.getObjectByName('Walls');
+console.log(JSON.stringify({
+ names: Object.keys(parts).sort(),
+ tris,
+ height: whole.max.y - whole.min.y,
+ baseY: whole.min.y,
+ width: whole.max.x - whole.min.x,
+ trimOverhangsWall: parts.Trim.box[3] - parts.Walls.box[3],
+ glazingType: parts.Glazing.material,
+ glazingMetalness: parts.Glazing.metalness,
+ revealAlbedo: parts.Reveals.albedo,
+ revealEmissive: parts.Reveals.emissive,
+ floors: b.userData.floors,
+ forward: b.userData.forward,
+ clearFraction: clear / fired,
+ wallBox: parts.Walls.box,
+ distinctTints: tints.size,
+ peakAlbedo: peak, peakName,
+ density: texelDensity(walls.geometry),
+}));
+""")
+
+
+def test_a_facade_has_walls_trim_glazing_and_a_dark_interior(facade):
+ """Four named parts, because the complaints name four things.
+
+ Unlit, the two glazing batches collapse to whichever ones drew — the
+ part names an agent (and mirror.js's glazeFacade) targets are stable.
+ """
+ m = facade
+ for part in ("Walls", "Trim", "Glazing", "Reveals"):
+ assert part in m["names"], (part, m["names"])
+ assert not [n for n in m["names"] if n.startswith("LitRooms")], m["names"]
+
+
+def test_openings_are_real_gaps_not_painted_on(facade):
+ """A ray through a window bay must miss the wall.
+
+ This is the whole claim of the module. A textured box passes every other
+ check here and still reads as a box in silhouette and shadow.
+ """
+ m = facade
+ assert m["clearFraction"] > 0.35, (
+ f"only {m['clearFraction']:.0%} of rays across the facade at window "
+ "height passed the wall -- the openings are not real (a solid box "
+ "scores 0%)")
+
+
+def test_the_roofline_and_base_are_not_flush_with_the_wall(facade):
+ """"Trim and mouldings" is 15% of the building complaints."""
+ m = facade
+ assert m["trimOverhangsWall"] > 0.1, (
+ f"cornice does not project past the wall: {m['trimOverhangsWall']}")
+
+
+def test_glazing_is_a_dielectric(facade):
+ """Matte glass towers are a named verdict; metal glass is wrong physics."""
+ m = facade
+ assert m["glazingType"] == "MeshPhysicalMaterial", m["glazingType"]
+ assert m["glazingMetalness"] == 0, m["glazingMetalness"]
+
+
+def test_it_rests_on_zero_at_the_requested_size(facade):
+ """Same origin contract as every other asset, so `seat()` works."""
+ m = facade
+ assert abs(m["baseY"]) < 0.01, m["baseY"]
+ assert abs(m["height"] - 24) < 1.6, m["height"]
+ # `w` is the WALL width; the bbox is legitimately wider because the
+ # cornice projects past it -- that projection is the point.
+ wall_w = m["wallBox"][3] - m["wallBox"][0]
+ assert abs(wall_w - 14) < 1.0, wall_w
+ assert m["width"] - wall_w < 2.0, (m["width"], wall_w)
+ assert m["forward"] == "-Z"
+ assert m["floors"] >= 6, m["floors"]
+
+
+def test_a_city_can_afford_it(facade):
+ """The whole scene has a ~600k triangle budget.
+
+ A 12-cliff run shipped 6.7M tris and crawled; a block a city places by
+ the hundred stays cheap even before instancing merges it.
+ """
+ m = facade
+ assert m["tris"] < 4000, f"{m['tris']} triangles for one block"
+
+
+def test_the_reveal_behind_a_window_is_dark_but_not_a_hole(facade):
+ """0x14161a is 0.08 albedo: under our ACES/exposure-1.0 pipeline with no
+ post chain it rendered as pure black, and a black rectangle reads as a
+ hole punched in the wall rather than a room behind glass."""
+ m = facade
+ assert 0.1 < m["revealAlbedo"] < 0.28, m["revealAlbedo"]
+ assert m["revealEmissive"] == 0, (
+ "an unlit block must not glow anywhere", m["revealEmissive"])
+
+
+def test_a_street_of_blocks_is_not_one_colour(facade):
+ """Seeded blocks draw a batch tint, so a district stops reading as one
+ stamped asset. Bucketed, so a hundred blocks still cost a few materials."""
+ m = facade
+ assert m["distinctTints"] >= 3, m["distinctTints"]
+ assert m["distinctTints"] <= 9, ("tint buckets leaked", m["distinctTints"])
+
+
+def test_no_wall_is_brighter_than_a_lit_albedo(facade):
+ """Non-emissive albedos stay under 0.8 sRGB. Plaster and travertine ship
+ near 0.92, which at exposure 1.0 with no post chain lands a whole facade
+ at the top of the range -- a white card no shadow can shape."""
+ m = facade
+ assert m["peakAlbedo"] <= 0.80, (m["peakName"], m["peakAlbedo"])
+
+
+def test_one_texel_scale_across_the_whole_facade(facade):
+ """three gives every box face a full 0..1 UV whatever it measures, so one
+ merged facade stretched a brick tile over a 14 m wall and squeezed it onto
+ a 0.34 m mullion -- the piers rendered as vertical woodgrain stripes."""
+ d = facade["density"]
+ assert d["n"] > 200, d
+ assert d["p90"] / d["p10"] < 1.05, (
+ f"texel density varies {d['p90'] / d['p10']:.1f}x across the walls", d)
+
+
[email protected](scope="module")
+def lit_block() -> dict:
+ """One node launch for the night facade."""
+ return _measure("""
+const b = block({ w: 16, d: 14, h: 26, style: 'masonry', lit: 0.45,
+ rand: mk(5) });
+const { parts } = census(b);
+const glow = [];
+b.traverse((o) => {
+ if (o.isMesh && o.material.emissive && o.material.emissiveIntensity > 0
+ && o.material.emissive.getHex() !== 0) {
+ glow.push({ name: o.name, emissive: o.material.emissive.getHex(),
+ intensity: o.material.emissiveIntensity,
+ tris: o.geometry.index ? o.geometry.index.count / 3
+ : o.geometry.attributes.position.count / 3 });
+ }
+});
+// Panes are boxes: 12 triangles each, lit or dark. The ratio IS the
+// `lit` fraction the caller asked for -- unless the whole shell glows.
+const litPanes = glow.reduce((a, g) => a + g.tris, 0) / 12;
+let darkPanes = 0;
+b.traverse((o) => { if (o.isMesh && o.name.startsWith('Glazing'))
+ darkPanes += (o.geometry.index ? o.geometry.index.count / 3
+ : o.geometry.attributes.position.count / 3) / 12; });
+console.log(JSON.stringify({
+ names: Object.keys(parts).sort(),
+ revealEmissive: parts.Reveals.emissive,
+ revealTris: parts.Reveals.tris,
+ glow,
+ litPanes, darkPanes,
+ warm: glow.filter((g) => (g.emissive >> 16 & 255) > (g.emissive & 255)).length,
+ cool: glow.filter((g) => (g.emissive & 255) > (g.emissive >> 16 & 255)).length,
+}));
+""")
+
+
+def test_a_lit_block_lights_windows_not_the_whole_shell(lit_block):
+ """The reveal shell is ONE box spanning the building. Pushing lit panes
+ onto it and making it emissive lit every window at once, so `lit: 0.45`
+ rendered as a solid glowing lantern with no dark windows at all."""
+ m = lit_block
+ assert m["revealEmissive"] == 0, (
+ "the interior shell itself glows -- every window in the building "
+ "lights from one box")
+ assert all(g["name"].startswith("LitRooms") for g in m["glow"]), m["glow"]
+ # `lit: 0.45` has to mean 45% of the windows, not the building.
+ frac = m["litPanes"] / (m["litPanes"] + m["darkPanes"])
+ assert 0.25 < frac < 0.65, (frac, m["litPanes"], m["darkPanes"])
+ assert m["darkPanes"] >= 8, ("no window stayed dark", m["darkPanes"])
+
+
+def test_lit_windows_split_into_room_classes(lit_block):
+ """A night facade on one emissive material is a slab. Real windows split
+ by room -- tungsten, warm white, the odd cool kitchen -- and that split
+ is the whole night read."""
+ m = lit_block
+ hexes = {g["emissive"] for g in m["glow"]}
+ assert len(hexes) >= 2, ("one emissive colour for every lit window", m["glow"])
+ assert m["warm"] >= 1 and m["cool"] >= 1, m["glow"]
+
+
+def test_lit_windows_stay_in_the_bloom_friendly_band(lit_block):
+ """Peak 1.5-4, never 20: an emissive that clips is a white hole with no
+ colour left in it, and nothing downstream can grade it back."""
+ m = lit_block
+ for g in m["glow"]:
+ assert 1.0 <= g["intensity"] <= 4.0, g
+
+
+def test_lit_windows_are_not_matched_by_the_mirror_sweep(lit_block):
+ """mirror.js `glazeFacade` retargets every `/glaz|pane/i` mesh and
+ documents that lit windows are left glowing. Naming the lit cards
+ `LitGlazing` (as cottage did) walked them straight into that sweep."""
+ m = lit_block
+ import re
+ for name in m["names"]:
+ if re.search(r"glaz|pane", name, re.I):
+ assert not name.startswith("Lit"), name
+
+
+# ------------------------------------------------------------ the casement
+
[email protected](scope="module")
+def casement_probe() -> dict:
+ """One node launch, shared by every casement test."""
+ return _measure("""
+const c = casement({ w: 1.2, h: 1.5, shutters: true, rand: mk(7) });
+const { parts, tris } = census(c);
+
+let litBacking = null;
+casement({ lit: true, rand: mk(3) }).traverse((o) => {
+ if (o.isMesh && o.name === 'Backing') litBacking = {
+ emissive: o.material.emissive.getHex(),
+ emissiveIntensity: o.material.emissiveIntensity,
+ };
+});
+
+const countGlow = (g) => { let n = 0; g.traverse((o) => {
+ if (o.isMesh && o.material.emissive && o.material.emissiveIntensity > 0
+ && o.material.emissive.getHex() !== 0) n++; }); return n; };
+
+const sl = parts.ShutterL.box;
+console.log(JSON.stringify({
+ names: Object.keys(parts).sort(),
+ tris,
+ frameFrontZ: parts.Frame.box[2],
+ paneRecess: parts.Pane.box[2] - parts.Frame.box[2],
+ paneBehindWall: parts.Pane.box[2],
+ sillFrontZ: parts.Sill.box[2],
+ shutterAngleDeg: Math.atan2(sl[5] - sl[2], sl[3] - sl[0]) * 180 / Math.PI,
+ shutterTris: parts.ShutterL.tris,
+ shutterMaxZ: Math.max(sl[5], parts.ShutterR.box[5]),
+ backingEmissive: parts.Backing.emissive,
+ backingAlbedo: parts.Backing.albedo,
+ litBacking,
+ forward: c.userData.forward,
+ cottageGlowDark: countGlow(cottage({ rand: mk(11) })),
+ cottageGlowLit: countGlow(cottage({ lit: 1, rand: mk(11) })),
+}));
+""")
+
+
+def test_casement_pane_is_recessed_behind_a_proud_frame(casement_probe):
+ """The whole claim: depth, not a flush quad.
+
+ Audited failures were flush single quads; good scenes recess the pane
+ >=0.08 m behind a proud frame, measured by world-Z.
+ """
+ m = casement_probe
+ assert m["frameFrontZ"] < -0.02, (
+ f"frame front at z={m['frameFrontZ']} is not proud of the wall")
+ assert m["paneRecess"] >= 0.08, (
+ f"pane only {m['paneRecess']:.3f} m behind the frame front -- "
+ "that is the flush-quad failure this function exists to kill")
+ assert m["paneBehindWall"] > 0, (
+ f"pane at z={m['paneBehindWall']} floats OUTSIDE the wall")
+
+
+def test_casement_sill_projects_past_the_frame(casement_probe):
+ """A sill that does not project is a paint stripe."""
+ m = casement_probe
+ assert m["sillFrontZ"] < m["frameFrontZ"], (
+ f"sill front {m['sillFrontZ']} does not clear the frame "
+ f"front {m['frameFrontZ']}")
+
+
+def test_casement_shutters_hinge_open_off_the_wall(casement_probe):
+ """Louvered panels at ~55 deg, the best audited scene's form.
+
+ World-bbox angle: ~0 deg is flat on the wall, ~90 straight out; the
+ hinge swing must land between, on the OUTSIDE of the wall.
+ """
+ m = casement_probe
+ assert 35 < m["shutterAngleDeg"] < 75, (
+ f"shutter plane at {m['shutterAngleDeg']:.0f} deg to the wall")
+ assert m["shutterMaxZ"] < 0.02, (
+ f"a shutter reaches z={m['shutterMaxZ']} -- through the wall")
+ assert m["shutterTris"] >= 60, (
+ f"{m['shutterTris']} tris is a flat panel, not louvers")
+
+
+def test_casement_lit_swaps_in_the_warm_card(casement_probe):
+ """`lit: true` must glow warm; unlit must stay a dark interior.
+
+ One window is one room, so it draws a WARM class only -- a lone blue
+ window in a wall reads as a fault, not as a fluorescent kitchen.
+ """
+ m = casement_probe
+ assert m["backingEmissive"] == 0, m["backingEmissive"]
+ assert 0.1 < m["backingAlbedo"] < 0.28, m["backingAlbedo"]
+ lit = m["litBacking"]
+ assert 1 < lit["emissiveIntensity"] <= 4, lit
+ assert (lit["emissive"] >> 16 & 0xFF) > (lit["emissive"] & 0xFF), (
+ f"lit backing 0x{lit['emissive']:06x} is not warm")
+
+
+def test_cottage_lit_path_glows(casement_probe):
+ """5/5 failing dusk scenes had zero window emissive; cottage() was the
+ only building silhouette with no lit path at all."""
+ m = casement_probe
+ assert m["cottageGlowDark"] == 0, m["cottageGlowDark"]
+ assert m["cottageGlowLit"] >= 1, (
+ "cottage({lit: 1}) produced no emissive mesh")
+
+
+def test_casement_parts_and_budget(casement_probe):
+ """Named parts a fix agent can target, at a cost a village affords."""
+ m = casement_probe
+ for part in ("Frame", "Sill", "Pane", "Backing", "ShutterL", "ShutterR"):
+ assert part in m["names"], (part, m["names"])
+ assert m["tris"] < 900, f"{m['tris']} triangles for one window"
+ assert m["forward"] == "-Z"
+
+
+# ---------------------------------------------------- the interior casement
+
[email protected](scope="module")
+def interior() -> dict:
+ """One node launch, shared by every interior-casement test."""
+ return _measure("""
+const c = casement({ w: 1.2, h: 1.5, interior: true });
+const { parts } = census(c);
+
+// From the ROOM (+Z), the first thing a ray hits must be the frame or the
+// pane. If the daylight card wins, it is floating INSIDE the room instead
+// of standing in for the sky outside the glass.
+const firstHits = [0, 0.3, -0.45].map(
+ (x) => firstHit(c, [x, 0.2, 6], [0, 0, -1]));
+
+let nightCard = null;
+casement({ interior: true, view: 'night' }).traverse((o) => {
+ if (o.isMesh && o.name === 'Daylight') nightCard = {
+ emissive: o.material.emissive.getHex(),
+ emissiveIntensity: o.material.emissiveIntensity,
+ };
+});
+
+console.log(JSON.stringify({
+ names: Object.keys(parts).sort(),
+ firstHits,
+ cardMaxZ: parts.Daylight.box[5],
+ paneMinZ: parts.Pane.box[2],
+ frameMaxZ: parts.Frame.box[5],
+ sillMaxZ: parts.Sill.box[5],
+ cardEmissive: parts.Daylight.emissive,
+ cardIntensity: parts.Daylight.emissiveIntensity,
+ nightCard,
+ forward: c.userData.forward,
+}));
+""")
+
+
+def test_interior_casement_puts_daylight_outside_the_pane(interior):
+ """The whole claim: a lit opening with depth, not a black hole.
+
+ The emissive card must sit BEHIND the pane (lower Z, outside the room);
+ a ray from the room must hit frame or pane, never the card.
+ """
+ m = interior
+ for hit in m["firstHits"]:
+ assert hit in ("Frame", "Pane"), m["firstHits"]
+ assert m["cardMaxZ"] < m["paneMinZ"], (
+ f"daylight card front z={m['cardMaxZ']} is not behind the pane "
+ f"back z={m['paneMinZ']}")
+
+
+def test_interior_casement_frame_and_sill_face_the_room(interior):
+ """The reveal is on the +Z (room) side, and the stool clears it."""
+ m = interior
+ assert m["frameMaxZ"] > 0.02, (
+ f"frame front at z={m['frameMaxZ']} does not stand into the room")
+ assert m["sillMaxZ"] > m["frameMaxZ"], (
+ f"sill front {m['sillMaxZ']} does not project past the frame "
+ f"front {m['frameMaxZ']}")
+ assert m["forward"] == "+Z", m["forward"]
+
+
+def test_interior_casement_day_card_is_bright_and_cool(interior):
+ """Blown-out sky through glass: cool 0xdfeaff family, intensity >= 1.5 --
+ a dim or warm card reads as a lamp, not daylight."""
+ m = interior
+ assert 1.5 <= m["cardIntensity"] <= 4, m["cardIntensity"]
+ e = m["cardEmissive"]
+ assert (e & 0xFF) >= (e >> 16 & 0xFF), f"day card 0x{e:06x} is not cool"
+
+
+def test_interior_casement_night_swaps_to_deep_blue(interior):
+ """After dark the opening must still read, at LOW emissive."""
+ m = interior
+ night = m["nightCard"]
+ assert night is not None, "view:'night' lost the Daylight card"
+ assert night["emissiveIntensity"] < 1, night
+ e = night["emissive"]
+ assert (e & 0xFF) > (e >> 16 & 0xFF), f"night card 0x{e:06x} not blue"
+ assert e < 0x404060, f"night card 0x{e:06x} is not deep"
+
+
+# ------------------------------------------------------------- the cottage
+
[email protected](scope="module")
+def cot() -> dict:
+ """One node launch, shared by every cottage test."""
+ return _measure("""
+const W = 8, D = 7, H = 3.2, PITCH = 0.85 * W / 2;
+const c = cottage({ w: W, d: D, h: H, dormers: 2, roof: 'gable',
+ rand: mk(23) });
+const { parts, tris } = census(c);
+const whole = new THREE.Box3().setFromObject(c);
+
+// A bay window on the -Z gable wall, aimed off its mullion cross: the
+// first thing seen from outside must be GLASS. A frame box filled solid
+// (or a pane buried inside the wall) answers 'Trim' or 'Walls'.
+const bayX = -W / 2 + (W / Math.max(1, Math.round(W / 2.6))) * 0.5;
+const gableWindow = firstHit(c, [bayX + 0.2, H * 0.55 + 0.2, -30], [0, 0, 1]);
+// The same on an eaves (+-X) wall, which carried no openings at all.
+// Off the mullion cross in BOTH axes, or the ray meets a glazing bar.
+const eavesZ = -D / 2 + (D / Math.max(1, Math.round(D / 2.8))) * 0.5;
+const eavesWindow = firstHit(c, [-30, H * 0.55 + 0.2, eavesZ + 0.2], [1, 0, 0]);
+// And a dormer, which sat buried INSIDE the roof mass.
+const dormerZ = -D / 2 + (D / 3) * 1;
+const dormerHit = firstHit(c, [-30, H + PITCH * 0.42, dormerZ], [1, 0, 0]);
+
+// WHICH WAY UP IS THE GABLE. Apex up: the triangle is narrow near the
+// ridge and wide at the eaves. Fire along Z at the gable plane, against
+// the WALLS mesh only, high in the gable and low in it.
+const wallsOnly = new THREE.Group();
+c.traverse((o) => { if (o.isMesh && o.name === 'Walls') wallsOnly.add(o.clone()); });
+const gableAt = (frac) => firstHit(
+ wallsOnly, [W * 0.35, H + PITCH * frac, 40], [0, 0, -1]);
+
+const glazing = c.getObjectByName('Glazing');
+const gb = new THREE.Box3().setFromObject(glazing);
+
+console.log(JSON.stringify({
+ names: Object.keys(parts).sort(),
+ tris,
+ baseY: whole.min.y,
+ ridgeY: c.userData.ridgeY,
+ topY: whole.max.y,
+ forward: c.userData.forward,
+ gableWindow, eavesWindow, dormerHit,
+ gableHigh: gableAt(0.75), gableLow: gableAt(0.15),
+ wallsMaxX: parts.Walls.box[3],
+ glazingFrontZ: gb.min.z,
+ roofColor: parts.Roof.albedo,
+ trimIsNotRoof:
+ c.getObjectByName('Trim').material.uuid
+ !== c.getObjectByName('Roof').material.uuid,
+ chimney: !!parts.Chimney,
+ chimneyIsNotWall: parts.Chimney
+ ? c.getObjectByName('Chimney').material.uuid
+ !== c.getObjectByName('Walls').material.uuid : null,
+ litNames: Object.keys(census(cottage({ w: W, d: D, h: H, dormers: 2,
+ lit: 1, rand: mk(23) })).parts).sort(),
+}));
+""")
+
+
+def test_cottage_window_is_glass_not_a_painted_slab(cot):
+ """The frame was a SOLID box covering the whole opening and the pane sat
+ inside the wall behind it, so every cottage window rendered as an opaque
+ rectangle in the roof's terracotta -- the flat-facade complaint itself."""
+ m = cot
+ assert m["gableWindow"] == "Glazing", (
+ f"looking into a bay from outside hits '{m['gableWindow']}'")
+ assert m["glazingFrontZ"] < -3.5, (
+ "the pane is buried inside the wall box", m["glazingFrontZ"])
+
+
+def test_cottage_has_openings_on_every_elevation(cot):
+ """The eaves (+-X) walls had no windows at all: turned any way but one, a
+ cottage showed a blank white elevation to the camera."""
+ m = cot
+ assert m["eavesWindow"] == "Glazing", m["eavesWindow"]
+
+
+def test_cottage_dormers_sit_on_the_slope_they_open_through(cot):
+ """The ridge runs along Z, so the slopes face +-X; dormers spread along X
+ at one Z were boxes buried inside the roof mass and rendered as nothing."""
+ m = cot
+ assert m["dormerHit"] in ("Glazing", "Trim"), (
+ f"a ray at dormer height meets '{m['dormerHit']}' first")
+
+
+def test_cottage_gable_ends_are_apex_up(cot):
+ """three's first radial vertex is at +Z, so `rotateX(+PI/2)` puts the
+ 3-gon's APEX at y=-1 and a flat edge at +0.5: every gable shipped upside
+ down, its two top corners poking out through the roof as white wings.
+ A bbox sees the same triangle either way, so this measures the shape."""
+ m = cot
+ assert m["gableLow"] == "Walls", (
+ "no gable wall low down: the end is open", m["gableLow"])
+ assert m["gableHigh"] is None, (
+ "the gable is still wide near the ridge -- it is upside down "
+ f"({m['gableHigh']})")
+
+
+def test_cottage_joinery_is_not_roof_tile(cot):
+ """`trimMat` was built and then discarded (`void trimMat`) while the
+ frames, sills and door surround were merged into the ROOF mesh."""
+ m = cot
+ assert m["trimIsNotRoof"], "the joinery still shares the roof material"
+ assert "Trim" in m["names"] and "Door" in m["names"], m["names"]
+ assert m["chimney"] and m["chimneyIsNotWall"], (
+ "the stack is limewash, not masonry", m["names"])
+
+
+def test_cottage_keeps_its_origin_and_silhouette(cot):
+ """Rests on y=0, faces -Z, and the roof's high point is the ridge."""
+ m = cot
+ assert abs(m["baseY"]) < 0.01, m["baseY"]
+ assert m["forward"] == "-Z"
+ assert abs(m["topY"] - m["ridgeY"]) < 1.4, (m["topY"], m["ridgeY"])
+
+
+def test_a_village_can_afford_a_cottage(cot):
+ """Real openings on four elevations plus two dormers, still cheap enough
+ to place by the dozen."""
+ m = cot
+ assert m["tris"] < 2600, f"{m['tris']} triangles for one cottage"
+
+
+def test_cottage_lit_rooms_are_their_own_meshes(cot):
+ """Its lit panes used to be named `LitGlazing`, which walks straight into
+ mirror.js `glazeFacade`'s `/glaz|pane/i` sweep."""
+ m = cot
+ lit = [n for n in m["litNames"] if n.startswith("LitRooms")]
+ assert lit, m["litNames"]
+ assert not [n for n in m["litNames"] if "Glaz" in n and n.startswith("Lit")]
+
+
+# ------------------------------------------------- tower, clutter, district
+
+def test_a_tower_steps_in_as_it_rises():
+ """Towers SET BACK; a stack of equal slabs is a layer cake, and each
+ tier stays a `block()` so it keeps real openings."""
+ out = _measure("""
+const t = tower({ w: 22, d: 20, h: 90, tiers: 3, rand: mk(9) });
+t.updateMatrixWorld(true);
+const tiers = [];
+for (let i = 1; i <= 3; i++) {
+ const g = t.getObjectByName('Tier' + i);
+ const b = new THREE.Box3().setFromObject(g);
+ tiers.push({ y: b.min.y, top: b.max.y, w: b.max.x - b.min.x,
+ glazed: !!g.getObjectByName('Glazing') });
+}
+const whole = new THREE.Box3().setFromObject(t);
+console.log(JSON.stringify({ tiers, baseY: whole.min.y,
+ height: whole.max.y - whole.min.y, crown: !!t.getObjectByName('Crown') }));
+""")
+ tiers = out["tiers"]
+ assert abs(out["baseY"]) < 0.01, out["baseY"]
+ for lo, hi in zip(tiers, tiers[1:], strict=False):
+ assert hi["w"] < lo["w"] * 0.95, ("a tier did not step in", tiers)
+ assert hi["y"] >= lo["top"] - 1.5, ("a tier floats", tiers)
+ # Lower tiers are taller: the real setback ratio is roughly halving.
+ assert (lo["top"] - lo["y"]) > (hi["top"] - hi["y"]), tiers
+ assert all(t["glazed"] for t in tiers), tiers
+ assert out["crown"]
+
+
+def test_roof_clutter_lands_on_the_roof_and_varies():
+ """A bare flat roof is the most visible emptiness in an aerial shot after
+ the ground plane, and three identical grey boxes on one axis read as a
+ copy rather than as plant replaced piecemeal over decades."""
+ out = _measure("""
+const b = block({ w: 18, d: 16, h: 20, rand: mk(4) });
+b.updateMatrixWorld(true);
+const roofY = new THREE.Box3().setFromObject(b).max.y;
+roofClutter(b, { rand: mk(8), tanks: 1, units: 4 });
+b.updateMatrixWorld(true);
+const g = b.getObjectByName('RoofClutter');
+const box = new THREE.Box3().setFromObject(g);
+const yaws = new Set(), colors = new Set();
+let shadows = true;
+g.traverse((o) => { if (o.isMesh) {
+ yaws.add(o.rotation.y.toFixed(3));
+ colors.add(o.material.color.getHex());
+ if (!o.castShadow) shadows = false; } });
+console.log(JSON.stringify({ minY: box.min.y, roofY, yaws: yaws.size,
+ colors: colors.size, shadows }));
+""")
+ assert out["minY"] >= out["roofY"] - 0.01, (out["minY"], out["roofY"])
+ assert out["yaws"] >= 3, ("every HVAC unit on one axis", out)
+ assert out["colors"] >= 3, ("every unit the same paint", out)
+ assert out["shadows"]
+
+
+def test_a_district_is_a_layout_not_a_grid_of_stamps():
+ """Streets are real gaps, blocks subdivide into lots, and the caller gets
+ the road centrelines back so traffic and road surfaces can use them."""
+ out = _measure("""
+const f = cityFabric({ rand: mk(53), width: 460, depth: 300, blockW: 50,
+ blockD: 60, streetW: 12, avenueW: 22, density: 0.8,
+ skyline: (x, z) => 1 + Math.exp(-(x * x + z * z) / 8000) });
+f.group.updateMatrixWorld(true);
+const heights = [], widths = new Set();
+for (const b of f.group.children) {
+ const box = new THREE.Box3().setFromObject(b);
+ heights.push(box.max.y - box.min.y);
+ widths.add(b.getObjectByName('Walls').material.color.getHex());
+}
+heights.sort((a, b) => a - b);
+console.log(JSON.stringify({
+ buildings: f.buildings,
+ footprintFrac: f.footprintFrac,
+ streetsZ: f.group.userData.streets.alongZ.length,
+ streetsX: f.group.userData.streets.alongX.length,
+ avenue: Math.max(...f.group.userData.streets.alongZ.map((r) => r.width)),
+ street: Math.min(...f.group.userData.streets.alongZ.map((r) => r.width)),
+ hMin: heights[0], hMax: heights[heights.length - 1],
+ hMed: heights[Math.floor(heights.length / 2)],
+ wallTints: widths.size,
+}));
+""")
+ assert out["buildings"] > 20, out
+ assert 0.1 < out["footprintFrac"] < 0.8, out
+ assert out["streetsZ"] >= 2 and out["streetsX"] >= 2, out
+ assert out["avenue"] > out["street"], ("no avenue rhythm", out)
+ # A skyline function must actually shape the district.
+ assert out["hMax"] > out["hMed"] * 1.5 > out["hMin"], out
+ assert out["wallTints"] >= 4, ("one colour for the whole city", out)
diff --git a/harness/tests/scene_runtime/lib/test_canopy.py b/harness/tests/scene_runtime/lib/test_canopy.py
new file mode 100644
index 00000000..42a48895
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_canopy.py
@@ -0,0 +1,294 @@
+"""canopy.js — the crown has to read as leaves, not as a green solid.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_canopy_lib.py). The three properties a convex crown cannot have —
+a broken silhouette, light between the leaves, colour that varies leaf to leaf
+— are pinned exactly as they were.
+
+Their two ``scene_check`` cases wanted a GPU compile, and it is at the end of
+this file: ``_probe.compile_scene`` stages the fixture as the workspace
+``src/scene.js`` that ``runtime_js/check_shaders.mjs`` boots (13 programs, 2
+custom materials). The structural assertions stay in front of it — they say
+WHAT the GLSL does, which a compile cannot.
+
+The last two tests are new here, and both cover a change the port made: the
+shade colour is now MORE saturated than the lit one (desaturating it was what
+pulled the whole mass toward grey-green felt on our pipeline), and the
+transmission through a leaf goes out when the sun goes below the horizon
+(``patchLeafSSS`` adds it to the ALBEDO, so nothing else turns it off, and the
+night pass rendered every crown as glowing daylight foliage).
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "noise.js", "grass.js", "foliage_shade.js", "canopy.js")
+
+
+def test_a_whole_woodland_of_crowns_is_one_draw_call():
+ """A crown is thousands of cards; per-leaf meshes would spend the scene's
+ whole draw budget on foliage — the avenue that prompted this library
+ shipped 158,917 separate meshes and timed its own census out."""
+ out = measure("""
+import { makeCanopy } from './lib/canopy.js';
+const g = makeCanopy({ crowns: [
+ { position: [0, 6, 0], radius: 3 },
+ { position: [9, 7, 2], radius: 3.5 },
+ { position: [-8, 5, 4], radius: 2.5 },
+], leaves: 900, seed: 4 });
+const meshes = [];
+g.traverse((o) => { if (o.isMesh) meshes.push(o); });
+const lv = g.getObjectByName('Leaves');
+console.log(JSON.stringify({
+ meshes: meshes.length,
+ instanced: !!lv.geometry.isInstancedBufferGeometry,
+ count: lv.geometry.instanceCount,
+ attrs: Object.keys(lv.geometry.attributes).sort(),
+ culled: lv.frustumCulled,
+ box: [lv.geometry.boundingBox.min.toArray(),
+ lv.geometry.boundingBox.max.toArray()],
+ hasTick: typeof g.userData.tick === 'function',
+}));
+""", _LIBS)
+ # Three crowns, one mesh — that is the whole point of the field.
+ assert out["meshes"] == 1, out
+ assert out["instanced"] and out["count"] == 2700, out
+ assert out["attrs"] == ["aCorner", "iAxis", "iPos", "iVar", "normal",
+ "position", "uv"], out
+ assert out["culled"] is False, out
+ # position stays at zero, so a derived bound would be a point at the
+ # origin: the stated box must span all three crowns.
+ assert out["box"][0][0] < -9 and out["box"][1][0] > 11, out
+ assert out["hasTick"], out
+
+
+def test_neighbouring_leaves_are_not_the_same_green():
+ """Broken colour is the mechanism: a mass of cards that all share one hue
+ is the flat crown again with more triangles. The spread is carried per
+ leaf and scaled by `hue`, so hue 0 must collapse it."""
+ out = measure("""
+import { makeCanopy } from './lib/canopy.js';
+const read = (h) => {
+ const lv = makeCanopy({ leaves: 2000, seed: 9, hue: h })
+ .getObjectByName('Leaves');
+ const v = lv.geometry.attributes.iVar.array;
+ let lo = 1e9, hi = -1e9;
+ for (let i = 1; i < v.length; i += 4) {
+ lo = Math.min(lo, v[i]); hi = Math.max(hi, v[i]);
+ }
+ return { lo, hi, swing: lv.material.userData.uniforms.uLeafHue.value };
+};
+console.log(JSON.stringify({ on: read(0.30), off: read(0) }));
+""", _LIBS)
+ on = out["on"]
+ # Offsets run the full -1..1 so the swing uniform alone sets the spread:
+ # neighbours land up to `hue` radians apart.
+ assert on["lo"] < -0.9 and on["hi"] > 0.9, on
+ assert abs(on["swing"] - 0.30) < 1e-6, on
+ assert out["off"]["swing"] == 0, out
+
+
+def test_a_hedge_is_a_leaf_mass_that_is_not_a_ball():
+ """The first builder handed this library wrote its own Icosahedra for a
+ hedgerow and said why in a comment: it wanted a "non-spherical" foliage
+ volume, and a crown described by one radius cannot be one. Per-axis
+ extents, with the lighting normal following the ELLIPSOID rather than the
+ sphere the direction was drawn on."""
+ out = measure("""
+import { makeCanopy } from './lib/canopy.js';
+const lv = makeCanopy({ crowns: [
+ { position: [0, 1.2, 0], size: [0.9, 1.2, 18] }],
+ leaves: 3000, seed: 6 }).getObjectByName('Leaves');
+const p = lv.geometry.attributes.iPos.array;
+const a = lv.geometry.attributes.iAxis.array;
+let ex = 0, ez = 0, sideward = 0, endward = 0;
+for (let i = 0; i < p.length; i += 3) {
+ ex = Math.max(ex, Math.abs(p[i]));
+ ez = Math.max(ez, Math.abs(p[i + 2]));
+ // Judge it well DOWN the length, where the two normals disagree: near the
+ // middle any normal points sideways anyway.
+ if (Math.abs(p[i + 2]) > 8 && Math.abs(p[i]) > 0.4) {
+ if (Math.abs(a[i]) > Math.abs(a[i + 2])) sideward++;
+ else endward++;
+ }
+}
+console.log(JSON.stringify({ ex, ez, sideward, endward }));
+""", _LIBS)
+ # The mass runs down its long axis and stays thin across.
+ assert out["ez"] > 12 and out["ex"] < 2, out
+ # Facing follows the hedge's flank; on a sphere-derived normal these would
+ # split evenly instead.
+ assert out["sideward"] > 8 * out["endward"], out
+
+
+def test_two_canopies_with_one_seed_are_identical():
+ """A crown that reshuffles every reload cannot be reviewed, and the refine
+ loop compares renders across rounds."""
+ out = measure("""
+import { makeCanopy } from './lib/canopy.js';
+const of = () => Array.from(
+ makeCanopy({ leaves: 400, seed: 21 })
+ .getObjectByName('Leaves').geometry.attributes.iPos.array);
+const a = of(), b = of();
+console.log(JSON.stringify({ same: a.every((v, i) => v === b[i]),
+ n: a.length }));
+""", _LIBS)
+ assert out["same"] and out["n"] == 1200, out
+
+
+def test_a_shade_leaf_is_darker_cooler_and_more_saturated():
+ """The default under-colour is the crown's inside, and mixing toward it is
+ most of what gives the mass a form. The reference desaturated it
+ (`s * 0.9`), which is what LIGHTENING a colour does — measured on our
+ pipeline the crown came out at 0.34 mean foliage saturation and read as
+ grey-green felt. A shade leaf is the chlorophyll-dense one."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeCanopy } from './lib/canopy.js';
+const u = makeCanopy({ leaves: 200 }).getObjectByName('Leaves')
+ .material.userData.uniforms;
+const hsl = (c) => { const o = {}; c.getHSL(o); return o; };
+console.log(JSON.stringify({ lit: hsl(u.uLeafLit.value),
+ under: hsl(u.uLeafUnder.value) }));
+""", _LIBS)
+ lit, under = out["lit"], out["under"]
+ assert under["l"] < lit["l"] * 0.45, out # darker
+ assert under["h"] > lit["h"] + 0.02, out # cooler
+ assert under["s"] > lit["s"], out # and MORE saturated
+
+
+def test_transmission_through_a_leaf_goes_out_when_the_sun_does():
+ """`patchLeafSSS` adds its glow to the albedo, before any light is
+ applied, so a sun below the horizon does not turn it off by itself: on the
+ night showcase pass every crown stayed a bright yellow-green over correctly
+ dark ground. Full strength is kept for any sun at or above the horizon —
+ a low sun is exactly when a backlit crown glows most."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeCanopy } from './lib/canopy.js';
+const amt = (el) => {
+ const r = el * Math.PI / 180;
+ const dir = new THREE.Vector3(Math.cos(r), Math.sin(r), 0.2).normalize();
+ return makeCanopy({ leaves: 200, backlit: { sunDir: dir } })
+ .getObjectByName('Leaves').material.userData.uniforms.uLeafAmt.value;
+};
+const off = makeCanopy({ leaves: 200, backlit: false })
+ .getObjectByName('Leaves').material.userData.uniforms.uLeafAmt;
+console.log(JSON.stringify({ high: amt(38), low: amt(1), night: amt(-20),
+ off: off === undefined }));
+""", _LIBS)
+ assert out["high"] > 0.4, out
+ # Golden hour keeps the whole effect; it is the best moment for it.
+ assert abs(out["low"] - out["high"]) < 1e-6, out
+ assert out["night"] == 0, out
+ # `backlit: false` never installs the patch at all.
+ assert out["off"] is True, out
+
+
+def test_every_leaf_is_built_in_the_vertex_shader_and_the_chain_is_whole():
+ """The whole crown lives in a patched MeshStandardMaterial, so a typo in
+ the leaf GLSL is a blank screen rather than a bad-looking tree.
+
+ This drives the material's own `onBeforeCompile` and reads the GLSL that
+ would go to the driver: the leaf body must reach the vertex stage, the
+ grade must reach the fragment stage, `patchLeafSSS` must have CHAINED
+ behind the leaf patch rather than replaced it (assigning
+ `onBeforeCompile` outright is how a second patch silently eats the
+ first), and `shadows: true` must install the displaced depth pass — a
+ shadow pass over the undisplaced geometry draws only the zero-position
+ quads. The real GPU compile of this same material is
+ `test_every_program_compiles_on_the_gpu` at the end of this file; the frames
+ are at fx/out/canopy/ (zero shader_errors)."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeCanopy } from './lib/canopy.js';
+const g = makeCanopy({
+ crowns: [{ position: [0, 7, 0], radius: 4 },
+ { position: [0, 0.9, -9], size: [0.9, 0.9, 14] }],
+ leaves: 1200, wind: { strength: 1.4, speed: 0.8 },
+ backlit: { sunDir: new THREE.Vector3(0.45, 0.62, 0.35) },
+ shadows: true, seed: 2,
+});
+const mesh = g.getObjectByName('Leaves');
+const glsl = (mat) => {
+ const s = { uniforms: {}, vertexShader: '#include <begin_vertex>',
+ fragmentShader: '#include <color_fragment>' };
+ mat.onBeforeCompile(s, null);
+ return s;
+};
+const s = glsl(mesh.material);
+const d = mesh.customDepthMaterial ? glsl(mesh.customDepthMaterial) : null;
+console.log(JSON.stringify({
+ patches: mesh.material.userData.astraPatches.map((p) => p.name),
+ key: mesh.material.customProgramCacheKey(),
+ vertexBuildsLeaf: s.vertexShader.includes('leafLocalDir')
+ && s.vertexShader.includes('transformed = lfP;'),
+ fragmentGrades: s.fragmentShader.includes('astraHueShift')
+ && s.fragmentShader.includes('diffuseColor.rgb = clamp(lfC'),
+ sssAfterLeaf: s.fragmentShader.indexOf('uLeafTint')
+ > s.fragmentShader.indexOf('uLeafUnder'),
+ varyingsOnce: (s.fragmentShader.match(/varying vec2 vLeafB;/g) || []).length,
+ boundUniforms: ['uLeafLit', 'uLeafUnder', 'uLeafHue', 'uLeafWind', 'uTime']
+ .every((k) => s.uniforms[k] !== undefined),
+ depthDisplaces: !!d && d.vertexShader.includes('transformed = lfP;'),
+}));
+""", _LIBS)
+ # foliageBase is the shared varying `patchLeafSSS` installs before its
+ # own patch; the leaf patch must still be FIRST, and the cache key must
+ # name the whole chain in order (one key per distinct GLSL).
+ assert out["patches"] == ["canopy:leaf", "foliageBase", "leaf"], out
+ assert out["key"] == "astra:canopy:leaf+foliageBase+leaf", out
+ assert out["vertexBuildsLeaf"] and out["fragmentGrades"], out
+ assert out["sssAfterLeaf"], out
+ assert out["varyingsOnce"] == 1, out
+ assert out["boundUniforms"], out
+ assert out["depthDisplaces"], out
+
+# A FOGGED, shadow-casting scene: `USE_FOG` and the shadow branches only exist
+# in a program built from one, and a patch that drops a chunk compiles fine in
+# an unfogged fixture and renders as a sticker in a real scene.
+_COMPILE_SCENE = """
+import * as THREE from 'three';
+import { tickShaders } from './lib/shader.js';
+import { makeCanopy } from './lib/canopy.js';
+
+export const BOUNDS = { min: [-30, 0, -30], max: [30, 20, 30] };
+export function heightAt(x, z) { return Math.sin(x * 0.1) * 0.3; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.004);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 1.0));
+ const sun = new THREE.DirectionalLight(0xffffff, 3);
+ sun.position.set(10, 20, 10); sun.castShadow = true; scene.add(sun);
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(80, 80),
+ new THREE.MeshStandardMaterial({ color: 0x6d6a52 }));
+ ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground);
+ scene.add(makeCanopy({ crowns: [
+ { position: [0, 4, 0], radius: 2.4, height: 3.2 },
+ { position: [6, 2, -3], size: [7, 1.6, 1.4] },
+ ], wind: 0.5 }));
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [12, 5, 14], lookAt: [0, 2, 0], fov: 45 }],
+ update(t) { tickShaders(scene, t); },
+ };
+}
+"""
+
+
+def test_every_program_compiles_on_the_gpu():
+ """A crown is thousands of leaf cards in ONE instanced draw with a displaced
+ vertex stage and its own depth material; the hedge form (`size`) builds the
+ same program from a different mass.
+
+ The reference had this case and the port dropped it: `_probe.shader_check`
+ staged only `src/fixture.js` while `check_shaders.mjs` boots the workspace's
+ `src/scene.js`, so it could never run. `_probe.compile_scene` stages the
+ scene, so the case is back (consolidation, 2026-09-01)."""
+ code, out = compile_scene(_COMPILE_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out
diff --git a/harness/tests/scene_runtime/lib/test_caustics.py b/harness/tests/scene_runtime/lib/test_caustics.py
new file mode 100644
index 00000000..2b0247f8
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_caustics.py
@@ -0,0 +1,706 @@
+"""Caustics are LIGHT, and every way of getting them wrong is silent.
+
+``caustics.js`` is one ``patchStandard`` that throws the water's moving
+net onto what is under it. Five things can go wrong with no error at
+all: a uniform a neighbour already declares is absorbed by dedupeUniforms
+and the patch reads someone else's number; a local declared twice in the
+one injected main takes the whole material down; a pattern built from one
+fbm compiles perfectly and reads as dirt; lifting albedo instead of the
+emissive term caps the net at the light the surface already gets, so it
+vanishes exactly where a pool is interesting; and a net whose peaks run
+past what the tone map holds comes out of ACES as flat white — the
+brightest node and one a third as bright arrive at the same pixel value.
+These pin the source that avoids that, then compile the real chain on the
+real renderer.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference test. The
+assertions about THEIR renderer contract are gone; the colour half (a
+per-channel extinction, the dispersion split, the local source) is ours.
+"""
+
+from __future__ import annotations
+
+import re
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "caustics.js", "waterside.js", "terrain_shade.js",
+ "surface_wear.js")
+_LIB = LIB_DIR / "caustics.js"
+
+# The two hooks patchStandard injects into, as a material three would.
+# Nothing else is in the source, so what comes back is the patch itself.
+_FAKE_SHADER = """
+const fake = () => ({
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+});
+const mains = (sh) => sh.fragmentShader.slice(
+ sh.fragmentShader.indexOf('void main')) + '\\n' +
+ sh.vertexShader.slice(sh.vertexShader.indexOf('void main'));
+const locals = (src) => (src.match(
+ /^\\s+(?:float|vec2|vec3|vec4|mat3|mat4)\\s+(\\w+)/gm) || [])
+ .map((h) => h.trim().split(/\\s+/)[1]);
+"""
+
+
+def _measure(script: str) -> dict:
+ return measure(_FAKE_SHADER + script, _LIBS)
+
+
+def test_the_net_is_ridged_interference_not_one_noise_call():
+ """The whole difference between caustics and dirt. A caustic is a
+ net of FILAMENTS — the creases of a wave field, not its blobs — so
+ the pattern folds noise about its own mid-line and raises the crease
+ to a power, which is what makes a line instead of a smear. One such
+ field is a smear of worms; the effect is the INTERFERENCE of two,
+ summed for the net and multiplied so the crossings flare into the
+ bright nodes. A single fbm call would compile and read as mud.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+const sh = fake();
+patchCaustics(new THREE.MeshStandardMaterial()).onBeforeCompile(sh);
+const fs = sh.fragmentShader;
+console.log(JSON.stringify({
+ fs,
+ webs: (fs.match(/astraCauWeb\\(/g) || []).length,
+ fbm: (fs.match(/astraFbm2\\(/g) || []).length,
+}));
+""")
+ fs = out["fs"]
+ # The crease: |n - mid| folded, then powered into a filament. Two
+ # octaves (which top out at 0.75, hence 2.667) kink the contour.
+ assert "float d = abs(astraFbm2(p, 2) * 2.667 - 1.0);" in fs
+ assert "return pow(1.0 - d, 16.0);" in fs
+ # Two fields, each in its OWN frame: a train's filaments run ACROSS
+ # the way it travels, so the frame is stretched that way.
+ assert out["webs"] == 3, "one definition, two crossing trains"
+ assert "vec2 cauU = vec2(0.86, 0.51);" in fs
+ assert "vec2 cauV = vec2(-0.51, 0.86);" in fs
+ assert "dot(cauP, cauU) + cauT," in fs
+ assert "dot(cauP, cauV) * 0.80));" in fs
+ assert "dot(cauP, cauV) * 1.43 - cauT * 0.83," in fs
+ # Sum = the net, product = the nodes. They are kept as separate
+ # locals because the colour half needs to tell them apart, but the
+ # interference term itself is what makes this a caustic: without the
+ # product the two fields never meet.
+ assert "float cauFil = (cauA + cauB) * 0.5;" in fs
+ assert "float cauNode = cauA * cauB;" in fs
+ assert "float cauNet = cauFil + 4.0 * cauNode;" in fs
+ # Not one noise read pretending to be a pattern.
+ assert out["fbm"] >= 2, out["fbm"]
+ assert "astraFbmUnit" not in fs, "that is terrain_shade's helper"
+
+
+def test_nothing_above_the_waterline_is_touched():
+ """Above ``level`` there is no water, so there is nothing to throw a
+ net — a caustic that climbs the dry bank is the tell that it is a
+ texture. The depth is clamped at zero at the line and the whole
+ contribution is gated by a smoothstep FROM zero, so at and above the
+ line the added light is exactly 0.0, not merely small. Below it the
+ net fades in over the first fraction of a depth (light needs a run
+ to converge) and out again with the water column.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+const sh = fake();
+const m = patchCaustics(new THREE.MeshStandardMaterial(),
+ { level: 2.5, depthFade: 4 });
+m.onBeforeCompile(sh);
+const fs = sh.fragmentShader;
+const body = fs.slice(fs.indexOf('#include <color_fragment>'));
+console.log(JSON.stringify({
+ fs, body,
+ level: m.userData.uniforms.uCauLevel.value,
+ fade: m.userData.uniforms.uCauFade.value,
+ zeroFade: patchCaustics(new THREE.MeshStandardMaterial(),
+ { depthFade: 0 }).userData.uniforms.uCauFade.value,
+ zeroAbs: patchCaustics(new THREE.MeshStandardMaterial(),
+ { depthFade: 0 }).userData.uniforms.uCauAbs.value,
+}));
+""")
+ fs, body = out["fs"], out["body"]
+ assert out["level"] == 2.5 and out["fade"] == 4
+ # Depth below the line, clamped: above it every term that follows
+ # sees zero.
+ assert "float cauD = max(uCauLevel - vAstraWorld.y, 0.0);" in fs
+ # smoothstep(0, x, 0) is exactly 0, so the gate is not "nearly none
+ # above the line", it is none.
+ assert "float cauK = smoothstep(0.0, uCauFade * 0.3, cauD);" in fs
+ # A zero fade would divide by zero and paint NaN over the surface —
+ # in the gate AND in the extinction, which is now the other user of
+ # that number.
+ assert out["zeroFade"] > 0
+ assert all(0 < v < 1e6 for v in out["zeroAbs"].values()), out["zeroAbs"]
+ # And the gate reaches the ONE write: nothing else in the body may
+ # touch an output, or the patch could leak past the waterline by
+ # another route.
+ assert "* (cauNet * cauK * uCauAmt);" in body
+ writes = re.findall(
+ r"^\s*(diffuseColor|totalEmissiveRadiance|gl_FragColor|"
+ r"roughnessFactor)[.\w]*\s*[-+*/]?=", body, re.M)
+ assert writes == ["totalEmissiveRadiance"], writes
+
+
+def test_the_net_belongs_to_the_water_above_not_to_the_floor():
+ """What separates thrown light from a painted pattern: the fragment
+ is shaded from where its sunbeam ENTERED the water — its own world
+ XZ slid toward the sun by its own depth — so a step riser and the
+ floor beside it take one continuous net rather than a pattern each.
+ The slide is REFRACTED on the CPU (water bends the ray toward the
+ vertical), which is why it is a uniform and not ``sunDir.xz /
+ sunDir.y``: that air tangent overshoots by a third and shears the
+ net off the wall. A sun straight overhead throws no slide at all.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+const sh = fake();
+const low = new THREE.Vector3(0.8, 0.35, 0.0);
+const m = patchCaustics(new THREE.MeshStandardMaterial(), { sunDir: low });
+m.onBeforeCompile(sh);
+const u = (mat, k) => mat.userData.uniforms[k].value;
+const up = patchCaustics(new THREE.MeshStandardMaterial(),
+ { sunDir: new THREE.Vector3(0, 1, 0) });
+const under = patchCaustics(new THREE.MeshStandardMaterial(),
+ { sunDir: new THREE.Vector3(0.3, -0.9, 0.2) });
+const n = low.clone().normalize();
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ slide: u(m, 'uCauSlide'), sun: u(m, 'uCauSun'),
+ airTan: Math.hypot(n.x, n.z) / n.y,
+ upSlide: u(up, 'uCauSlide'), underSlide: u(under, 'uCauSlide'),
+}));
+""")
+ fs = out["fs"]
+ assert "vec2 cauP = (vAstraWorld.xz + uCauSlide * cauD) / uCauScale" in fs
+ assert "uniform vec2 uCauSlide;" in fs, "two floats, not a sampler"
+ slide = out["slide"]
+ # Along the sun's azimuth (+x here), and SHORTER than the air
+ # tangent — that shortening is the refraction.
+ assert slide["y"] == 0, slide
+ assert 0 < slide["x"] < out["airTan"], (slide, out["airTan"])
+ assert slide["x"] < out["airTan"] * 0.8, "n = 1.333 is a third"
+ # Straight overhead: no slide, and no divide by a zero azimuth.
+ assert out["upSlide"] == {"x": 0, "y": 0}
+ # A sun below the horizon must still give finite numbers, not NaN.
+ assert all(abs(v) < 10 for v in out["underSlide"].values())
+ # The facing term: light that arrives edge-on spreads over more
+ # floor, so it must not land at full strength on a vertical face.
+ assert "max(dot(normalize(vAstraWorldN), uCauSun)," in fs
+ assert out["sun"]["y"] > 0.3, "sunDir points TOWARD the sun"
+
+
+def test_caustics_land_on_the_light_not_on_the_albedo():
+ """``fragmentBody`` edits ``diffuseColor``, which is ALBEDO, and
+ albedo is the wrong place for this: it would cap the net at whatever
+ light the surface already gets, so the shaded corner, the soffit and
+ the deep step — the places a caustic is the only light there is —
+ would get none. So the lift goes on ``totalEmissiveRadiance``,
+ tinted by the albedo because what the eye sees is that light
+ REFLECTED. The cost of that choice is a material that has no such
+ term at all, and it is a compile error rather than a dim result, so
+ it is said out loud.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+const sh = fake();
+const said = [];
+console.warn = (msg) => said.push(String(msg));
+const m = patchCaustics(new THREE.MeshStandardMaterial());
+m.onBeforeCompile(sh);
+const quiet = said.length;
+patchCaustics(new THREE.MeshBasicMaterial({ name: 'Tile' }));
+patchCaustics(new THREE.ShaderMaterial({ name: 'Ocean' }));
+patchCaustics(new THREE.MeshPhysicalMaterial());
+console.log(JSON.stringify({
+ fs: sh.fragmentShader, said, quiet, after: said.length,
+ rough: m.roughness,
+ color: m.userData.uniforms.uCauColor.value.getHex(),
+ amt: m.userData.uniforms.uCauAmt.value,
+}));
+""")
+ fs = out["fs"]
+ assert "totalEmissiveRadiance += cauTint * diffuseColor.rgb" in fs
+ # Albedo is READ and never written: the surface is not repainted.
+ assert "diffuseColor.rgb =" not in fs and "diffuseColor *=" not in fs
+ assert "diffuseColor.rgb *=" not in fs
+ # roughnessFactor does not exist yet at this hook, and gloss is not
+ # this patch's business anyway.
+ assert "roughnessFactor" not in fs
+ assert out["rough"] == 1.0, "a lit floor is not polished by caustics"
+ assert out["amt"] == 4
+ # Daylight above the surface, before the water takes the red out of
+ # it: near white, and warm rather than the cold white it was, since
+ # the cool end is now the DEPTH's job and not the lamp's.
+ assert out["color"] == 0xfff2e2
+ # A lit material is quiet; the two that cannot carry the term are
+ # named, once each.
+ assert out["quiet"] == 0
+ assert out["after"] == 2, out["said"]
+ assert "Tile" in out["said"][0] and "Ocean" in out["said"][1]
+ assert "totalEmissiveRadiance" in out["said"][0]
+
+
+def test_the_water_takes_the_red_out_first_without_dimming_the_net():
+ """The colour of thrown light is the colour of what it came
+ through. A single scalar fade leaves a 3 m floor lit the same
+ colour as a shin-deep one, which is the one thing no photograph of
+ a pool shows: red is gone in a couple of metres where blue crosses
+ tens, so the ramp runs warm at the step and green-blue at the drain.
+
+ The extinction is per channel AND normalised to Rec.709 luminance,
+ which is what keeps it a hue split rather than a second dimmer:
+ ``depthFade`` still means the metres it always meant. Weighting by
+ thirds instead would darken the net by about a tenth at every depth,
+ because green — the middle channel — carries 71% of the luminance.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+const sh = fake();
+const m = patchCaustics(new THREE.MeshStandardMaterial(), { depthFade: 2.5 });
+m.onBeforeCompile(sh);
+const abs = m.userData.uniforms.uCauAbs.value;
+const at = (d) => [Math.exp(-d * abs.x), Math.exp(-d * abs.y),
+ Math.exp(-d * abs.z)];
+const lum = (c) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ abs: [abs.x, abs.y, abs.z],
+ rate: 0.2126 * abs.x + 0.7152 * abs.y + 0.0722 * abs.z,
+ shallow: at(0.4), deep: at(2.5), lumDeep: lum(at(2.5)),
+ wide: (() => { const a = patchCaustics(new THREE.MeshStandardMaterial(),
+ { depthFade: 5 }).userData.uniforms.uCauAbs.value; return a.x; })(),
+}));
+""")
+ fs = out["fs"]
+ assert "vec3 cauTint = uCauColor * exp(-cauD * uCauAbs);" in fs
+ assert "uniform vec3 uCauAbs;" in fs
+ r, g, b = out["abs"]
+ # Red is drunk first, blue last — and by a real margin, not a hint.
+ assert r > g > b > 0, out["abs"]
+ assert r / b > 2.0, (r, b)
+ # Luminance-neutral: the mid-grey rate is exactly 1 / depthFade, so
+ # a caller who asked for 2.5 m still gets 2.5 m.
+ assert abs(out["rate"] - 1 / 2.5) < 1e-6, out["rate"]
+ # A deeper fade is a slower rate, per channel, in proportion.
+ assert abs(out["wide"] - r * 2.5 / 5) < 1e-6
+ # The ramp itself: barely tinted at the step, clearly cold at depth.
+ sr, sg, sb = out["shallow"]
+ dr, dg, db = out["deep"]
+ assert sb / sr < 1.35, (sr, sb)
+ assert db / dr > 2.2, (dr, db)
+ # And the net at one fade of depth still holds the ~exp(-1) it held
+ # when the fade was one number (Jensen: never darker, never much
+ # brighter).
+ assert 0.36 < out["lumDeep"] < 0.46, out["lumDeep"]
+ # Dispersion within one net: a lone filament is a fold seen edge-on
+ # and keeps the cool end, a crossing is achromatic and warm-white.
+ assert "float cauNf = cauNode / (cauNode + cauFil * 0.5 + 1e-4);" in fs
+ assert "mix(vec3(0.84, 0.98, 1.10), vec3(1.08, 1.00, 0.92)," in fs
+ # Broken colour over metres: one flat green over a whole pool is the
+ # tell of a painted pattern.
+ assert "cauTint = astraHueBreak(cauTint, cauP, 0.25, 0.22);" in fs
+
+
+def test_the_peaks_stay_inside_the_tone_map_and_the_far_field_stays_lit():
+ """Two folds plus their product run to 5 and the swell carries that
+ to 8; at the shipped strength that is 30-odd units of radiance into
+ an ACES curve that holds about 4, so the brightest node and one a
+ third as bright came out as the same white and the floor's own
+ material went with them. The field is rolled off before it is
+ scaled — peaks toward 5.5, mid-tones nearly untouched.
+
+ And the aliasing guard fades the net to the field's MEAN rather than
+ to black: fading to zero draws a line across the floor at the
+ distance where the water stops being lit.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+const sh = fake();
+patchCaustics(new THREE.MeshStandardMaterial()).onBeforeCompile(sh);
+const fs = sh.fragmentShader;
+const roll = (x) => x / (1.0 + 0.18 * x);
+console.log(JSON.stringify({
+ fs,
+ peak: roll(5.0 * 1.65), mid: roll(0.5), asymptote: roll(1e6),
+}));
+""")
+ fs = out["fs"]
+ assert "cauNet = cauNet / (1.0 + 0.18 * cauNet);" in fs
+ # A node lands in the range a bloom threshold can catch and a tone
+ # map can still separate; four times the shipped strength is not.
+ assert 3.0 < out["peak"] * 4 * 0.25 < 4.0, out["peak"]
+ assert out["asymptote"] < 5.6
+ # The mid-tones are barely touched: this is a shoulder, not a
+ # brightness cut.
+ assert out["mid"] > 0.45, out["mid"]
+ # Aliasing: to the mean, keeping the swell, never to black.
+ assert "cauNet = mix(cauNet, 0.30 * cauSwell," in fs
+ assert "smoothstep(0.25, 0.9, cauAa));" in fs
+ assert "cauNet *= 1.0 - smoothstep" not in fs, "that ended the water"
+ # A ramp of depth over hundreds of pixels is where 8-bit output
+ # bands, so the gate carries its own dither.
+ assert "cauK *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.05;" in fs
+
+
+def test_a_lamp_over_the_water_lights_a_pool_and_the_sun_lights_a_bay():
+ """A night pool is a POOL: one bulb whose net reaches the far bank of
+ a reservoir is the same tell as a net that climbs a dry wall. The
+ sun is the opposite — parallel light, no falloff — so it stays the
+ default, and its packed reach of 0 makes the falloff term exactly
+ 1.0 with no branch and no second shader variant.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+const sh = fake();
+const sun = patchCaustics(new THREE.MeshStandardMaterial());
+sun.onBeforeCompile(sh);
+const u = (m) => m.userData.uniforms.uCauSrc.value;
+const lamp = patchCaustics(new THREE.MeshStandardMaterial(),
+ { source: new THREE.Vector3(4, 5, -2), reach: 6 });
+const noReach = patchCaustics(new THREE.MeshStandardMaterial(),
+ { source: new THREE.Vector3(0, 3, 0) });
+const zero = patchCaustics(new THREE.MeshStandardMaterial(),
+ { source: new THREE.Vector3(0, 3, 0), reach: 0 });
+const fall = (r, w) => 1 / (1 + (r * w) * (r * w));
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ sun: u(sun), lamp: u(lamp), noReach: u(noReach).w, zeroW: u(zero).w,
+ atReach: fall(6, u(lamp).w), atSun: fall(500, u(sun).w),
+ key: sun.customProgramCacheKey() === lamp.customProgramCacheKey(),
+}));
+""")
+ fs = out["fs"]
+ assert "uniform vec4 uCauSrc;" in fs
+ assert "float cauR = length(vAstraWorld.xz - uCauSrc.xz) * uCauSrc.w;" in fs
+ assert "cauK /= 1.0 + cauR * cauR;" in fs
+ # The sun: no source, no falloff — and 500 m away is still full
+ # strength, which is what "parallel" means.
+ assert out["sun"] == {"x": 0, "y": 0, "z": 0, "w": 0}
+ assert out["atSun"] == 1.0
+ # The lamp: its position, and 1 / reach packed into w.
+ assert out["lamp"] == {"x": 4, "y": 5, "z": -2, "w": 1 / 6}
+ assert abs(out["atReach"] - 0.5) < 1e-9, "reach is the half-way mark"
+ assert out["noReach"] == 1 / 8, "a default reach, not an infinity"
+ assert 0 < out["zeroW"] < 1e6, "reach 0 must not pack an infinity"
+ # One shader for both: the source is a uniform, so a lamp-lit pool
+ # and a sunlit one share a program.
+ assert out["key"], "the cache key must not fork on a uniform"
+
+
+def test_the_net_moves_with_the_water_instead_of_crawling():
+ """A scrolled pattern reads as a texture sliding under the water,
+ which is the failure this shape exists to avoid. Three things stop
+ it: the two trains counter-drift at incommensurate rates, so their
+ crossings travel at neither speed; the sample point is warped by two
+ noise fields of its own, coarse and fine, so the filaments writhe
+ rather than translate; and the whole thing rides ``uTime``, which
+ must reach the fragment stage DECLARED — patchStandard adds that
+ only because its declaration pass runs after the bodies go in.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+const sh = fake();
+const m = patchCaustics(new THREE.MeshStandardMaterial(), { speed: 0.9 });
+m.onBeforeCompile(sh);
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ speed: m.userData.uniforms.uCauSpeed.value,
+ timeDecls: (sh.fragmentShader.match(/uniform float uTime;/g) || []).length,
+ hasUniform: !!sh.uniforms.uCauSlide,
+ tickable: !!m.userData.uniforms.uTime,
+}));
+""")
+ fs = out["fs"]
+ assert out["speed"] == 0.9
+ assert "float cauT = uTime * uCauSpeed;" in fs
+ assert out["timeDecls"] == 1, "read undeclared, uTime is a compile error"
+ assert out["tickable"], "tickShaders finds uTime on userData.uniforms"
+ assert out["hasUniform"], "the patch's uniforms reach the program"
+ # Counter-drift: one train down +cauT, the other down -cauT, and at
+ # a rate that is not a multiple of the first's.
+ assert "dot(cauP, cauU) + cauT," in fs
+ assert "- cauT * 0.83," in fs
+ # Two warps, coarse and fine, both moving: the net writhes.
+ assert "astraNoise2(cauP * 0.35 + cauT * 0.07)" in fs
+ assert "astraNoise2(cauP * 2.2 + cauT * 0.30)" in fs
+ assert "cauP += (cauW - 0.5) * 0.40;" in fs
+ # And a slow broad cell, so the whole field breathes rather than
+ # lighting the floor evenly.
+ assert "float cauSwell = 0.35 + 1.30 * cauC;" in fs
+ assert "cauNet *= cauSwell;" in fs
+
+
+def test_its_uniforms_and_locals_collide_with_no_sibling_library():
+ """The failure with no symptom. dedupeUniforms drops a repeated
+ ``uniform`` declaration and keeps the FIRST, so a caustic patch that
+ named a uniform waterside already declares would silently read the
+ waterline's number for the rest of the run. A repeated local is the
+ opposite and just as fatal: two patches share ONE injected main, and
+ a redeclared local is a GLSL redefinition that takes the whole
+ material down. This library lands on exactly the materials those
+ siblings are already on, so both sets must be disjoint from all of
+ them — with uTime the one deliberate share.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+import { patchShoreWet, patchShoreFoam, patchShallowWater }
+ from './lib/waterside.js';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+const mineSh = fake(), sibSh = fake();
+const mine = patchCaustics(new THREE.MeshStandardMaterial());
+mine.onBeforeCompile(mineSh);
+const sib = new THREE.MeshStandardMaterial();
+patchShoreWet(sib); patchShoreFoam(sib); patchShallowWater(sib);
+patchTriplanar(sib); patchSlopeSplat(sib);
+patchMicroBreakup(sib); patchEdgeWear(sib);
+sib.onBeforeCompile(sibSh);
+console.log(JSON.stringify({
+ mineU: Object.keys(mine.userData.uniforms),
+ sibU: Object.keys(sib.userData.uniforms),
+ mineL: locals(mains(mineSh)),
+ sibL: locals(mains(sibSh)),
+}));
+""")
+ shared_uniforms = set(out["mineU"]) & set(out["sibU"])
+ assert shared_uniforms == {"uTime"}, shared_uniforms
+ assert all(u.startswith("uCau") for u in out["mineU"] if u != "uTime")
+ shared_locals = set(out["mineL"]) & set(out["sibL"])
+ assert shared_locals == set(), shared_locals
+ assert all(x.startswith("cau") for x in out["mineL"]), out["mineL"]
+ # And nothing declared twice within the patch's own bodies either.
+ assert len(out["mineL"]) == len(set(out["mineL"])), out["mineL"]
+
+
+def test_the_whole_chain_shares_one_main_without_a_redefinition():
+ """The load-bearing case: a submerged bank wears the rock
+ projection, the waterline and this at once. patchStandard chains by
+ name, so every body must survive in call order, the cache key must
+ name the whole chain (the first material to compile a key decides
+ the source for all of them), the shared world varyings must be
+ declared once however many patches ask for them, and no local may
+ appear twice in the one main.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+import { patchShoreWet } from './lib/waterside.js';
+import { patchTriplanar } from './lib/terrain_shade.js';
+const sh = fake();
+const m = new THREE.MeshStandardMaterial();
+patchTriplanar(m);
+patchShoreWet(m, { level: 1.2 });
+patchCaustics(m, { level: 1.2, seed: 4 });
+patchCaustics(m, { level: 1.4, seed: 4 }); // retune, not a 4th patch
+m.onBeforeCompile(sh);
+const fs = sh.fragmentShader, vs = sh.vertexShader;
+const count = (s, re) => (s.match(re) || []).length;
+const seen = {};
+for (const name of locals(mains(sh))) seen[name] = (seen[name] || 0) + 1;
+console.log(JSON.stringify({
+ key: m.customProgramCacheKey(),
+ level: m.userData.uniforms.uCauLevel.value,
+ order: fs.indexOf('uTriA') < fs.indexOf('uWetDark')
+ && fs.indexOf('uWetDark') < fs.indexOf('cauNet'),
+ cau: fs.includes('totalEmissiveRadiance += cauTint'),
+ varyingVs: count(vs, /varying vec3 vAstraWorld;/g),
+ varyingFs: count(fs, /varying vec3 vAstraWorld;/g),
+ utilOnce: count(fs, /float astraFbm2\\(/g),
+ webOnce: count(fs, /float astraCauWeb\\(vec2 p\\)/g),
+ timeOnce: count(fs, /uniform float uTime;/g),
+ uniforms: ['uTriA', 'uWetY', 'uCauLevel', 'uCauAbs', 'uTime']
+ .every((k) => !!sh.uniforms[k]),
+ dupLocals: Object.keys(seen).filter((k) => seen[k] > 1),
+}));
+""")
+ assert out["cau"], out
+ assert out["order"], "bodies run in call order"
+ # The key names the whole chain, in order, and this patch is last
+ # because it was applied last. (The sibling halves are asserted by
+ # shape, not spelling: they are their own modules' contract.)
+ parts = out["key"].split("+")
+ assert parts[0].startswith("astra:") and len(parts) >= 3, out["key"]
+ assert parts[-1] == "caustics:net", out["key"]
+ assert out["level"] == 1.4, "re-applying retunes in place"
+ assert out["uniforms"], "every patch's uniforms reach the program"
+ # The world varyings are shared with the neighbours BY NAME on
+ # purpose, so the pair is declared once for the three of them.
+ assert out["varyingVs"] == 1 and out["varyingFs"] == 1
+ assert out["utilOnce"] == 1 and out["timeOnce"] == 1
+ assert out["webOnce"] == 1, "the helper is defined once"
+ assert out["dupLocals"] == [], out["dupLocals"]
+
+
+def test_the_shipped_module_is_deterministic_and_stage_safe():
+ """A pool must come back identical on a re-render, so the seed is
+ arithmetic and never a Math.random; and the patch's GLSL ships into
+ the VERTEX stage as well, where a fragment-only builtin would fail
+ every program in the engine at once — so fwidth and gl_FragCoord may
+ appear only in the fragment body.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+const a = fake(), b = fake();
+const opts = { level: 1.5, seed: 9, scale: 0.4, strength: 2 };
+const ma = patchCaustics(new THREE.MeshStandardMaterial(), opts);
+const mb = patchCaustics(new THREE.MeshStandardMaterial(), opts);
+ma.onBeforeCompile(a);
+mb.onBeforeCompile(b);
+const seed = (m) => m.userData.uniforms.uCauSeed.value;
+console.log(JSON.stringify({
+ same: a.fragmentShader === b.fragmentShader
+ && a.vertexShader === b.vertexShader,
+ seedA: seed(ma), seedB: seed(mb),
+ seed8: seed(patchCaustics(new THREE.MeshStandardMaterial(), { seed: 8 })),
+ vsBody: a.vertexShader.slice(a.vertexShader.indexOf('void main')),
+ vsHead: a.vertexShader.slice(0, a.vertexShader.indexOf('void main')),
+}));
+""")
+ assert out["same"], "one seed, one shader"
+ assert out["seedA"] == out["seedB"]
+ # A seed must MOVE the lattice, not shift it by a cell — a one-cell
+ # offset is the same pool drawn twice.
+ assert abs(out["seed8"]["x"] - out["seedA"]["x"]) > 5, out["seed8"]
+ # Nothing of this patch's own reaches the vertex stage but the world
+ # position: fwidth there is only GLSL_UTIL's, behind ASTRA_FRAG.
+ assert "fwidth" not in out["vsBody"]
+ assert "gl_FragCoord" not in out["vsBody"], "vertex stage has no such"
+ assert "astraCauWeb" not in out["vsHead"], "the web is fragment work"
+ src = _LIB.read_text(encoding="utf-8")
+ assert "Math.random" not in src
+ assert "Date.now" not in src
+ assert "export function patchCaustics" in src
+ # One export: the library is the net, nothing else.
+ assert src.count("\nexport ") == 1
+ assert max(len(ln) for ln in src.splitlines()) <= 80
+
+
+_SCENE = """
+import * as THREE from 'three';
+import { patchCaustics } from './lib/caustics.js';
+import { patchShoreWet } from './lib/waterside.js';
+import { patchTriplanar } from './lib/terrain_shade.js';
+import { tickShaders } from './lib/shader.js';
+
+export const BOUNDS = { min: [-8, -1, -6], max: [8, 5, 6] };
+
+const LEVEL = 1.3;
+const SUN = new THREE.Vector3(0.45, 0.75, 0.35);
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ // Without this USE_FOG is undefined and every fog branch compiles to
+ // nothing — which is how a library ships fog chunks that cannot
+ // compile at all and nobody finds out.
+ scene.fog = new THREE.FogExp2(0xc9d6e0, 0.02);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ // And without a shadow CASTER the depth variant of every patched
+ // material is never compiled either.
+ const sun = new THREE.DirectionalLight(0xfff0d6, 2.5);
+ sun.position.set(5, 8, 7);
+ sun.castShadow = true;
+ scene.add(sun);
+
+ // The pool: floor, wall and steps on ONE material wearing all three
+ // patches, which is the case the chain has to survive.
+ const tile = new THREE.MeshStandardMaterial(
+ { color: 0x4a5a5e, roughness: 0.85 });
+ patchTriplanar(tile, { scale: 1.4 });
+ patchShoreWet(tile, { level: LEVEL, band: 0.25 });
+ patchCaustics(tile, { level: LEVEL, sunDir: SUN, depthFade: 2.4 });
+
+ const floor = new THREE.Mesh(new THREE.BoxGeometry(11, 0.2, 8), tile);
+ floor.position.set(0, 0.1, 0);
+ floor.receiveShadow = true;
+ scene.add(floor);
+
+ const wall = new THREE.Mesh(new THREE.BoxGeometry(0.4, 2.6, 8), tile);
+ wall.position.set(-5.3, 1.3, 0);
+ wall.castShadow = wall.receiveShadow = true;
+ scene.add(wall);
+
+ // Four steps out of the water: two below the line, two above.
+ for (let i = 0; i < 4; i++) {
+ const h = 0.45 * (i + 1);
+ const step = new THREE.Mesh(new THREE.BoxGeometry(0.7, h, 4), tile);
+ step.position.set(4.6 - i * 0.7, 0.1 + h / 2, 1.4);
+ step.castShadow = step.receiveShadow = true;
+ scene.add(step);
+ }
+
+ // A boulder, half under: a curved surface at every angle to the sun.
+ const rock = new THREE.MeshStandardMaterial(
+ { color: 0x6f6559, roughness: 0.95 });
+ patchTriplanar(rock, { scale: 0.9 });
+ patchCaustics(rock, { level: LEVEL, sunDir: SUN, seed: 3 });
+ const boulder = new THREE.Mesh(
+ new THREE.IcosahedronGeometry(1.05, 2), rock);
+ boulder.position.set(-1.6, 0.85, -1.2);
+ boulder.castShadow = true;
+ scene.add(boulder);
+
+ // A lamp-lit corner: the local-source branch has to compile too.
+ const ledge = new THREE.MeshStandardMaterial(
+ { color: 0x585d5a, roughness: 0.9 });
+ patchCaustics(ledge, { level: LEVEL, sunDir: SUN, seed: 5,
+ source: new THREE.Vector3(3, 3.2, -2.4),
+ reach: 5, color: 0xffe6c0 });
+ const slab = new THREE.Mesh(new THREE.BoxGeometry(3, 0.3, 3), ledge);
+ slab.position.set(3, 0.35, -2.4);
+ slab.receiveShadow = true;
+ scene.add(slab);
+
+ // Instanced cobbles, so the USE_INSTANCING branch has to compile.
+ const pebbles = new THREE.InstancedMesh(
+ new THREE.IcosahedronGeometry(0.3, 1), rock, 10);
+ const m4 = new THREE.Matrix4();
+ for (let i = 0; i < 10; i++) {
+ m4.makeTranslation(-4 + i * 0.9, 0.32, -2.6 + (i % 3) * 0.7);
+ pebbles.setMatrixAt(i, m4);
+ }
+ pebbles.castShadow = true;
+ scene.add(pebbles);
+
+ // A camera, because the host reports a scene with none as not booted
+ // and never reaches the compile stage at all.
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [7, 3, 9], lookAt: [0, 1, 0],
+ fov: 45 }],
+ // One tick drives every patch in the chain; an un-advanced uTime is
+ // a frozen net, which is the other way this reads as a texture.
+ update(t) { tickShaders(scene, t); },
+ };
+}
+"""
+
+
+def test_the_chain_compiles_on_the_real_renderer():
+ """The only witness that counts. Everything above reads a string;
+ whether the GPU accepts three chained bodies in one main, the
+ instancing branch, a two-octave fbm inside a helper, a pow(16) and a
+ gl_FragCoord dither per fragment cannot be asserted from source, and
+ a patch that does not compile is worth nothing. Runs the same
+ wrapper the authoring agent runs, on our own renderer.
+ """
+ code, out = compile_scene(
+ _SCENE, ("shader.js", "caustics.js", "waterside.js",
+ "terrain_shade.js"))
+ assert code == 0, out
+ assert "every program compiled" in out
+ # A patched built-in keeps the built-in's own depth and fog chunks,
+ # so nothing here may be flagged as discardable.
+ assert "DISCARDED" not in out
diff --git a/harness/tests/scene_runtime/lib/test_celestial.py b/harness/tests/scene_runtime/lib/test_celestial.py
new file mode 100644
index 00000000..f64fce2b
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_celestial.py
@@ -0,0 +1,367 @@
+"""celestial.js: heat shimmer, stars, the Milky Way and the aurora.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_celestial_lib.py). Their renderer-contract assertions are
+dropped and their fog marker is retargeted — our `makeShaderMaterial` writes
+`3dcv: no-fog`, the token runtime_js/lib/glsl_audit.mjs reads, and the old
+`astra3d:` spelling is still accepted on read. Their physical claims (the
+magnitude distribution, the foot-bright curtain, a shimmer that displaces
+rather than paints, one seed one sky) are kept as they stood.
+
+THE PORT'S OWN LAWS, and the three regressions this file exists to stop —
+each one was a frame rendered on our host, looked at, and measured:
+
+1. A DISPLAY HAS TO CROSS THE SKY THE CAMERA IS POINTED AT. The curtain
+ azimuths were `n` independent draws, and at seed 11 the five of them left
+ a hundred-degree hole that both showcase cameras looked straight through:
+ the aurora was in the scene, cost its draw call, and did not appear in a
+ single pixel. Simulated over 180 seed/activity pairs, independent draws
+ left a gap wider than one camera's own field 64% of the time and up to
+ 270 degrees wide. One curtain per equal slice, jittered inside it, takes
+ that to 37% and 139 degrees — so the floor asserted here is a bound the
+ old code could not have met.
+
+2. ADDED LIGHT MUST STOP SHORT OF WHITE. ACES desaturates as it rolls off,
+ so a curtain allowed to reach alpha 1 arrives WHITE rather than green:
+ measured at 2.1% of the frame clipped past 0.97 with the hue gone. The
+ saturating curve now approaches `uPeak`, not 1.
+
+3. THE NIGHT BUILD IS THE DEFAULT. `ambient` defaulted to 0.85 — the
+ daylight-safe blend — and a star field belongs to exactly one frame, a
+ dark one. At the default, `makeStars()` on a night scene put the whole
+ sky inside a single 8-bit bucket (modal_frac 0.95, sky luminance flat at
+ 0.19): the catalog promised stars and the frame had none. The bright
+ build is still one argument away, and is still what a pale frame gets.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "noise.js", "materials.js", "celestial.js")
+
+
+def test_a_real_sky_is_mostly_faint_stars():
+ """The count of stars brighter than magnitude m grows as 10^0.6m, so a
+ sky is overwhelmingly faint with a handful of bright ones. A field of
+ evenly bright points reads as confetti, and it is what a uniform random
+ brightness gives — so the claim is the DISTRIBUTION, not the count."""
+ out = measure("""
+import { makeStars } from './lib/celestial.js';
+const g = makeStars({ count: 3000, seed: 5 });
+let attr = null;
+g.traverse((o) => {
+ if (!o.isMesh || attr) return;
+ // Per-star data rides aStar; .x is the brightness the size and the
+ // alpha are both built from.
+ const a = o.geometry.getAttribute('aStar');
+ if (a) attr = a;
+});
+const v = [];
+if (attr) for (let i = 0; i < attr.count; i++) v.push(attr.getX(i));
+v.sort((a, b) => a - b);
+const q = (p) => v[Math.min(v.length - 1, Math.floor(p * v.length))];
+console.log(JSON.stringify({
+ n: v.length,
+ min: v[0], q25: q(0.25), median: q(0.5), q75: q(0.75), max: v[v.length - 1],
+ mean: v.reduce((s, x) => s + x, 0) / (v.length || 1),
+}));
+""", _LIBS)
+ assert out["n"] > 100, "no per-star brightness attribute found"
+ span = out["max"] - out["min"]
+ assert span > 0, "every star is the same brightness"
+ # Skewed faint: the median sits well below the midpoint of the range.
+ mid = out["min"] + span / 2
+ assert out["median"] < mid, (
+ f"the field is not skewed faint (median {out['median']:.4f} vs "
+ f"midpoint {mid:.4f})")
+ assert out["mean"] < mid
+
+
+def test_nothing_in_the_sky_writes_depth_or_casts_a_shadow():
+ """A star field at the far plane that writes depth clips whatever is
+ drawn after it, and a firmament that casts a shadow puts the Milky Way
+ on the ground."""
+ out = measure("""
+import { makeStars, makeAurora } from './lib/celestial.js';
+const check = (g) => {
+ const bad = [];
+ g.traverse((o) => {
+ if (!o.isMesh) return;
+ for (const m of [].concat(o.material || [])) {
+ if (!m) continue;
+ if (m.depthWrite) bad.push(o.name + ':depthWrite');
+ if (o.castShadow) bad.push(o.name + ':castShadow');
+ }
+ });
+ return bad;
+};
+console.log(JSON.stringify({
+ stars: check(makeStars({ count: 200, seed: 1 })),
+ aurora: check(makeAurora({ seed: 2 })),
+}));
+""", _LIBS)
+ assert not out["stars"], out["stars"]
+ assert not out["aurora"], out["aurora"]
+
+
+def test_the_shimmer_displaces_what_is_behind_it():
+ """A shimmer you can SEE as a shape is wrong — it has to move what is
+ behind it. This pins that it displaces sample coordinates into a grab
+ of the frame rather than painting a haze of its own."""
+ out = measure("""
+import { makeHeatShimmer } from './lib/celestial.js';
+const g = makeHeatShimmer({ seed: 3 });
+let fs = '';
+let hasGrab = false;
+g.traverse((o) => {
+ if (o.isMesh && typeof o.onBeforeRender === 'function') hasGrab = true;
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.fragmentShader) fs += m.fragmentShader;
+ }
+});
+console.log(JSON.stringify({
+ found: fs.length > 0,
+ hasGrab,
+ // A displaced sample: the coordinate is offset before it is read.
+ displaces: /texture2D\\s*\\(|texture\\s*\\(/.test(fs)
+ && /\\+\\s*(vec2|off|wob|push|sh\\w*)/i.test(fs),
+ // And it must not simply add its own colour on top.
+ notJustAdditive: !/gl_FragColor\\s*=\\s*vec4\\(\\s*uColor/.test(fs),
+ // Resampling pixels that were already tone mapped and re-mapping them
+ // is the one way this shader could change a colour instead of moving
+ // it, so the card has to opt out.
+ toneMapped: (() => { let t = null;
+ g.traverse((o) => { for (const m of [].concat(o.material || []))
+ if (m && m.fragmentShader) t = m.toneMapped; }); return t; })(),
+}));
+""", _LIBS)
+ assert out["found"], "the shimmer builds no shader"
+ assert out["displaces"], (
+ "a shimmer must move what is behind it, not draw itself")
+ assert out["notJustAdditive"]
+ assert out["hasGrab"], "nothing grabs the frame the shimmer resamples"
+ assert out["toneMapped"] is False, (
+ "the resampled pixels are already tone mapped; mapping them twice "
+ "changes a colour instead of moving it")
+
+
+def test_the_aurora_is_brightest_at_its_foot():
+ """A curtain is fed from below: it is dense at the bottom edge and
+ dissolves upward. Uniform brightness is a painted band. The profile is
+ baked per vertex, so this reads the DATA rather than the GLSL."""
+ out = measure("""
+import { makeAurora } from './lib/celestial.js';
+const g = makeAurora({ seed: 4 });
+let mesh = null;
+g.traverse((o) => { if (o.isMesh && !mesh) mesh = o; });
+const glow = mesh.geometry.getAttribute('aGlow');
+const uv = mesh.geometry.getAttribute('uv');
+// v is height up the curtain, 0 at the foot. Bucket the baked glow by it.
+const sum = [0, 0, 0, 0], cnt = [0, 0, 0, 0];
+for (let i = 0; i < glow.count; i++) {
+ const b = Math.min(3, Math.floor(uv.getY(i) * 4));
+ sum[b] += glow.getX(i); cnt[b]++;
+}
+console.log(JSON.stringify({
+ bands: sum.map((s, i) => (cnt[i] ? s / cnt[i] : 0)),
+}));
+""", _LIBS)
+ b = out["bands"]
+ assert all(c > 0 for c in b[:1]), "no baked glow profile on the curtain"
+ assert b[0] > b[1] > b[2], (
+ f"the aurora does not fade upward from its foot: {b}")
+ assert b[3] < b[0] * 0.2, f"the top of the curtain never dissolves: {b}"
+
+
+def test_a_display_crosses_the_sky_wherever_the_camera_looks():
+ """Port law 1. A curtain per equal slice of the compass, jittered
+ inside it — so no seed can leave a hole wide enough to swallow a whole
+ camera. Asserted over the seeds and activities an agent will actually
+ pass, on the built geometry rather than on the generator."""
+ out = measure("""
+import { makeAurora } from './lib/celestial.js';
+const rows = [];
+for (let seed = 1; seed <= 12; seed++) {
+ for (const activity of [0.2, 0.5, 0.9]) {
+ const g = makeAurora({ seed, activity });
+ let mesh = null;
+ g.traverse((o) => { if (o.isMesh && !mesh) mesh = o; });
+ const p = mesh.geometry.getAttribute('position');
+ const B = 180, bins = new Array(B).fill(0);
+ for (let i = 0; i < p.count; i++) {
+ let a = Math.atan2(p.getZ(i), p.getX(i));
+ if (a < 0) a += Math.PI * 2;
+ bins[Math.min(B - 1, Math.floor(a / (Math.PI * 2) * B))] = 1;
+ }
+ // Longest empty run, wrapping: the widest sky with no curtain in it.
+ let best = 0, run = 0;
+ for (let k = 0; k < B * 2; k++) {
+ if (bins[k % B]) run = 0;
+ else { run++; if (run > best) best = run; }
+ }
+ rows.push([seed, activity, Math.min(360, best * 2),
+ bins.reduce((s, x) => s + x, 0) / B]);
+ }
+}
+console.log(JSON.stringify({ rows }));
+""", _LIBS)
+ gaps = [r[2] for r in out["rows"]]
+ covers = [r[3] for r in out["rows"]]
+ worst = max(out["rows"], key=lambda r: r[2])
+ # Independent draws reached 270 degrees and a median of 103; this bound
+ # is one the old generator could not have met.
+ assert worst[2] <= 150, (
+ f"seed {worst[0]} at activity {worst[1]} leaves a {worst[2]} degree "
+ "hole in the sky — a camera can look straight through the display")
+ assert sorted(gaps)[len(gaps) // 2] <= 100, (
+ f"median gap {sorted(gaps)[len(gaps) // 2]} degrees")
+ assert min(covers) >= 0.25, (
+ f"a display covers only {min(covers):.2f} of the compass")
+
+
+def test_the_curtain_alpha_stops_short_of_white():
+ """Port law 2. The saturating curve approaches uPeak, not 1: an aurora
+ that reaches full alpha comes back out of the tone map white, and white
+ is the one colour an aurora is not."""
+ out = measure("""
+import { makeAurora } from './lib/celestial.js';
+const read = (opts) => {
+ const g = makeAurora(opts);
+ let u = null;
+ g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.uniforms && m.uniforms.uPeak) u = m.uniforms.uPeak.value;
+ }
+ });
+ return u;
+};
+console.log(JSON.stringify({ night: read({ seed: 1 }),
+ day: read({ seed: 1, ambient: 0.9 }) }));
+""", _LIBS)
+ assert out["night"] is not None, "the curtain declares no alpha ceiling"
+ assert 0 < out["night"] <= 0.7, (
+ f"the night curtain may reach alpha {out['night']}")
+ assert out["day"] < out["night"], (
+ "the daylight build must be the quieter of the two")
+
+
+def test_the_night_build_is_the_default():
+ """Port law 3. Both sky fields default to the frame they belong in — a
+ dark one — and both still switch to the blend that cannot clip when the
+ caller says the sky behind is bright."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeStars, makeAurora } from './lib/celestial.js';
+const blends = (g) => {
+ const out = [];
+ g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.fragmentShader) out.push([m.name,
+ m.blending === THREE.AdditiveBlending ? 'add' : 'normal']);
+ }
+ });
+ return out.sort();
+};
+console.log(JSON.stringify({
+ starsDefault: blends(makeStars({ count: 60, seed: 1 })),
+ starsBright: blends(makeStars({ count: 60, seed: 1, ambient: 0.9 })),
+ auroraDefault: blends(makeAurora({ seed: 1 })),
+ auroraBright: blends(makeAurora({ seed: 1, ambient: 0.9 })),
+}));
+""", _LIBS)
+ for key in ("starsDefault", "auroraDefault"):
+ assert out[key], f"{key} built no sky material"
+ assert all(mode == "add" for _, mode in out[key]), (
+ f"{key} is not the added-light build: {out[key]}")
+ for key in ("starsBright", "auroraBright"):
+ assert all(mode == "normal" for _, mode in out[key]), (
+ f"{key} still ADDS to a frame the caller called bright: "
+ f"{out[key]}")
+
+
+def test_the_sky_declares_its_own_fog_opt_out():
+ """The firmament sits outside the weather. Our GLSL audit reads a
+ source marker, and the option that writes it is the one its own warning
+ tells you to pass — so passing it has to produce the marker, or the
+ advice does nothing. `3dcv:` is this harness's spelling; the
+ reference's `astra3d:` is still accepted on read."""
+ out = measure("""
+import { makeStars, makeAurora } from './lib/celestial.js';
+const marks = [];
+for (const g of [makeStars({ count: 50, seed: 1 }),
+ makeAurora({ seed: 1 })]) {
+ g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.fragmentShader) {
+ marks.push([m.name, m.fog === false,
+ /(3dcv|astra3d):\\s*no-fog/.test(m.fragmentShader)]);
+ }
+ }
+ });
+}
+console.log(JSON.stringify({ marks }));
+""", _LIBS)
+ assert out["marks"], "no sky materials found"
+ for name, flag, marker in out["marks"]:
+ assert flag, f"{name} does not opt out of fog"
+ assert marker, f"{name} opts out but writes no marker for the checker"
+
+
+def test_one_seed_lays_the_same_sky_twice():
+ out = measure("""
+import { makeStars } from './lib/celestial.js';
+const shape = (seed) => {
+ const g = makeStars({ count: 200, seed });
+ const v = [];
+ g.traverse((o) => {
+ if (!o.isMesh) return;
+ // position is zeroed for the billboard; the sky lives on aDir.
+ const d = o.geometry.getAttribute('aDir');
+ const b = o.geometry.getAttribute('aStar');
+ let s = 0;
+ if (d) for (let i = 0; i < d.count; i += 5) s += d.getX(i) + d.getZ(i);
+ if (b) for (let i = 0; i < b.count; i += 5) s += b.getX(i);
+ v.push(o.name, s.toFixed(5));
+ });
+ return v.join('|');
+};
+console.log(JSON.stringify({
+ same: shape(6) === shape(6),
+ differs: shape(6) !== shape(11),
+}));
+""", _LIBS)
+ assert out["same"] and out["differs"]
+
+
+def test_all_three_compile_on_the_headless_gpu():
+ """rain.js shipped fog chunks that could not compile for months because
+ nothing ever built them. Every shader in this file — including the
+ shimmer's, which only exists once a card is made — goes through a real
+ GLSL compile here."""
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import { makeHeatShimmer, makeStars, makeAurora } from './lib/celestial.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 20, 20] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ // Both builds of both fields, and the shimmer: five programs.
+ scene.add(makeHeatShimmer({ seed: 1 }));
+ scene.add(makeStars({ count: 300, seed: 2 }));
+ scene.add(makeStars({ count: 300, seed: 4, ambient: 0.9 }));
+ scene.add(makeAurora({ seed: 3 }));
+ scene.add(makeAurora({ seed: 5, ambient: 0.9 }));
+ const cameras = [
+ { name: 'sky', position: [0, 2, 12], lookAt: [0, 8, 0], fov: 55 },
+ ];
+ return { scene, cameras, update() {} };
+}
+""", _LIBS)
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_cloth.py b/harness/tests/scene_runtime/lib/test_cloth.py
new file mode 100644
index 00000000..7bc9e610
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_cloth.py
@@ -0,0 +1,780 @@
+"""Cloth and crop have to SHOW the wind, not merely be moved by it.
+
+Each of the three earns its place by one cue, and each of those cues is a
+number rather than a look:
+
+ a flag is held at ONE edge, so its wave amplitude is pinned to zero along
+ the hoist and largest at the fly — a sine over the whole sheet is a
+ rippling billboard with no attachment;
+
+ a banner is hung along its TOP edge, so it swings as the pendulum its own
+ drop makes it (sqrt(g/drop), far slower than a flag flaps) and its folds
+ are functions of x ALONE, which is what "the fold lines run down" means;
+
+ a wheat field's subject is the WAVE, so two stalks a metre apart move
+ together and two fifteen metres apart move with the lag the travel speed
+ sets. Per-stalk motion is a fraction of the shared term, or a hectare of
+ crop boils instead of rippling.
+
+The gust field is a seeded, seamlessly tiling texture rather than
+GLSL_UTIL's unseeded noise, which is what lets these tests read the exact
+numbers the vertex shader samples instead of trusting a claim about one.
+
+Ported 2026-09-01 from the reference's tests/test_cloth_lib.py. Their
+separate `scene_check` (a fogged scene with a casting sun) is folded into the
+one compile test here, because OUR check_shaders.mjs takes a workspace SCENE
+rather than a bare asset: the fixture below sets its own fog and hangs a
+casting sun, so every fog branch and both displaced depth materials are real
+programs rather than dead code.
+
+The grading test at the end is OURS — it holds the colour work done for this
+renderer (ACES, exposure 1.0, no post chain).
+"""
+from __future__ import annotations
+
+import json
+
+from tests.scene_runtime.lib._probe import compile_scene, measure
+
+_LIBS = ("shader.js", "noise.js", "grass.js", "cloth.js")
+
+_SCENE = """
+import * as THREE from 'three';
+import { makeFlag, makeBanner, makeWheatField } from './lib/cloth.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 12, 20] };
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ // Without this USE_FOG is undefined and every fog branch below compiles
+ // to nothing — which is how a library ships fog chunks that cannot
+ // compile at all and nobody finds out.
+ scene.fog = new THREE.FogExp2(0xc9d6e0, 0.02);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ // And without a shadow CASTER the three custom depth materials this
+ // library carries are never compiled either.
+ const sun = new THREE.DirectionalLight(0xfff0d6, 2.5);
+ sun.position.set(5, 8, 7);
+ sun.castShadow = true;
+ scene.add(sun);
+ const wind = { dir: [1, 0.3], strength: 1.1, speed: 1 };
+ scene.add(makeFlag({ width: 1.8, height: 1.1, mast: 6, wind, seed: 3 }));
+ const b = makeBanner({ width: 2.2, drop: 3.2, wind, seed: 5 });
+ b.position.set(5, 0, 0);
+ scene.add(b);
+ scene.add(makeWheatField({ extent: 12, density: 25, wind, seed: 7,
+ shadows: true }));
+ // A camera, because the host reports a scene with none as not booted
+ // and never reaches the compile stage at all.
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [8, 4, 10], lookAt: [0, 2, 0],
+ fov: 45 }],
+ update() {},
+ };
+}
+"""
+
+
+# The GLSL every wheat probe has to agree with: the gust texture is sampled
+# bilinearly with wrapping, and astraStagger decorrelates the per-stalk term.
+# Both are read from the shipped uniforms, so a probe cannot drift from the
+# field it is measuring.
+_WHEAT_READER = """
+const smooth = (e0, e1, x) => {
+ const t = Math.max(0, Math.min(1, (x - e0) / (e1 - e0)));
+ return t * t * (3 - 2 * t);
+};
+const stagger = (x) => (Math.sin(x * 311) * 1.70
+ + Math.sin(x * 137 + 1.1) * 1.15
+ + Math.sin(x * 57 + 2.3) * 0.60) * 4.3;
+const reader = (mesh) => {
+ const g = mesh.geometry, u = mesh.material.userData.uniforms;
+ const pos = g.attributes.iPos.array, crop = g.attributes.iCrop.array;
+ const vary = g.attributes.iVar.array;
+ const tex = u.uWheatWave.value;
+ const W = tex.image.width, H = tex.image.height, D = tex.image.data;
+ const at = (i, j) => D[((((j % H) + H) % H) * W
+ + (((i % W) + W) % W)) * 4] / 255;
+ const sample = (x, y) => {
+ const fx = x * W - 0.5, fy = y * H - 0.5;
+ const i0 = Math.floor(fx), j0 = Math.floor(fy);
+ const tx = fx - i0, ty = fy - j0;
+ return at(i0, j0) * (1 - tx) * (1 - ty) + at(i0 + 1, j0) * tx * (1 - ty)
+ + at(i0, j0 + 1) * (1 - tx) * ty + at(i0 + 1, j0 + 1) * tx * ty;
+ };
+ const w = u.uWheatWind.value, tile = u.uWheatTile.value;
+ const n = g.instanceCount;
+ const A = new Float64Array(n), C = new Float64Array(n);
+ for (let i = 0; i < n; i++) {
+ A[i] = pos[i * 3] * w.x + pos[i * 3 + 2] * w.y;
+ C[i] = -pos[i * 3] * w.y + pos[i * 3 + 2] * w.x;
+ }
+ const wave = (i, t) => smooth(0.34, 0.98,
+ sample((A[i] - u.uWheatMps.value * t) * tile.x, C[i] * tile.y));
+ const solo = (i, t) => u.uWheatJitter.value
+ * Math.sin(t * u.uWheatRate.value + stagger(vary[i * 3]));
+ const bend = (i, t) => crop[i * 4 + 3] * (u.uWheatBase.value
+ + u.uWheatGust.value * wave(i, t) + solo(i, t));
+ return { n, u, A, C, wave, solo, bend,
+ near: (a, c) => {
+ let best = -1, bd = 1e9;
+ for (let i = 0; i < n; i++) {
+ const d = (A[i] - a) * (A[i] - a) + (C[i] - c) * (C[i] - c);
+ if (d < bd) { bd = d; best = i; }
+ }
+ return best;
+ } };
+};
+const pearson = (a, b, off, n) => {
+ let sa = 0, sb = 0;
+ for (let k = 0; k < n; k++) { sa += a[k]; sb += b[k + off]; }
+ sa /= n; sb /= n;
+ let s = 0, va = 0, vb = 0;
+ for (let k = 0; k < n; k++) {
+ const x = a[k] - sa, y = b[k + off] - sb;
+ s += x * y; va += x * x; vb += y * y;
+ }
+ return s / Math.sqrt(Math.max(va * vb, 1e-12));
+};
+"""
+
+
+def _wrapper_json(out: str) -> dict:
+ """The JSON line check_shaders prints after its human summary."""
+ return json.loads(out.strip().splitlines()[-1])
+
+
+def test_all_three_compile_on_the_real_renderer():
+ """Three patched built-ins whose vertex bodies replace `transformed` and
+ rewrite `vNormal`, plus two custom depth materials so the shadows follow
+ the displacement, plus a vertex TEXTURE fetch. Only the GPU can say
+ that GLSL is legal."""
+ _, out = compile_scene(_SCENE, _LIBS)
+ report = _wrapper_json(out)
+ # Every finding that is not glsl_audit's uTime pair. patchStandard
+ # DECLARES and BINDS uTime itself (shader.js `withTime`), which the
+ # static audit cannot see: it fires on six shipped lib modules,
+ # cloth.js among them, and is reported to the foundations agent. A
+ # third kind here is a real one.
+ stale = {"undeclared_uniform", "unbound_uniform"}
+ real = [e for e in report["errors"] if e["kind"] not in stale]
+ assert real == [], out
+ for e in report["errors"]:
+ assert e["file"].endswith("cloth.js"), out
+ # A WARN here is the fog trap or the GTAO trap: both ship an effect that
+ # looks wrong rather than one that errors.
+ assert report["warnings"] == [], out
+ # It got as far as the GPU, and built more programs than it has
+ # materials: the three custom depth materials are the shadow half of
+ # this library and compile separately.
+ #
+ # `custom_materials` counts EVERY material with captured sources, and a
+ # `shadowLike` depth material is one of them — so the three cloths bring
+ # six, not three. Asserted as a floor: the exact number also moves when a
+ # sibling library staged into this scene patches one more material, which
+ # is how this line went stale in the first place.
+ comp = report["compile"]
+ assert comp and comp["custom_materials"] >= 6, out
+ assert comp["programs"] >= 7, out
+
+
+def test_the_flag_is_pinned_at_the_mast_and_free_at_the_fly():
+ """The one cue that says "held at an edge". The envelope is CPU data,
+ not GLSL, so this reads the exact numbers the vertex shader multiplies
+ its travelling sine by: zero along the hoist, largest at the fly, and
+ GROWING — a linear ramp reads as a hinge."""
+ out = measure("""
+import { makeFlag } from './lib/cloth.js';
+const shape = (opts) => {
+ const f = makeFlag(Object.assign({ width: 2, height: 1.2, seed: 3 },
+ opts));
+ const m = f.getObjectByName('FlagSheet');
+ const a = m.geometry.attributes.aFlag.array;
+ const p = m.geometry.attributes.position;
+ const u = m.material.userData.uniforms;
+ const rows = new Map();
+ for (let i = 0; i < p.count; i++) {
+ rows.set(a[i * 4].toFixed(6), [a[i * 4], a[i * 4 + 1]]);
+ }
+ const list = [...rows.values()].sort((x, y) => x[0] - y[0]);
+ let mono = true;
+ for (let i = 1; i < list.length; i++) {
+ if (list[i][1] < list[i - 1][1] - 1e-9) mono = false;
+ }
+ const at = (q) => list.reduce(
+ (b, r) => Math.abs(r[0] - q) < Math.abs(b[0] - q) ? r : b, list[0]);
+ const amp = u.uFlagAmp.value;
+ return {
+ cols: list.length, mono,
+ uMin: list[0][0], uMax: list[list.length - 1][0],
+ envMast: list[0][1], envFly: list[list.length - 1][1],
+ metres: [0, 0.25, 0.5, 0.75, 1].map((q) => amp * at(q)[1]),
+ amp, sag: u.uFlagSag.value, rate: u.uFlagRate.value,
+ k: u.uFlagK.value, shrink: u.uFlagShrink.value,
+ yaw: f.getObjectByName('FlagFly').rotation.y,
+ };
+};
+console.log(JSON.stringify({
+ base: shape({ wind: { dir: [1, 0], strength: 1 } }),
+ hard: shape({ wind: { dir: [1, 0], strength: 2 } }),
+ calm: shape({ wind: { dir: [1, 0], strength: 0.2 } }),
+ east: shape({ wind: { dir: [0, 1], strength: 1 } }),
+}));
+""", _LIBS)
+ b = out["base"]
+ assert b["cols"] > 40, out
+ assert b["uMin"] < 1e-6 and b["uMax"] == 1, out
+ # Pinned at the mast, free at the fly.
+ assert b["envMast"] < 1e-9, out
+ assert b["envFly"] > 1 - 1e-6, out
+ assert b["mono"], out
+ m = b["metres"]
+ assert m[0] < 1e-9, out
+ assert m[4] > 0.15, out
+ # GROWING, not ramping: half way out the sheet carries well under a
+ # third of the fly's swing.
+ assert m[2] < 0.34 * m[4], out
+ assert m[4] / m[2] > 2.9, out
+ for i in range(4):
+ assert m[i] < m[i + 1], out
+ # The wave TRAVELS: a phase that runs over the chord at a rate.
+ assert b["k"] > 5 and b["rate"] > 5, out
+ # A slack flag hangs and a taut one flies, on the one wind option.
+ assert out["hard"]["amp"] > 1.9 * b["amp"], out
+ assert out["calm"]["sag"] > 2.5 * out["hard"]["sag"], out
+ # The sheet is TURNED to the wind; the shader carries no direction.
+ assert abs(b["yaw"]) < 1e-9, out
+ assert abs(out["east"]["yaw"] + 1.5707963) < 1e-6, out
+
+
+def test_the_banner_hangs_from_its_top_edge():
+ """A hung cloth swings about the edge it is hung from, so the swing
+ envelope is zero there and full at the hem, and the rate is the pendulum
+ its own drop makes it — which is what separates a heavy curtain from a
+ flag, and a long curtain from a short one."""
+ out = measure("""
+import { makeBanner, makeFlag } from './lib/cloth.js';
+const b = makeBanner({ width: 2, drop: 3, hang: 4, seed: 5,
+ wind: { dir: [0, 1], strength: 1 } });
+const cloth = b.getObjectByName('BannerCloth');
+const g = cloth.geometry, a = g.attributes.aBan.array;
+const p = g.attributes.position;
+let topS = -1, hemS = 2, topY = -1e9, botY = 1e9, worst = 0;
+for (let i = 0; i < p.count; i++) {
+ const y = p.getY(i), s = a[i * 4];
+ topY = Math.max(topY, y); botY = Math.min(botY, y);
+ if (y > -1e-9) topS = Math.max(topS, s);
+ if (y < -3 + 1e-9) hemS = Math.min(hemS, s);
+ worst = Math.max(worst, Math.abs(s + y / 3));
+}
+const u = cloth.material.userData.uniforms;
+const rateOf = (d) => makeBanner({ drop: d }).getObjectByName('BannerCloth')
+ .material.userData.uniforms.uBanRate.value;
+const flapRate = makeFlag({ width: 2, height: 1.2 })
+ .getObjectByName('FlagSheet').material.userData.uniforms
+ .uFlagRate.value;
+console.log(JSON.stringify({
+ topS, hemS, topY, botY, worst,
+ hang: b.getObjectByName('BannerHang').position.y,
+ yaw: b.getObjectByName('BannerHang').rotation.y,
+ rod: !!b.getObjectByName('BannerRod'),
+ noRod: !makeBanner({ rod: false }).getObjectByName('BannerRod'),
+ rate: u.uBanRate.value, lean: u.uBanLean.value, sway: u.uBanSway.value,
+ lag: u.uBanLag.value, flapRate,
+ rate1: rateOf(1), rate4: rateOf(4),
+}));
+""", _LIBS)
+ # Zero swing at the hanging edge, full swing at the hem.
+ assert out["topS"] == 0, out
+ assert out["hemS"] == 1, out
+ assert out["worst"] < 1e-6, out
+ # The cloth hangs BELOW the point it is hung from, and that point is
+ # `hang` above the group origin.
+ assert out["topY"] == 0 and out["botY"] == -3, out
+ assert out["hang"] == 4, out
+ assert out["rod"] and out["noRod"], out
+ # A pendulum, not a flap: sqrt(g / drop), and a quarter of the rate the
+ # same library flaps a flag at.
+ assert abs(out["rate"] - (9.81 / 3) ** 0.5) < 1e-9, out
+ assert abs(out["rate1"] / out["rate4"] - 2) < 1e-6, out
+ assert out["rate"] < 0.25 * out["flapRate"], out
+ # It leans downwind and swings about that lean, and the hem arrives
+ # after the rod.
+ assert out["lean"] > 0 and out["sway"] > 0 and out["lag"] > 0, out
+ assert abs(out["yaw"]) < 1e-9, out
+
+
+def test_the_banner_folds_run_down_from_where_it_is_hung():
+ """The fold profile, its slope and the width it gathers are all
+ functions of x ALONE — held per vertex, so a column of the cloth carries
+ one fold value from the rod to the hem. Anything that varies down the
+ drop is a diagonal ripple, which is a flag's cue and not a curtain's."""
+ out = measure("""
+import { makeBanner } from './lib/cloth.js';
+const read = (folds) => {
+ const cloth = makeBanner({ width: 2.4, drop: 3, folds, seed: 5 })
+ .getObjectByName('BannerCloth');
+ const g = cloth.geometry, a = g.attributes.aBan.array;
+ const p = g.attributes.position;
+ const cols = new Map();
+ for (let i = 0; i < p.count; i++) {
+ const key = p.getX(i).toFixed(6);
+ if (!cols.has(key)) cols.set(key, []);
+ cols.get(key).push([a[i * 4 + 1], a[i * 4 + 2], a[i * 4 + 3]]);
+ }
+ let spread = 0;
+ for (const rows of cols.values()) {
+ for (let k = 0; k < 3; k++) {
+ const v = rows.map((r) => r[k]);
+ spread = Math.max(spread, Math.max(...v) - Math.min(...v));
+ }
+ }
+ const xs = [...cols.keys()].map(Number).sort((x, y) => x - y);
+ const line = xs.map((x) => cols.get(x.toFixed(6))[0][0]);
+ let crossings = 0, peak = 0;
+ for (let i = 1; i < line.length; i++) {
+ if (line[i] * line[i - 1] < 0) crossings++;
+ peak = Math.max(peak, Math.abs(line[i]));
+ }
+ return { spread, crossings, peak, cols: xs.length,
+ fold: cloth.material.userData.uniforms.uBanFold.value };
+};
+console.log(JSON.stringify({ f3: read(3), f5: read(5), f8: read(8) }));
+""", _LIBS)
+ for key, folds in (("f3", 3), ("f5", 5), ("f8", 8)):
+ r = out[key]
+ # ONE fold value per column, from the rod to the hem.
+ assert r["spread"] < 1e-7, (key, out)
+ # Real folds, and as many of them as were asked for.
+ assert 0.75 < r["peak"] <= 1.01, (key, out)
+ assert 2 * folds - 2 <= r["crossings"] <= 2 * folds + 6, (key, out)
+ # More folds in the same width means SHALLOWER ones, or the cloth
+ # gathers back more than its own span.
+ assert out["f8"]["fold"] < out["f3"]["fold"], out
+
+
+def test_the_wheat_wave_crosses_the_field_not_each_stalk_alone():
+ """The claim the whole library turns on. Two stalks a metre apart move
+ as one; two fifteen metres apart move with the lag the stated travel
+ speed puts between them, and at ZERO lag they disagree. Per-stalk
+ motion is a fraction of the shared wave — reverse that and a hectare of
+ crop boils instead of rippling."""
+ out = measure("""
+import { makeWheatField } from './lib/cloth.js';
+""" + _WHEAT_READER + """
+const f = makeWheatField({ extent: 60, density: 12, height: 1.1, seed: 7,
+ waveMps: 7, maxStalks: 60000,
+ wind: { dir: [1, 0], strength: 1, speed: 1 } });
+const r = reader(f.getObjectByName('Stalks'));
+const DT = 0.02, N = 240, LAGS = 200;
+const series = (fn, i, n) => {
+ const s = new Float64Array(n);
+ for (let k = 0; k < n; k++) s[k] = fn(i, k * DT);
+ return s;
+};
+const varOf = (s) => {
+ let m = 0;
+ for (const v of s) m += v;
+ m /= s.length;
+ let q = 0;
+ for (const v of s) q += (v - m) * (v - m);
+ return q / s.length;
+};
+const median = (v) => v.slice().sort((a, b) => a - b)[v.length >> 1];
+// Sample where the wave IS: a crop between crests is genuinely still, and
+// stillness has nothing to correlate. Every seed puts its calm patches
+// somewhere else, so the calm ones are dropped by measurement and not by
+// being chosen around.
+const spots = [];
+for (let a = -18; a <= 18; a += 6) {
+ for (let c = -12; c <= 12; c += 12) spots.push([a, c]);
+}
+const pairs = (gap) => {
+ const out = [];
+ for (const [a0, c0] of spots) {
+ const p = r.near(a0, c0), q = r.near(r.A[p] + gap, r.C[p]);
+ if (varOf(series(r.wave, p, N)) < 0.01) continue;
+ const sa = series(r.bend, p, N), sb = series(r.bend, q, N + LAGS);
+ let best = -2, bestLag = 0;
+ for (let l = 0; l <= LAGS; l++) {
+ const c = pearson(sa, sb, l, N);
+ if (c > best) { best = c; bestLag = l * DT; }
+ }
+ const d = r.A[q] - r.A[p];
+ out.push({ d, best, bestLag, zero: pearson(sa, sb, 0, N),
+ travel: bestLag > 1e-9 ? d / bestLag : 1e9 });
+ }
+ return {
+ n: out.length,
+ best: median(out.map((o) => o.best)),
+ lag: median(out.map((o) => o.bestLag)),
+ zero: median(out.map((o) => o.zero)),
+ travel: median(out.map((o) => o.travel)),
+ };
+};
+const mid = r.near(0, 0);
+const waveVar = varOf(series((i, t) => r.u.uWheatGust.value * r.wave(i, t),
+ mid, N));
+const soloVar = varOf(series(r.solo, mid, N));
+console.log(JSON.stringify({
+ mps: r.u.uWheatMps.value, n: r.n, spots: spots.length,
+ gust: r.u.uWheatGust.value, jitter: r.u.uWheatJitter.value,
+ waveVar, soloVar, near: pairs(1.5), far: pairs(15),
+}));
+""", _LIBS)
+ assert out["n"] > 5000, out
+ assert out["near"]["n"] >= 8 and out["far"]["n"] >= 8, out
+ # A metre and a half apart is a metre and a half apart: they move as one
+ # field, at the travel lag and very nearly at none.
+ assert out["near"]["best"] > 0.90, out
+ assert out["near"]["zero"] > 0.70, out
+ # Fifteen metres downwind, the SAME motion arrives later — and at the
+ # same instant the two disagree.
+ far = out["far"]
+ assert far["best"] > 0.88, out
+ assert far["lag"] > 0.1, out
+ assert abs(far["travel"] - out["mps"]) < 0.15 * out["mps"], out
+ assert far["zero"] < 0.35, out
+ # The wave is the effect; the stalk is the texture that shows it.
+ assert out["jitter"] < 0.15 * out["gust"], out
+ assert out["soloVar"] < 0.05 * out["waveVar"], out
+
+
+def test_the_wheat_is_sown_in_rows_and_the_grass_is_not():
+ """A crop was planted by a machine, and the drill rows are the cue no
+ meadow has — the difference between this library and a taller copy of
+ grass.js. Measured as the strength of the `rowGap` period in the stalk
+ positions, over every possible sowing angle."""
+ out = measure("""
+import { makeWheatField } from './lib/cloth.js';
+import { makeGrass } from './lib/grass.js';
+const rowiness = (pts, gap) => {
+ let best = 0, bestAng = 0;
+ for (let a = 0; a < 180; a++) {
+ const th = a * Math.PI / 180;
+ const nx = Math.cos(th), nz = Math.sin(th);
+ let sr = 0, si = 0;
+ for (let i = 0; i < pts.length; i += 3) {
+ const p = (pts[i] * nx + pts[i + 2] * nz) / gap * 2 * Math.PI;
+ sr += Math.cos(p); si += Math.sin(p);
+ }
+ const m = Math.hypot(sr, si) / (pts.length / 3);
+ if (m > best) { best = m; bestAng = a; }
+ }
+ return { best, bestAng };
+};
+const wheat = makeWheatField({ extent: 12, density: 40, seed: 7,
+ rowGap: 0.18 })
+ .getObjectByName('Stalks').geometry.attributes.iPos.array;
+const grass = makeGrass({ extent: 12, density: 40, seed: 7 })
+ .getObjectByName('Blades').geometry.attributes.iPos.array;
+console.log(JSON.stringify({
+ wheat: rowiness(wheat, 0.18),
+ wheatWide: rowiness(
+ makeWheatField({ extent: 12, density: 40, seed: 7, rowGap: 0.3 })
+ .getObjectByName('Stalks').geometry.attributes.iPos.array, 0.3),
+ grass: rowiness(grass, 0.18),
+ nWheat: wheat.length / 3, nGrass: grass.length / 3,
+}));
+""", _LIBS)
+ # Sown: nearly every stalk sits on a line at the drill spacing.
+ assert out["wheat"]["best"] > 0.6, out
+ assert out["wheatWide"]["best"] > 0.6, out
+ # Scattered: grass has no such period at all.
+ assert out["grass"]["best"] < 0.15, out
+ assert out["nWheat"] > 1000 and out["nGrass"] > 1000, out
+
+
+def test_one_wind_option_moves_the_wheat_and_the_grass_alike():
+ """`windOf` is imported from grass.js rather than re-read, so a scene
+ that hands one option to its meadow and its crop gets one wind: the same
+ direction, and a strength that scales both."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+import { makeWheatField } from './lib/cloth.js';
+const read = (wind) => {
+ const g = makeGrass({ extent: 6, density: 20, wind })
+ .getObjectByName('Blades').material.userData.uniforms;
+ const w = makeWheatField({ extent: 6, density: 8, wind })
+ .getObjectByName('Stalks').material.userData.uniforms;
+ return {
+ grassDir: g.uGrassWind.value.toArray(),
+ wheatDir: w.uWheatWind.value.toArray(),
+ grassAmp: g.uGrassAmp.value, wheatGust: w.uWheatGust.value,
+ grassSpeed: g.uGrassSpeed.value, wheatMps: w.uWheatMps.value,
+ };
+};
+const wind = { dir: [0.6, -0.8], strength: 1.4, speed: 1.3 };
+console.log(JSON.stringify({
+ full: read(wind),
+ half: read({ dir: [0.6, -0.8], strength: 0.7, speed: 1.3 }),
+ slow: read({ dir: [0.6, -0.8], strength: 1.4, speed: 0.65 }),
+ bare: read(1),
+}));
+""", _LIBS)
+ f = out["full"]
+ # One direction, to the last bit.
+ assert f["grassDir"] == f["wheatDir"], out
+ assert abs(f["grassDir"][0] - 0.6) < 1e-6, out
+ assert out["bare"]["grassDir"] == out["bare"]["wheatDir"], out
+ # One strength: halve it and both fields bend half as far.
+ assert abs(out["half"]["grassAmp"] / f["grassAmp"] - 0.5) < 1e-6, out
+ assert abs(out["half"]["wheatGust"] / f["wheatGust"] - 0.5) < 1e-6, out
+ # One speed: the crop wave's metres per second rides it.
+ assert f["grassSpeed"] == 1.3, out
+ assert abs(f["wheatMps"] - 7 * 1.3) < 1e-6, out
+ assert abs(out["slow"]["wheatMps"] - 7 * 0.65) < 1e-6, out
+
+
+def test_the_stated_sphere_covers_every_moving_part():
+ """Every moving part lives in the vertex shader, so the bounds are a
+ PROMISE the CPU makes: three CULLS on the sphere, and a field that
+ leaves the one it states blinks out the moment its origin leaves the
+ frame. The two sheets are checked against their own displacement,
+ replayed over a full period; the crop against the fact that a stalk
+ bends along an arc of its own length."""
+ out = measure("""
+import { makeFlag, makeBanner, makeWheatField } from './lib/cloth.js';
+const cover = (geo, pts) => {
+ const b = geo.boundingBox, s = geo.boundingSphere;
+ let box = -1e9, sph = -1e9;
+ for (const p of pts) {
+ box = Math.max(box, b.min.x - p[0], p[0] - b.max.x,
+ b.min.y - p[1], p[1] - b.max.y,
+ b.min.z - p[2], p[2] - b.max.z);
+ sph = Math.max(sph, Math.hypot(p[0] - s.center.x, p[1] - s.center.y,
+ p[2] - s.center.z) - s.radius);
+ }
+ return { box, sph, radius: s.radius };
+};
+const flagPts = (strength) => {
+ const m = makeFlag({ width: 2, height: 1.2, seed: 3,
+ wind: { dir: [1, 0], strength } })
+ .getObjectByName('FlagSheet');
+ const g = m.geometry, u = m.material.userData.uniforms;
+ const a = g.attributes.aFlag.array, p = g.attributes.position;
+ const pts = [];
+ for (let f = 0; f < 24; f++) {
+ const t = f / 24 * (2 * Math.PI / u.uFlagRate.value);
+ for (let i = 0; i < p.count; i++) {
+ const ph = u.uFlagK.value * a[i * 4] - u.uFlagRate.value * t
+ + u.uFlagPhase.value + u.uFlagTilt.value * p.getY(i);
+ const sN = Math.sin(ph) + 0.42 * Math.sin(1.7 * ph + 1.3);
+ pts.push([
+ p.getX(i) - Math.min(u.uFlagShrink.value * a[i * 4 + 3],
+ u.uFlagMaxShrink.value),
+ p.getY(i) - u.uFlagSag.value * a[i * 4 + 1],
+ p.getZ(i) + u.uFlagAmp.value * a[i * 4 + 1] * sN]);
+ }
+ }
+ return { g, pts };
+};
+const banPts = (strength) => {
+ const m = makeBanner({ width: 2, drop: 3, seed: 5,
+ wind: { dir: [0, 1], strength } })
+ .getObjectByName('BannerCloth');
+ const g = m.geometry, u = m.material.userData.uniforms;
+ const a = g.attributes.aBan.array, p = g.attributes.position;
+ const pts = [];
+ for (let f = 0; f < 24; f++) {
+ const t = f / 24 * (2 * Math.PI / u.uBanRate.value);
+ for (let i = 0; i < p.count; i++) {
+ const s = a[i * 4], e = s * (2 - s);
+ const ang = u.uBanLean.value + u.uBanSway.value * Math.sin(
+ u.uBanRate.value * t + u.uBanPhase.value - u.uBanLag.value * s);
+ const d = u.uBanDrop.value * s;
+ pts.push([
+ p.getX(i) - Math.max(-u.uBanShrinkMax.value, Math.min(
+ u.uBanShrinkMax.value,
+ u.uBanShrink.value * a[i * 4 + 3] * e * e)),
+ -d * Math.cos(ang),
+ d * Math.sin(ang) + u.uBanFold.value * a[i * 4 + 1] * e]);
+ }
+ }
+ return { g, pts };
+};
+const wheat = makeWheatField({ extent: 20, density: 20, height: 1.2,
+ heightAt: (x, z) => 0.3 * Math.sin(x * 0.2),
+ seed: 4 }).getObjectByName('Stalks');
+const wp = wheat.geometry.attributes.iPos.array;
+const wc = wheat.geometry.attributes.iCrop.array;
+const wpts = [];
+for (let i = 0; i < wheat.geometry.instanceCount; i++) {
+ const x = wp[i * 3], y = wp[i * 3 + 1], z = wp[i * 3 + 2];
+ const h = wc[i * 4];
+ wpts.push([x, y, z], [x + h, y, z], [x - h, y, z],
+ [x, y, z + h], [x, y, z - h], [x, y + h, z]);
+}
+const f1 = flagPts(1), f2 = flagPts(2.5);
+const b1 = banPts(1), b2 = banPts(2.5);
+console.log(JSON.stringify({
+ flag: cover(f1.g, f1.pts), flagHard: cover(f2.g, f2.pts),
+ banner: cover(b1.g, b1.pts), bannerHard: cover(b2.g, b2.pts),
+ wheat: cover(wheat.geometry, wpts),
+ nWheat: wheat.geometry.instanceCount,
+}));
+""", _LIBS)
+ for key in ("flag", "flagHard", "banner", "bannerHard", "wheat"):
+ assert out[key]["box"] <= 1e-6, (key, out)
+ assert out[key]["sph"] <= 1e-6, (key, out)
+ # A 1e4 placeholder would "cover" anything and cull nothing.
+ assert out[key]["radius"] < 100, (key, out)
+ assert out["flag"]["radius"] < 3, out
+ assert out["nWheat"] > 3000, out
+
+
+def test_two_fields_with_one_seed_are_identical():
+ """Determinism is the contract for every shipped factory: a re-run that
+ reshuffles the crop is a re-run nobody can compare against. The gust
+ texture is included, because grass.js's gusts come from GLSL_UTIL's
+ UNSEEDED noise — every grass field in every scene gusts identically, and
+ nothing on the CPU can read what the shader will see."""
+ out = measure("""
+import { makeBanner, makeWheatField } from './lib/cloth.js';
+const banner = (s) => JSON.stringify(Array.from(
+ makeBanner({ width: 2, drop: 3, seed: s })
+ .getObjectByName('BannerCloth').geometry.attributes.aBan.array));
+const stalks = (s) => JSON.stringify(['iPos', 'iCrop', 'iVar'].map((k) =>
+ Array.from(makeWheatField({ extent: 8, density: 20, seed: s })
+ .getObjectByName('Stalks').geometry.attributes[k].array)));
+const gust = (s) => JSON.stringify(Array.from(
+ makeWheatField({ extent: 4, density: 4, seed: s })
+ .getObjectByName('Stalks').material.userData.uniforms
+ .uWheatWave.value.image.data));
+console.log(JSON.stringify({
+ bannerSame: banner(4) === banner(4), bannerDiffer: banner(4) !== banner(9),
+ stalksSame: stalks(4) === stalks(4), stalksDiffer: stalks(4) !== stalks(9),
+ gustSame: gust(4) === gust(4), gustDiffer: gust(4) !== gust(9),
+ n: JSON.parse(stalks(4))[0].length,
+}));
+""", _LIBS)
+ assert out["bannerSame"] and out["bannerDiffer"], out
+ assert out["stalksSame"] and out["stalksDiffer"], out
+ # A seeded gust field, so two fields in one scene do not gust in
+ # lockstep and a test can read what the GPU will sample.
+ assert out["gustSame"] and out["gustDiffer"], out
+ assert out["n"] > 3000, out
+
+
+def test_tick_advances_every_material_including_the_shadows():
+ """Every moving part lives in the vertex shader, so an un-advanced uTime
+ is a photograph of a model. The two custom depth materials share the
+ surface's uniform map on purpose: patch them with their own and the
+ shadow freezes at t = 0 while the cloth keeps moving, which is worse
+ than casting no shadow at all."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeFlag, makeBanner, makeWheatField } from './lib/cloth.js';
+const g = new THREE.Group();
+g.add(makeFlag({ seed: 2 }));
+g.add(makeBanner({ seed: 2 }));
+g.add(makeWheatField({ extent: 4, density: 10, seed: 2 }));
+const times = () => {
+ const out = [];
+ g.traverse((o) => {
+ for (const m of [].concat(o.material || [],
+ o.customDepthMaterial || [])) {
+ if (!m) continue;
+ const u = (m.uniforms && m.uniforms.uTime) ? m.uniforms
+ : (m.userData && m.userData.uniforms);
+ if (u && u.uTime) out.push(u.uTime.value);
+ }
+ });
+ return out;
+};
+const before = times();
+for (const c of g.children) c.userData.tick(2.5);
+console.log(JSON.stringify({ before, after: times(), n: before.length }));
+""", _LIBS)
+ # Three surfaces plus two shadow materials.
+ assert out["n"] == 5, out
+ assert out["before"] == [0] * 5, out
+ assert out["after"] == [2.5] * 5, out
+
+
+def test_wheat_shadows_are_opt_in_and_displaced_when_on():
+ """Same call grass.js makes: 70k stalks in the shadow map are a real
+ SwiftShader cost, so the crop casts only when asked — and then only
+ through a depth material carrying the SAME wave displacement on the
+ surface's own uniform map (its vertex texture fetch included), or the
+ crop's shadow is nothing / a frozen field."""
+ out = measure("""
+import { makeWheatField } from './lib/cloth.js';
+const pick = (g) => {
+ let m;
+ g.traverse((o) => { if (o.name === 'Stalks') m = o; });
+ return m;
+};
+const off = pick(makeWheatField({ extent: 8, density: 30, seed: 3 }));
+const on = pick(makeWheatField({ extent: 8, density: 30, seed: 3,
+ shadows: true }));
+console.log(JSON.stringify({
+ offCasts: off.castShadow, offDepth: !!off.customDepthMaterial,
+ onCasts: on.castShadow,
+ onShared: !!on.customDepthMaterial
+ && on.customDepthMaterial.userData.uniforms
+ === on.material.userData.uniforms,
+ waveInMap: !!(on.customDepthMaterial
+ && on.customDepthMaterial.userData.uniforms.uWheatWave),
+}));
+""", _LIBS)
+ assert not out["offCasts"] and not out["offDepth"], out
+ assert out["onCasts"] and out["onShared"] and out["waveInMap"], out
+
+
+def test_every_cloth_albedo_survives_this_renderer_s_shade():
+ """OURS, not the reference's: the grading pass for a host that runs ACES
+ at exposure 1.0 with no post chain.
+
+ Three claims, all of them numbers. (1) No shipped default has a channel
+ under 0.02 in LINEAR — the reference's flag red and banner crimson sat at
+ 0.021 and 0.019, so every part of a sheet the sun missed tone-mapped to a
+ black-red hole with no cloth in it, and none of them is over 0.8 either.
+ (2) Every effect carries HUE variance rather than one flat hex: the flag
+ and the banner break their dye across the sheet, and the crop ripens in
+ patches from a field-scale term the stalk's own scatter rides on. (3)
+ The fuzz that lights a turning edge is a real term on all three."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeFlag, makeBanner, makeWheatField } from './lib/cloth.js';
+const lin = (c) => [c.r, c.g, c.b];
+const flag = makeFlag({ seed: 1 }).getObjectByName('FlagSheet');
+const ban = makeBanner({ seed: 1 }).getObjectByName('BannerCloth');
+const wheat = makeWheatField({ extent: 6, density: 8, seed: 1 })
+ .getObjectByName('Stalks');
+const fu = flag.material.userData.uniforms;
+const bu = ban.material.userData.uniforms;
+const wu = wheat.material.userData.uniforms;
+console.log(JSON.stringify({
+ flagRGB: lin(flag.material.color),
+ banRGB: lin(ban.material.color),
+ strawRGB: lin(wu.uWheatStraw.value),
+ earRGB: lin(wu.uWheatEar.value),
+ dye: [fu.uFlagDye.value, bu.uBanDye.value],
+ fade: fu.uFlagFade.value, dust: bu.uBanDust.value,
+ sheen: [fu.uFlagSheen.value, bu.uBanSheen.value, wu.uWheatEdge.value],
+ patch: wu.uWheatPatch.value, ripen: wu.uWheatRipen.value,
+ // The tinted default is a DEFAULT: a caller's colour still wins.
+ custom: lin(makeFlag({ color: 0x123456 })
+ .getObjectByName('FlagSheet').material.color),
+}));
+""", _LIBS)
+ for key in ("flagRGB", "banRGB", "strawRGB", "earRGB"):
+ for ch in out[key]:
+ assert 0.02 <= ch <= 0.8, (key, out)
+ # Cloth is dyed, not printed: both sheets break their hue across
+ # themselves, at a swing wide enough to see (astraHueBreak's own
+ # calibration note puts anything under ~0.3 below the visible floor).
+ assert min(out["dye"]) >= 0.3, out
+ assert out["fade"] > 0 and out["dust"] > 0, out
+ # And the crop ripens in PATCHES: a field-scale term, so a stalk's
+ # neighbours are near it in tone rather than random.
+ assert 0.01 < out["patch"] < 0.5, out
+ assert out["ripen"] > 0, out
+ # The fuzz that lights a turning edge — present, and never a rim so hot
+ # it doubles the albedo.
+ for s in out["sheen"]:
+ assert 0.1 < s < 1.0, out
+ assert [round(c, 6) for c in out["custom"]] != [
+ round(c, 6) for c in out["flagRGB"]], out
diff --git a/harness/tests/scene_runtime/lib/test_clouds.py b/harness/tests/scene_runtime/lib/test_clouds.py
new file mode 100644
index 00000000..cb1689bb
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_clouds.py
@@ -0,0 +1,264 @@
+"""clouds.js — one instanced draw, deterministic, sun-lit, driftable.
+
+Built 2026-08-04 in the reference: r184's Sky cloud branch grid-artifacts
+at readable contrast, so hero clouds are this billboard layer.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_clouds_lib.py). Their renderer-contract assertions are kept
+(shader.js still injects the depth chunks, and OUR renderer has no post
+chain, so the tone-map + colour-space tail matters more here, not less).
+The port adds the three things this renderer needed:
+
+* the layer opts OUT of three's fog blend and keeps three's fog
+ UNIFORMS. A deck sits 300-1500 m out, and a scene's FogExp2 is
+ authored for scene-scale geometry: at the density a 120 m courtyard
+ uses (0.0035) every puff resolved to exactly the fog colour — measured
+ on the showcase render, the whole layer was invisible (cloud region
+ (224,233,236) against a (232,239,242) sky). It now mixes its own
+ bounded aerial perspective toward `fogColor`;
+* `sunDir` was documented and ignored — every puff was lit from straight
+ up. It drives the lit side now, and a BELOW-HORIZON sun (what
+ `sunRig().sunDir` keeps reporting at night, by design) is substituted
+ for the moon exactly as environment.js does, or the night deck is lit
+ from under the ground;
+* per-puff height inside its cluster (`iExtra.z`), so a cluster shades
+ as one mass instead of as a bag of identically top-lit blobs.
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("clouds.js",)
+
+_PROBE = """
+import * as THREE from 'three';
+import { makeClouds, makeCirrus, cloudTexture } from './lib/clouds.js';
+
+const a = makeClouds({ seed: 11, preset: 'day' });
+const b = makeClouds({ seed: 11, preset: 'day' });
+const c = makeClouds({ seed: 12, preset: 'day' });
+const offA = a.geometry.getAttribute('iOff').array;
+const offB = b.geometry.getAttribute('iOff').array;
+const offC = c.geometry.getAttribute('iOff').array;
+let sameSeed = offA.length === offB.length;
+if (sameSeed) {
+ for (let i = 0; i < offA.length; i++) {
+ if (offA[i] !== offB[i]) { sameSeed = false; break; }
+ }
+}
+let diffSeed = offA.length !== offC.length;
+if (!diffSeed) {
+ for (let i = 0; i < offA.length; i++) {
+ if (offA[i] !== offC[i]) { diffSeed = true; break; }
+ }
+}
+
+const golden = makeClouds({ seed: 11, preset: 'golden' });
+const t0 = a.material.uniforms.uTime.value;
+a.userData.update(4.2);
+
+// per-puff height within its own cluster
+const ex = a.geometry.getAttribute('iExtra');
+let hMin = 1e9, hMax = -1e9;
+for (let i = 0; i < ex.count; i++) {
+ hMin = Math.min(hMin, ex.getZ(i));
+ hMax = Math.max(hMax, ex.getZ(i));
+}
+
+const tex = cloudTexture(7, 64);
+const d = tex.image.data;
+let alphaSum = 0, bottomRow = 0, topAlpha = 0;
+for (let i = 3; i < d.length; i += 4) alphaSum += d[i];
+for (let x = 0; x < 64; x++) {
+ bottomRow += d[x * 4 + 3];
+ topAlpha += d[((63 * 64) + x) * 4 + 3];
+}
+
+const cirrus = makeCirrus({ seed: 23, count: 8 });
+const cirrusNight = makeCirrus({ seed: 23, count: 8, preset: 'night' });
+
+// the sun actually reaches the shader, and a set sun becomes the moon
+const day = makeClouds({ seed: 3, sunDir: new THREE.Vector3(-0.6, 0.55, -0.3) });
+const set = makeClouds({ seed: 3, sunDir: new THREE.Vector3(0.62, -0.34, 0.21) });
+const noSun = makeClouds({ seed: 3 });
+const dayDir = day.material.uniforms.uSunDir.value.clone();
+const setDir = set.material.uniforms.uSunDir.value.clone();
+
+// Assembled by lib/shader.js, so they carry what three appends to its
+// own fragment shaders: the tone map and the output colour space.
+const layers = [a.material, cirrus.material];
+const fromHelper = layers.every((m) => m.userData.astraShader === true);
+const logdepth = layers.every(
+ (m) => m.vertexShader.includes('<logdepthbuf_pars_vertex>')
+ && m.vertexShader.includes('<logdepthbuf_vertex>')
+ && m.fragmentShader.includes('<logdepthbuf_pars_fragment>')
+ && m.fragmentShader.includes('<logdepthbuf_fragment>'));
+const outChunks = layers.every(
+ (m) => m.fragmentShader.includes('<tonemapping_fragment>')
+ && m.fragmentShader.includes('<colorspace_fragment>'));
+const fogBlend = layers.some(
+ (m) => m.fragmentShader.includes('<fog_fragment>'));
+const readsFog = layers.every(
+ (m) => m.fragmentShader.includes('fogColor')
+ && m.uniforms.fogColor !== undefined
+ && m.uniforms.fogDensity !== undefined
+ && m.fog === true);
+
+console.log(JSON.stringify({
+ sameSeed, diffSeed, fromHelper, logdepth, outChunks, fogBlend, readsFog,
+ isSingleMesh: a.isMesh === true,
+ instances: a.geometry.instanceCount,
+ depthWrite: a.material.depthWrite,
+ t0, tAfter: a.material.uniforms.uTime.value,
+ sunHexDay: a.material.uniforms.uSunColor.value.getHex(),
+ sunHexGolden: golden.material.uniforms.uSunColor.value.getHex(),
+ clusterHMin: hMin, clusterHMax: hMax, extraItems: ex.itemSize,
+ alphaMean: alphaSum / (64 * 64),
+ bottomRowMean: bottomRow / 64,
+ topRowMean: topAlpha / 64,
+ dayDir: [dayDir.x, dayDir.y, dayDir.z],
+ setDir: [setDir.x, setDir.y, setDir.z],
+ noSunDir: noSun.material.uniforms.uSunDir.value.y,
+ cirrusIsMesh: cirrus.isMesh === true,
+ cirrusInstances: cirrus.geometry.instanceCount,
+ cirrusTransparent: cirrus.material.transparent
+ && !cirrus.material.depthWrite,
+ cirrusHexDay: cirrus.material.uniforms.uSunColor.value.getHex(),
+ cirrusHexNight: cirrusNight.material.uniforms.uSunColor.value.getHex(),
+ cirrusGainDay: cirrus.material.uniforms.uLitGain.value,
+ cirrusGainNight: cirrusNight.material.uniforms.uLitGain.value,
+}));
+"""
+
+_SCENE = """
+import * as THREE from 'three';
+import { makeClouds, makeCirrus } from './lib/clouds.js';
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ const sunDir = new THREE.Vector3(-0.6, 0.62, -0.5).normalize();
+ scene.add(makeClouds({ seed: 11, preset: 'day', sunDir }));
+ scene.add(makeCirrus({ seed: 23, sunDir }));
+ const cameras = [{ name: 'sky', position: [0, 3, 12], lookAt: [0, 40, 0] }];
+ return { scene, cameras, update() {} };
+}
+"""
+
+
+def _measure() -> dict:
+ return measure(_PROBE, _LIBS)
+
+
+def test_clouds_are_one_deterministic_instanced_mesh():
+ m = _measure()
+ assert m["isSingleMesh"], "cumulus must be ONE mesh (one draw call)"
+ assert m["instances"] > 40, m["instances"]
+ assert m["sameSeed"], "same seed must rebuild identical instances"
+ assert m["diffSeed"], "different seed must move the field"
+ assert m["depthWrite"] is False, "soft alpha needs depthWrite off"
+
+
+def test_presets_change_the_sun_tint_and_update_drives_drift():
+ m = _measure()
+ assert m["sunHexDay"] != m["sunHexGolden"], "presets must differ"
+ assert m["t0"] == 0 and abs(m["tAfter"] - 4.2) < 1e-9, (
+ "userData.update(t) must drive the wind uniform"
+ )
+
+
+def test_puff_texture_has_body_and_a_flat_base():
+ m = _measure()
+ assert 8 < m["alphaMean"] < 120, (
+ f"puff alpha off the usable band: {m['alphaMean']}"
+ )
+ # DataTexture row 0 = uv bottom: the base cut must leave it empty.
+ assert m["bottomRowMean"] < 2, (
+ f"cloud base is not flat: {m['bottomRowMean']}"
+ )
+
+
+def test_a_cluster_carries_its_own_height_gradient():
+ """Every billboard wearing the same top-lit gradient is what makes a
+ cumulus read as a bag of blobs: the shading needs to know which puffs
+ are the crown and which are the shaded underside of the same mass."""
+ m = _measure()
+ assert m["extraItems"] == 3, "iExtra must carry the in-cluster height"
+ assert m["clusterHMin"] < 0.12 and m["clusterHMax"] > 0.88, (
+ f"in-cluster height must span base to crown: "
+ f"{m['clusterHMin']}..{m['clusterHMax']}"
+ )
+
+
+def test_the_layer_is_lit_by_the_rig_and_a_set_sun_becomes_the_moon():
+ """`sunDir` reached the doc-comment and nothing else, so a low sun and
+ a noon sun painted the same cloud. And `sunRig().sunDir` keeps
+ reporting the authored sun after it sets — passed straight through,
+ every night puff is lit from under the ground."""
+ m = _measure()
+ assert m["dayDir"][1] > 0.5, (
+ f"a daylight sunDir must reach the shader: {m['dayDir']}"
+ )
+ assert m["setDir"][1] > 0.4, (
+ f"a set sun must be replaced by a moon ABOVE the horizon: "
+ f"{m['setDir']}"
+ )
+ assert m["setDir"][0] < 0, "the moon rises opposite the sun"
+ assert m["noSunDir"] == 1.0, "no sunDir keeps the old top-lit look"
+
+
+def test_every_layer_is_assembled_by_the_shader_helper():
+ """A hand-built ShaderMaterial gets neither of the two chunks three
+ appends to its own fragment shaders. THIS renderer has no post
+ chain, so the tone map and the sRGB encode happen in that tail: a
+ shader missing it renders dark and untonemapped next to every
+ built-in in every frame, not just in previews."""
+ m = _measure()
+ assert m["fromHelper"], (
+ "a cloud layer was not built by lib/shader.js makeShaderMaterial "
+ "(no userData.astraShader)"
+ )
+ assert m["logdepth"], "a cloud layer dropped the logdepthbuf chunks"
+ assert m["outChunks"], (
+ "a cloud layer is missing tonemapping_fragment / "
+ "colorspace_fragment — it renders dark and untonemapped"
+ )
+
+
+def test_the_deck_keeps_the_fog_colour_without_taking_the_fog_blend():
+ """Scene fog is authored for scene-scale geometry; a cloud deck is
+ kilometres out. Taking three's blend erases the layer (measured);
+ ignoring fog entirely gives the sticker look. So: no fog_fragment,
+ but the fog uniforms live and `material.fog` stays true so the
+ renderer keeps them current."""
+ m = _measure()
+ assert not m["fogBlend"], (
+ "the deck took three's fog blend: at a courtyard's fog density "
+ "every puff resolves to exactly the fog colour"
+ )
+ assert m["readsFog"], (
+ "the deck must still read fogColor/fogDensity (material.fog "
+ "true) — its haze and its sky bounce come from the scene"
+ )
+
+
+def test_cirrus_is_one_transparent_billboard_mesh_graded_by_preset():
+ # Sprites rendered as black slabs under the post chain (manhattan
+ # run); cirrus rides the proven instanced billboard shader.
+ m = _measure()
+ assert m["cirrusIsMesh"], "cirrus must be ONE instanced mesh"
+ assert m["cirrusInstances"] > 8
+ assert m["cirrusTransparent"]
+ assert m["cirrusHexDay"] != m["cirrusHexNight"], (
+ "cirrus colour was fixed at daylight ice: over a night rig that "
+ "band reads as a light leak"
+ )
+ assert m["cirrusGainNight"] < m["cirrusGainDay"]
+
+
+def test_every_cloud_shader_compiles_on_the_gpu():
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_creature.py b/harness/tests/scene_runtime/lib/test_creature.py
new file mode 100644
index 00000000..6aadb72f
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_creature.py
@@ -0,0 +1,390 @@
+"""Cartoon creatures are their own shape, not small humans.
+
+Cute-ifying figure.js's 7.5-head human yields a small adult; head 40-50%
+of height, egg body and three-layer wide-low eyes are what read as alive.
+
+Ported from the scene_multifile_graphics reference (tests/test_creature_lib.py)
+and extended with what this port had to fix on OUR renderer: albedos inside
+the band ACES at exposure 1 can light, colour graded BETWEEN parts instead of
+one flat value, a belly patch that stands proud of the torso rather than
+z-fighting along it, tails scaled by the creature rather than by a serpent's
+1.5x body depth, and a curl tail that is one piece instead of seven balls.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import measure
+
+pytestmark = pytest.mark.node
+
+
+_PROBE = """
+import * as THREE from 'three';
+import { creature, ear, tail, cheeks, walk, idle } from './lib/creature.js';
+
+const rand = (() => { let s = 5;
+ return () => (s = (s * 16807) % 2147483647) / 2147483647; })();
+
+const c = creature({ height: 0.45, body: 'biped', bodyColor: 0xf5d547,
+ bellyColor: 0xfff0a8, rand });
+ear(c, { type: 'point', length: 0.9, tipColor: 0x2b2b2b });
+tail(c, { type: 'bolt' });
+cheeks(c, 0xe8543f);
+c.updateMatrixWorld(true);
+
+const whole = new THREE.Box3().setFromObject(c);
+const named = {};
+c.traverse((o) => {
+ if (!o.name) return;
+ const b = new THREE.Box3().setFromObject(o);
+ if (!b.isEmpty()) named[o.name] = {
+ c: b.getCenter(new THREE.Vector3()).toArray(),
+ s: b.getSize(new THREE.Vector3()).toArray(),
+ };
+});
+const triCount = (o) => o.geometry.index ? o.geometry.index.count / 3
+ : o.geometry.attributes.position.count / 3;
+let tris = 0;
+c.traverse((o) => { if (o.isMesh) tris += triCount(o); });
+
+// Eye layer count: sclera + iris + glint = 3 meshes under each eye.
+let eyeMeshes = 0;
+c.traverse((o) => { if (o.name === 'eyeL') o.traverse((m) => {
+ if (m.isMesh) eyeMeshes++; }); });
+
+// A quadruped's legs must alternate diagonally, never in lockstep.
+const q = creature({ height: 0.7, body: 'quadruped' });
+walk(q, 0.11);
+const j = q.userData.joints;
+const diag = [j.legFL.rotation.x, j.legBR.rotation.x];
+const other = [j.legFR.rotation.x, j.legBL.rotation.x];
+
+// The three eye layers must be visible FROM THE FRONT, not merely
+// present: they shipped with the iris and glint at +Z, behind the
+// eyeball, and every creature had two blank white blobs for eyes.
+const ray = new THREE.Raycaster();
+const wpos = (o) => new THREE.Vector3().setFromMatrixPosition(o.matrixWorld);
+let eyeObj = null, cheekObj = null;
+c.traverse((o) => { if (o.name === 'eyeL') eyeObj = o;
+ if (o.name === 'cheekL') cheekObj = o; });
+const pe = wpos(eyeObj);
+ray.set(new THREE.Vector3(pe.x, pe.y, -5), new THREE.Vector3(0, 0, 1));
+const eyeHit = ray.intersectObject(c, true)[0];
+const irisFirst = eyeHit
+ ? eyeHit.object.material.color.getHexString() : null;
+let cheekFirst = null;
+if (cheekObj) {
+ const pc2 = wpos(cheekObj);
+ ray.set(new THREE.Vector3(pc2.x, pc2.y, -5), new THREE.Vector3(0, 0, 1));
+ const h = ray.intersectObject(c, true)[0];
+ if (h) { let o = h.object; while (!o.name && o.parent) o = o.parent;
+ cheekFirst = o.name; }
+}
+
+// Idle must actually move something -- and must not stretch the skull
+// with the chest, which is what scaling the shared body pivot did.
+const i0 = creature({ height: 0.5 });
+const restY = i0.userData.joints.head.rotation.y;
+idle(i0, 1.3);
+const idleY = i0.userData.joints.head.rotation.y;
+i0.updateMatrixWorld(true);
+const headScaleY = new THREE.Vector3().setFromMatrixScale(
+ i0.userData.joints.head.matrixWorld).y;
+
+// ALBEDO BAND. A cartoon palette is written as ink; at exposure 1 with
+// no post chain, a 0.99 sclera clips to paper and a 0x151515 pupil has
+// no linear lightness for the sun to lift. Every non-emissive surface
+// has to land inside 0.02..0.80 linear lightness.
+const albedo = [];
+const emissives = [];
+const seen = new Set();
+for (const o of [c, q]) o.traverse((m) => {
+ if (!m.isMesh || seen.has(m.material.uuid)) return;
+ seen.add(m.material.uuid);
+ const mt = m.material;
+ const hsl = mt.color.getHSL({ h: 0, s: 0, l: 0 });
+ const lit = mt.emissive && mt.emissive.getHex() !== 0
+ && mt.emissiveIntensity > 0;
+ if (lit) emissives.push(mt.emissiveIntensity);
+ else albedo.push(+hsl.l.toFixed(4));
+});
+
+// COLOUR GRADED BETWEEN PARTS: head, torso and limb are one hue family
+// at three lightnesses, not one flat value repeated.
+const lin = (mesh) => {
+ let m = null;
+ c.traverse((o) => { if (o.name === mesh) o.traverse((x) => {
+ if (x.isMesh && !m) m = x.material; }); });
+ return m ? m.color.getHSL({ h: 0, s: 0, l: 0 }) : null;
+};
+const headL = lin('headMesh'), torsoL = lin('torso'), legL = lin('legMeshL');
+
+// The BELLY PATCH has to stand clearly proud of the torso. Expressed in
+// the torso ellipsoid's own normalised space, its front pole was at
+// 1.04 -- near-tangent over a wide ring, which renders as a band of
+// z-fighting speckle instead of a bib.
+let torsoM = null, bellyM = null;
+c.traverse((o) => { if (o.name === 'torso') torsoM = o;
+ if (o.name === 'belly') bellyM = o; });
+const bellyProud = (Math.abs(bellyM.position.z - torsoM.position.z)
+ + bellyM.scale.z * 0.5) / (torsoM.scale.z * 0.5);
+
+// A LEGLESS body still rests on y = 0 (the torso sphere is scaled 1.12
+// about its own centre, so it used to dip below the pivot).
+const serp = creature({ height: 1.0, body: 'serpent' });
+tail(serp, { type: 'fin', length: 1.2 });
+serp.updateMatrixWorld(true);
+const sBox = new THREE.Box3().setFromObject(serp);
+let serpTailH = 0;
+serp.traverse((o) => { if (o.name === 'tail') {
+ const b = new THREE.Box3().setFromObject(o);
+ serpTailH = b.max.y - b.min.y; } });
+
+// The CURL tail is one connected piece, not a row of separated balls.
+const cu = creature({ height: 0.7, body: 'quadruped' });
+tail(cu, { type: 'curl' });
+let curlMeshes = 0, curlTris = 0;
+cu.userData.joints.tail.traverse((o) => {
+ if (o.isMesh) { curlMeshes++; curlTris += triCount(o); } });
+
+// A `long` ear's coloured tip must CAP the cone it sits on, never flare
+// out of it -- it shipped with fixed radii and read as a wedge.
+// ONE ear: measured across both, the two shafts pair off against each
+// other and the ratio is 1 whatever the tip does.
+const le = creature({ height: 0.6 });
+ear(le, { type: 'long', length: 1.2, tipColor: 0xffd9a0 });
+let earL = null;
+le.userData.joints.head.traverse((o) => { if (o.name === 'earL') earL = o; });
+const cyl = [];
+earL.traverse((o) => {
+ if (o.isMesh && o.geometry.parameters
+ && o.geometry.parameters.radiusBottom !== undefined) {
+ cyl.push({ p: o.geometry.parameters, y: o.position.y });
+ }
+});
+cyl.sort((a, b) => b.p.height - a.p.height);
+let tipShaft = null;
+if (cyl.length === 2) {
+ const shaft = cyl[0].p, tip = cyl[1];
+ const y0 = tip.y - tip.p.height / 2;
+ const rAt = shaft.radiusBottom
+ + (shaft.radiusTop - shaft.radiusBottom) * (y0 / shaft.height);
+ tipShaft = tip.p.radiusBottom / rAt;
+}
+
+console.log(JSON.stringify({
+ height: whole.max.y - whole.min.y,
+ hUser: c.userData.height,
+ baseY: whole.min.y,
+ headH: named.headMesh ? named.headMesh.s[1] : null,
+ headRatio: named.headMesh
+ ? named.headMesh.s[1] / c.userData.height : null,
+ eyeL: named.eyeL ? named.eyeL.c : null,
+ eyeR: named.eyeR ? named.eyeR.c : null,
+ eyeMeshes,
+ headCy: named.headMesh ? named.headMesh.c[1] : null,
+ hasTail: !!named.tail,
+ hasEars: !!named.earL && !!named.earR,
+ hasCheeks: !!named.cheekL,
+ bodyW: named.torso ? named.torso.s[0] : null,
+ bodyH: named.torso ? named.torso.s[1] : null,
+ forward: c.userData.forward,
+ tris,
+ diagLockstep: Math.abs(diag[0] - diag[1]) < 1e-9,
+ gaitOpposed: diag[0] * other[0] < 0,
+ idleMoves: Math.abs(idleY - restY) > 1e-6,
+ headScaleY,
+ irisFirst,
+ cheekFirst,
+ albedoMin: Math.min(...albedo),
+ albedoMax: Math.max(...albedo),
+ emissives,
+ headL: headL ? +headL.l.toFixed(4) : null,
+ torsoL: torsoL ? +torsoL.l.toFixed(4) : null,
+ legL: legL ? +legL.l.toFixed(4) : null,
+ headHue: headL ? +headL.h.toFixed(4) : null,
+ legHue: legL ? +legL.h.toFixed(4) : null,
+ bellyProud: +bellyProud.toFixed(3),
+ serpBaseY: sBox.min.y,
+ serpH: serp.userData.height,
+ serpTailH,
+ curlMeshes,
+ curlTris,
+ tipShaft: tipShaft === null ? null : +tipShaft.toFixed(3),
+}));
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch of _PROBE, shared by every test that reads it."""
+ return measure(_PROBE, ("creature.js", "materials.js"))
+
+
+def test_the_head_is_oversized_the_way_a_cartoon_creature_is(probe):
+ """40-50% of total height. A human is 13%.
+
+ This single number is what separates a creature from a small adult,
+ and it is the thing a builder gets wrong when handed figure.js.
+ """
+ assert 0.36 < probe["headRatio"] < 0.56, probe["headRatio"]
+
+
+def test_the_eyes_have_three_layers(probe):
+ """Sclera, iris, and an offset glint.
+
+ A sphere with two flat dark dots is exactly what makes a low-poly
+ creature read as a toy instead of as something alive.
+ """
+ assert probe["eyeMeshes"] == 3, probe["eyeMeshes"]
+
+
+def test_the_pupil_is_what_the_camera_sees_first(probe):
+ """Layers present is not layers visible: a front ray must hit the iris.
+
+ The iris/glint shipped at +Z, behind the eyeball (creatures face -Z);
+ the owner caught it on a blank-eyed mascot while every test passed.
+ """
+ r, g, b = (int(probe["irisFirst"][i:i + 2], 16) for i in (0, 2, 4))
+ assert max(r, g, b) < 90, (
+ f"the frontmost thing at the eye centre is #{probe['irisFirst']}, "
+ "not a dark pupil")
+
+
+def test_the_cheek_patch_is_on_the_skull_not_inside_it(probe):
+ """At x = 0.74r the sphere surface is only at z = -0.67r.
+
+ The patch sat at -0.56r and was half buried, showing as two red
+ slivers beside the eyes instead of round cheeks.
+ """
+ assert probe["cheekFirst"] == "cheekL", probe["cheekFirst"]
+
+
+def test_the_eyes_are_wide_and_low_on_the_head(probe):
+ """High close-set eyes read adult; low wide eyes read young."""
+ gap = abs(probe["eyeL"][0] - probe["eyeR"][0])
+ assert gap > 0.25 * probe["headH"], f"eyes too close together: {gap}"
+ assert probe["eyeL"][1] < probe["headCy"] + 0.02, "eyes above head centre"
+ assert probe["eyeL"][2] < 0, "eyes must face -Z, the creature's forward"
+
+
+def test_the_body_is_an_egg_not_a_torso(probe):
+ """Wider than it is tall is the round silhouette."""
+ assert probe["bodyW"] > probe["bodyH"] * 0.85, (probe["bodyW"],
+ probe["bodyH"])
+
+
+def test_attachments_land_and_are_findable(probe):
+ assert probe["hasEars"] and probe["hasTail"] and probe["hasCheeks"], probe
+
+
+def test_it_rests_on_zero_and_faces_minus_z(probe):
+ """Same contract as every other asset, so place.js works on it."""
+ assert abs(probe["baseY"]) < 0.02, probe["baseY"]
+ # The bbox includes the ears, which stand above the skull.
+ assert abs(probe["hUser"] - 0.45) < 0.05, probe["hUser"]
+ assert probe["height"] >= probe["hUser"] * 0.95, (probe["height"],
+ probe["hUser"])
+ assert probe["forward"] == "-Z"
+
+
+def test_a_legless_body_rests_on_the_ground_too(probe):
+ """A serpent's torso is scaled 1.12 in Y about its own centre.
+
+ Taken from the pivot, its underside dips 6% of the body height below
+ zero, and the animal shipped buried to the waist.
+ """
+ assert abs(probe["serpBaseY"]) < 0.02 * probe["serpH"], probe["serpBaseY"]
+
+
+def test_a_quadruped_walks_on_diagonal_pairs(probe):
+ """Legs moving in lockstep is the classic toy-animal tell."""
+ assert probe["diagLockstep"], "diagonal pairs must move together"
+ assert probe["gaitOpposed"], "the other diagonal must be out of phase"
+
+
+def test_idle_actually_moves_something(probe):
+ """A perfectly still creature is a statue in every judged frame."""
+ assert probe["idleMoves"]
+
+
+def test_idle_breathes_with_the_chest_and_not_with_the_skull(probe):
+ """The head is a CHILD of the body pivot that idle() squashes.
+
+ Without the counter-scale the face pulses along with the chest,
+ which reads as a bug in every frame the judge sees. It cancels to
+ 1e-4 rather than exactly, because idle also TILTS the head and a
+ rotated child under a non-uniform parent scale is sheared, not
+ scaled; the defect this guards is 3.5%, two orders above that.
+ """
+ assert abs(probe["headScaleY"] - 1) < 2e-3, probe["headScaleY"]
+
+
+def test_a_village_can_afford_a_crowd_of_them(probe):
+ assert probe["tris"] < 6000, probe["tris"]
+
+
+def test_every_albedo_is_inside_the_band_this_renderer_can_light(probe):
+ """No post chain: ACES at exposure 1 clips a 0.99 sclera to paper.
+
+ And a near-black pupil has no linear lightness left for the sun to
+ lift, so it reads as a hole punched in the face rather than an eye.
+ """
+ assert probe["albedoMin"] >= 0.02, probe["albedoMin"]
+ assert probe["albedoMax"] <= 0.80, probe["albedoMax"]
+
+
+def test_emissives_stay_in_the_bloom_friendly_band(probe):
+ """1.5-4: below it the tone map folds the highlight into its own
+ surface, above it every emissive is the same white blob."""
+ assert probe["emissives"], "the eye glint is emissive"
+ assert all(1.5 <= e <= 4.0 for e in probe["emissives"]), probe["emissives"]
+
+
+def test_the_parts_are_graded_not_one_flat_value(probe):
+ """Face at the author's colour, chest under it, limbs under that.
+
+ A painter does this on every toy; the renderer will not invent it,
+ and without it a body is one flat value with a shadow on it.
+ """
+ assert probe["headL"] > probe["torsoL"] > probe["legL"], probe
+ assert probe["headL"] - probe["legL"] > 0.04, probe
+ # ... and the hue moves too: shaded parts go cool, not just dark.
+ assert abs(probe["headHue"] - probe["legHue"]) > 0.004, probe
+
+
+def test_the_belly_patch_stands_proud_of_the_torso(probe):
+ """Two near-tangent ellipsoids render as a ring of z-fight speckle.
+
+ At the shipped depth the bib's front pole reached 1.04 of the torso
+ radius and its edge was noise, not an outline.
+ """
+ assert probe["bellyProud"] > 1.10, probe["bellyProud"]
+
+
+def test_a_tail_is_scaled_by_the_creature_not_by_its_body_depth(probe):
+ """A serpent's bodyD is 1.5x its height.
+
+ Taken neat as the tail's span it gave a 1.9 m serpent a 3.4 m fin —
+ a pyramid taller than the animal wearing it.
+ """
+ assert probe["serpTailH"] < probe["serpH"], (probe["serpTailH"],
+ probe["serpH"])
+
+
+def test_the_curl_tail_is_one_piece(probe):
+ """Seven separated balls read as a bubble trail leaving the animal.
+
+ One tapered tube also costs 400 triangles instead of 980.
+ """
+ assert probe["curlMeshes"] <= 2, probe["curlMeshes"]
+ assert probe["curlTris"] < 700, probe["curlTris"]
+
+
+def test_a_long_ears_tip_caps_the_cone_it_sits_on(probe):
+ """Fixed tip radii flared out of a `long` ear (0.087 hr wide there)
+ and read as a coloured wedge stuck between the ears."""
+ assert probe["tipShaft"] is not None
+ assert probe["tipShaft"] <= 1.1, probe["tipShaft"]
diff --git a/harness/tests/scene_runtime/lib/test_damp.py b/harness/tests/scene_runtime/lib/test_damp.py
new file mode 100644
index 00000000..2c033e7a
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_damp.py
@@ -0,0 +1,1137 @@
+"""damp.js: moss that has a direction, an apron, and a cracked bed.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_damp_lib.py). Their renderer-contract assertions are dropped; the
+physics claims, the shared-name contract and the option-is-a-uniform law are
+kept, and TWO things this port changed are pinned so a later edit cannot
+quietly undo them:
+
+* the TONE FAMILIES. Every patch used to paint one colour with a brightness
+ ramp over it (measured on our showcase: a metre of moss read as felt and a
+ dried bed as one chip of paint). Each `color` option now derives a family —
+ a moss deep/body/crown plus two lichen crusts, a bed's pale and damp plate —
+ and the SIGN of every hue shift is asserted, because getting it backwards is
+ invisible in code and renders an acid-green cushion.
+* the ROUGHNESS TARGETS. `composeRoughness` is per MATERIAL, so a wet target
+ of 0.34 polished the dry terrace metres from any shore as well; under our
+ renderer (baked sky environment, ACES at exposure 1.0, no post chain) that
+ turned the whole ground into a sky mirror and lifted it from luminance 0.607
+ to 0.823 — brighter, when the entire point of the apron is that it is
+ darker. 0.62 (moisture) and 0.55 (a soaked crack) are the ported values.
+
+These three patches land on materials that already carry a triplanar, a micro
+breakup and a waterline, so the shared contract is asserted first: one world
+base, no name any neighbour owns, and every option a UNIFORM (`patchStandard`
+absorbs a duplicate uniform SILENTLY and the first material to compile a cache
+key fixes the GLSL for every material sharing it).
+"""
+from __future__ import annotations
+
+import json
+import re
+from collections import Counter
+
+import pytest
+from _probe import LIB_DIR, compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "terrain_shade.js", "waterside.js", "surface_wear.js",
+ "aging.js", "accumulation.js", "strata.js", "damp.js")
+
+_LIB_SRC = (LIB_DIR / "damp.js").read_text(encoding="utf-8")
+
+# The patch only exists inside onBeforeCompile, so every probe hands it the two
+# chunks patchStandard replaces and reads back what it wrote. `run` lifts a
+# stretch of the SHIPPED fragment body out and evaluates it: GLSL scalar code
+# is valid JS once the type keywords are dropped and clamp/smoothstep/mix/dot
+# exist, so a claim about the physics can be measured instead of
+# pattern-matched. new Function is sloppy mode even inside a module, which is
+# what makes `with` available.
+_PRELUDE = """
+import * as THREE from 'three';
+import { patchMoss, patchMoisture, patchCrackedMud } from './lib/damp.js';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+import { patchShoreWet, patchShoreFoam } from './lib/waterside.js';
+import { patchDripStains, patchRust, patchDust } from './lib/aging.js';
+import { patchSnow, patchSand } from './lib/accumulation.js';
+import { patchRockStrata, patchErosionStreaks } from './lib/strata.js';
+import { GLSL_UTIL } from './lib/shader.js';
+
+const std = (o = {}) => new THREE.MeshStandardMaterial(
+ Object.assign({ color: 0x8b8478, roughness: 0.7 }, o));
+
+function compile(mat) {
+ const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+ };
+ mat.onBeforeCompile(shader);
+ return shader;
+}
+
+const count = (src, needle) => src.split(needle).length - 1;
+
+const body = (src) => src.slice(src.indexOf('void main'));
+
+/** The shipped fragment body from `from` up to (not including) `to`. */
+function slice_(src, from, to) {
+ const b = body(src);
+ const i = b.indexOf(from);
+ const j = to ? b.indexOf(to, i) : b.length;
+ if (i < 0 || j < 0) throw new Error('no ' + from + ' .. ' + to);
+ return b.slice(i, j);
+}
+
+const GLSL = {
+ clamp: (x, a, b) => Math.min(b, Math.max(a, x)),
+ mix: (a, b, t) => a + (b - a) * t,
+ smoothstep: (e0, e1, x) => {
+ const t = Math.min(1, Math.max(0, (x - e0) / (e1 - e0)));
+ return t * t * (3 - 2 * t);
+ },
+ dot: (a, b) => a.reduce((s, v, i) => s + v * b[i], 0),
+ normalize: (a) => {
+ const l = Math.hypot(...a) || 1;
+ return a.map((v) => v / l);
+ },
+ fwidth: () => 0,
+ max: Math.max, min: Math.min, abs: Math.abs, floor: Math.floor,
+};
+
+/** Evaluate shipped GLSL scalar code with `ctx` in scope. */
+function run(code, ctx) {
+ const js = code.replace(/^\\s*(?:float|vec2|vec3|vec4) /gm, '');
+ const f = new Function('c', 'with (c) {\\n' + js
+ + '\\nreturn (typeof __out === "function") ? __out() : null;\\n}');
+ return f(Object.assign({}, GLSL, ctx));
+}
+"""
+
+# A shoreline strip as a workspace SCENE: a bank rising out of the water to a
+# terrace, a boulder standing clear on it, a wall on its footing and a dried
+# pan on the terrace. The pan's material carries ALL SIX patches, and the
+# cobbles are instanced on that same material because a real instanced program
+# is the only thing that compiles the USE_INSTANCING branch of the world base.
+_SCENE = """
+import * as THREE from 'three';
+import { patchTriplanar } from './lib/terrain_shade.js';
+import { patchMicroBreakup } from './lib/surface_wear.js';
+import { patchShoreWet } from './lib/waterside.js';
+import { patchMoss, patchMoisture, patchCrackedMud } from './lib/damp.js';
+
+const NORTH = [0, 0, -1];
+const WATER_Y = 0.35;
+const BED = new THREE.Vector2(2.5, 2.5);
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 12, 20] };
+
+let s = 20261;
+const rnd = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+const smooth = (t) => t * t * (3 - 2 * t);
+const clamp01 = (t) => Math.max(0, Math.min(1, t));
+
+function bankY(x, z) {
+ const t = smooth(clamp01((z + 4.5) / 6.5));
+ return 1.3 * t
+ + 0.09 * Math.sin(x * 1.13 + 1.1) * Math.sin(z * 0.91)
+ + 0.04 * Math.sin(x * 2.7 - 0.4) * Math.sin(z * 2.3 + 2.0);
+}
+
+function bank() {
+ const g = new THREE.PlaneGeometry(9, 9, 60, 60);
+ g.rotateX(-Math.PI / 2);
+ const p = g.attributes.position;
+ for (let i = 0; i < p.count; i++) p.setY(i, bankY(p.getX(i), p.getZ(i)));
+ g.computeVertexNormals();
+ return g;
+}
+
+function pan(r) {
+ const g = new THREE.CircleGeometry(r, 64);
+ g.rotateX(-Math.PI / 2);
+ const p = g.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ const d = Math.hypot(p.getX(i), p.getZ(i)) / r;
+ p.setY(i, -0.22 * (1 - d * d) + 0.03 * Math.sin(d * 8.0));
+ }
+ g.computeVertexNormals();
+ return g;
+}
+
+function boulder(r, k) {
+ const g = new THREE.SphereGeometry(r, 24, 16);
+ const p = g.attributes.position;
+ const v = new THREE.Vector3();
+ for (let i = 0; i < p.count; i++) {
+ v.fromBufferAttribute(p, i);
+ const n = Math.sin(v.x * k + 1.3) * Math.sin(v.y * (k * 0.8))
+ * Math.sin(v.z * (k * 1.2) + 0.7);
+ v.multiplyScalar(1 + n * 0.18);
+ p.setXYZ(i, v.x, v.y * 0.80, v.z);
+ }
+ g.computeVertexNormals();
+ return g;
+}
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ const sun = new THREE.DirectionalLight(0xfff0d6, 2.5);
+ sun.position.set(5, 8, 7);
+ sun.castShadow = true;
+ scene.add(sun);
+
+ const g = new THREE.Group();
+ const put = (geo, mat, x, y, z) => {
+ const m = new THREE.Mesh(geo, mat);
+ m.position.set(x, y, z);
+ m.castShadow = true;
+ m.receiveShadow = true;
+ g.add(m);
+ return m;
+ };
+ const bed = new THREE.MeshStandardMaterial(
+ { color: 0x9c9280, roughness: 0.85 });
+ const stone = new THREE.MeshStandardMaterial(
+ { color: 0x8e8880, roughness: 0.80 });
+ const ground = new THREE.MeshStandardMaterial(
+ { color: 0x7d7a68, roughness: 0.88 });
+
+ put(bank(), ground, 0, 0, 0);
+ const water = new THREE.Mesh(
+ new THREE.PlaneGeometry(9, 4.4),
+ new THREE.MeshStandardMaterial({ color: 0x24444c, roughness: 0.10 }));
+ water.rotation.x = -Math.PI / 2;
+ water.position.set(0, WATER_Y, -2.6);
+ g.add(water);
+
+ put(pan(1.5), bed, BED.x, bankY(BED.x, BED.y) + 0.24, BED.y);
+ put(boulder(0.75, 5.1), stone, -2.6, bankY(-2.6, 0.8) + 0.48, 0.8);
+ put(boulder(0.34, 7.3), stone, -1.5, bankY(-1.5, 1.7) + 0.22, 1.7);
+
+ const wy = bankY(-3.0, 3.3);
+ put(new THREE.BoxGeometry(2.6, 0.25, 0.80), stone, -3.0, wy + 0.09, 3.3);
+ put(new THREE.BoxGeometry(2.3, 1.50, 0.45), stone, -3.0, wy + 0.96, 3.3);
+ put(new THREE.BoxGeometry(2.5, 0.14, 0.60), stone, -3.0, wy + 1.78, 3.3);
+
+ const cobble = new THREE.InstancedMesh(boulder(0.15, 9.1), bed, 40);
+ const mx = new THREE.Matrix4();
+ for (let i = 0; i < 40; i++) {
+ const a = rnd() * Math.PI * 2;
+ const r = 0.3 + rnd() * 1.7;
+ const x = BED.x + Math.cos(a) * r;
+ const z = BED.y + Math.sin(a) * r;
+ mx.compose(
+ new THREE.Vector3(x, bankY(x, z) + 0.12, z),
+ new THREE.Quaternion().setFromEuler(
+ new THREE.Euler(rnd(), rnd() * 3, rnd())),
+ new THREE.Vector3(1, 0.65 + rnd() * 0.7, 1));
+ cobble.setMatrixAt(i, mx);
+ }
+ cobble.instanceMatrix.needsUpdate = true;
+ cobble.frustumCulled = false;
+ g.add(cobble);
+
+ for (const [mat, seed, tri] of [[bed, 3, 0.6], [stone, 6, 0.8],
+ [ground, 9, 1.4]]) {
+ patchTriplanar(mat, { scale: tri });
+ patchMicroBreakup(mat, { seed, strength: 0.12 });
+ patchShoreWet(mat, { level: WATER_Y, band: 0.25, darken: 0.45 });
+ patchMoss(mat, { amount: 0.5, north: NORTH, seed });
+ patchMoisture(mat, { waterY: WATER_Y, reach: 0.9, strength: 0.5, seed });
+ }
+ patchCrackedMud(bed, { scale: 0.24, depth: 0.75, wet: 0.0, seed: 3 });
+
+ scene.add(g);
+ // A camera is not decoration: the host reports `ok: false` with an EMPTY
+ // error when `cameras` is empty, so a scene with none fails the compile
+ // preflight before a program is built.
+ return {
+ scene,
+ cameras: [{ name: 'hero', position: [9, 4, 11], lookAt: [0, 1, 0],
+ fov: 45 }],
+ update() {},
+ };
+}
+"""
+
+
+def _probe(body: str) -> dict:
+ return measure(_PRELUDE + body, _LIBS)
+
+
+def _find(pattern: str, src: str) -> re.Match:
+ m = re.search(pattern, src)
+ assert m, f"{pattern} not in\n{src}"
+ return m
+
+
+def _main_body(src: str) -> str:
+ return src[src.index("void main"):]
+
+
+def _unguarded(src: str) -> str:
+ """Drop ``#ifndef X ... #endif`` blocks, which may repeat verbatim."""
+ return re.sub(r"#ifndef\b.*?#endif", "", src, flags=re.S)
+
+
+def test_the_six_patch_chain_compiles_clean_on_one_material():
+ """The stack this library exists to join, on our GPU: moss, moisture and
+ cracked mud on the SAME material that already carries a triplanar, a micro
+ breakup and a waterline, in a scene that also puts that material on an
+ InstancedMesh. Only a real instanced draw compiles the USE_INSTANCING
+ branch of the world base, and only a real compile proves four libraries'
+ varyings, helpers and main() locals survive concatenation — including a
+ Voronoi with two nested loops, which is the one thing here a driver could
+ refuse."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out
+ report = json.loads(out.strip().splitlines()[-1])
+ assert report["ok"] and report["errors"] == [], report
+ # bed (six patches), stone/ground (five, one key), water, and the
+ # instanced program for the bed material — the whole point.
+ assert report["compile"]["custom_materials"] >= 3, report
+ assert report["compile"]["programs"] >= 4, report
+ assert report["compile"]["gpu"], report
+
+
+def test_the_three_patches_chain_without_losing_each_other():
+ """All three on one material is the ordinary case, not an exotic one: a
+ shore bed is mossy at its edge, damp across its apron and cracked in its
+ middle. patchStandard chains them, but it repeats whatever it is handed —
+ the shared world base and its five helpers must be emitted ONCE (a second
+ function body now throws), the base must run FIRST or every fragment body
+ reads a varying nobody wrote, and re-applying a patch must retune its
+ uniforms rather than inject a second copy of its code."""
+ out = _probe("""
+const m = std();
+patchMoss(m, { amount: 0.3 });
+patchMoisture(m, { reach: 2 });
+patchCrackedMud(m, { depth: 0.2 });
+patchMoss(m, { amount: 0.8 });
+const s = compile(m);
+const mudOnly = std();
+patchCrackedMud(mudOnly);
+console.log(JSON.stringify({
+ key: m.customProgramCacheKey(), mudKey: mudOnly.customProgramCacheKey(),
+ moss: s.fragmentShader.includes('vec3 msCol = mix(uMossDeep'),
+ moist: s.fragmentShader.includes('float moK ='),
+ mud: s.fragmentShader.includes('vec2 mdC = astraDampCells('),
+ amount: m.userData.uniforms.uMossAmt.value,
+ reach: m.userData.uniforms.uMoistReach.value,
+ worldBody: count(s.vertexShader, 'vec4 dmP ='),
+ axesFn: count(s.fragmentShader, 'vec3 astraDampAxes(vec3 n) {'),
+ noiseFn: count(s.fragmentShader, 'float astraDampNoise('),
+ curvFn: count(s.fragmentShader, 'float astraDampCurv('),
+ siteFn: count(s.fragmentShader, 'vec2 astraDampSite('),
+ cellsFn: count(s.fragmentShader, 'vec2 astraDampCells('),
+ mossLine: count(s.fragmentShader, 'float msD ='),
+ varyVs: count(s.vertexShader, 'varying vec3 vAstraWorld;'),
+ varyFs: count(s.fragmentShader, 'varying vec3 vAstraWorldN;'),
+ baseFirst: s.fragmentShader.indexOf('vec3 astraDampAxes')
+ < s.fragmentShader.indexOf('vec3 msN ='),
+}));
+""")
+ assert out["moss"] and out["moist"] and out["mud"], "a patch was lost"
+ assert out["worldBody"] == 1 and out["axesFn"] == 1
+ assert out["noiseFn"] == 1 and out["curvFn"] == 1
+ assert out["siteFn"] == 1 and out["cellsFn"] == 1
+ assert out["varyVs"] == 1 and out["varyFs"] == 1
+ assert out["baseFirst"], "a fragment body runs before the base helpers"
+ # Every option is a uniform, so re-applying retunes in place.
+ assert out["mossLine"] == 1 and out["amount"] == 0.8
+ assert out["reach"] == 2
+ assert out["key"] == "astra:damp:base+damp:moss+damp:moisture+damp:mud", \
+ out["key"]
+ # A longer chain must not collide with a shorter one's program.
+ assert out["mudKey"] == "astra:damp:base+damp:mud"
+
+
+def test_moss_follows_north_and_up_and_not_a_baked_axis():
+ """Moss sprayed evenly is green paint. What makes it moss is that every
+ rock and wall in the frame carries it on the same side — so the shaded
+ direction is an OPTION, and this evaluates the shipped GLSL against a swept
+ normal to prove it: the north-facing face grows it, the sun-baked face
+ grows NOTHING (the gate is multiplicative, so no field can push growth onto
+ it), rotating `north` by 90 degrees moves the growth to the face that now
+ looks north, and swapping `up` moves which face counts as level. Nothing
+ reads world Y, both vectors are uniforms (two materials with different
+ compasses share one compiled program), a north tipped toward the sky is
+ flattened back to the horizontal, and a degenerate one falls back rather
+ than painting NaN."""
+ out = _probe("""
+const north = std();
+patchMoss(north, { amount: 0.5, north: [0, 0, -1] });
+const east = std();
+patchMoss(east, { amount: 0.5, north: [-1, 0, 0] });
+const zUp = std();
+patchMoss(zUp, { up: [0, 0, 4], north: [1, 0, 0] });
+const tipped = std();
+patchMoss(tipped, { north: [0, 5, -1] });
+const dead = std();
+patchMoss(dead, { north: [0, 1, 0], up: [0, 0, 0] });
+const sa = compile(north), sb = compile(east);
+const u = (m, n) => m.userData.uniforms[n].value.toArray();
+// The whole MASK chain, up to the first colour write, lifted from the
+// shipped source: noise stubbed flat so the DIRECTION is what is being
+// measured, curvature flat so a crevice cannot rescue a face.
+const code = slice_(sa.fragmentShader, ' vec3 msN =',
+ ' diffuseColor.rgb *= 1.0 - 0.20 * msLip;');
+const mask = (n, o = {}) => {
+ const amt = o.uMossAmt === undefined ? 0.5 : o.uMossAmt;
+ return run(code, Object.assign({
+ vAstraWorldN: n, vAstraWorld: [0, 0.4, 0],
+ uMossUp: [0, 1, 0], uMossNorth: [0, 0, -1], uMossAmt: amt,
+ uMossSeed: [0, 0, 0],
+ astraDampAxes: () => [0.34, 0.33, 0.33],
+ astraDampNoise: () => 0.5,
+ astraDampCurv: () => 0,
+ __out: function () {
+ return { k: msK, hold: msHold, sun: msSun,
+ cover: msK * msOn * (0.60 + 0.40 * amt) };
+ },
+ }, o));
+};
+console.log(JSON.stringify({
+ sameKey: north.customProgramCacheKey() === east.customProgramCacheKey(),
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ northU: u(north, 'uMossNorth'), eastU: u(east, 'uMossNorth'),
+ zUpU: [u(zUp, 'uMossUp'), u(zUp, 'uMossNorth')],
+ tipped: u(tipped, 'uMossNorth'),
+ dead: [u(dead, 'uMossUp'), u(dead, 'uMossNorth')],
+ facingNorth: mask([0, 0, -1]),
+ facingSouth: mask([0, 0, 1]),
+ facingEast: mask([1, 0, 0]),
+ level: mask([0, 1, 0]),
+ under: mask([0, -1, 0]),
+ // The same faces once north has been turned a quarter turn.
+ rotNorth: mask([0, 0, -1], { uMossNorth: [-1, 0, 0] }),
+ rotEast: mask([-1, 0, 0], { uMossNorth: [-1, 0, 0] }),
+ // A crevice on a north face is the thickest moss there is — and
+ // `amount` 0 must still mean none of it.
+ crevice: mask([0, 0, -1], { astraDampCurv: () => -20 }),
+ creviceOff: mask([0, 0, -1], { astraDampCurv: () => -20, uMossAmt: 0 }),
+ bakedCrevice: mask([0, 0, 1], { astraDampCurv: () => -20 }),
+ // ...and once up is +Z: the face that is level is the +Z one.
+ zLevel: mask([0, 0, 1], { uMossUp: [0, 0, 1], uMossNorth: [1, 0, 0],
+ vAstraWorld: [0, 0, 0.4] }),
+ yLevel: mask([0, 1, 0], { uMossUp: [0, 0, 1], uMossNorth: [1, 0, 0],
+ vAstraWorld: [0, 0, 0.4] }),
+ moss: slice_(sa.fragmentShader, ' vec3 msN =',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, msCr,'),
+ mixed: sa.fragmentShader.includes(
+ 'diffuseColor.rgb = mix(diffuseColor.rgb, msCol,'),
+}));
+""")
+ assert out["sameKey"] and out["sameFs"], "the compass was baked in"
+ assert out["northU"] == [0, 0, -1] and out["eastU"] == [-1, 0, 0]
+ # A compass direction is horizontal: the part along up is dropped.
+ assert [round(v, 6) for v in out["tipped"]] == [0, 0, -1]
+ assert out["zUpU"][0] == [0, 0, 1], "an unnormalised up must normalise"
+ assert out["dead"][0] == [0, 1, 0], "a zero up must fall back, not NaN"
+ assert abs(out["dead"][1][1]) < 1e-9, "north must not be parallel to up"
+ assert abs(sum(v * v for v in out["dead"][1]) - 1) < 1e-6
+ # THE CLAIM: the shaded face grows moss and the baked one grows none.
+ assert out["facingNorth"]["k"] > 0.5, out["facingNorth"]
+ assert out["facingSouth"]["k"] == 0, out["facingSouth"]
+ assert out["facingSouth"]["sun"] >= 1, "the sun gate must reach 1"
+ assert out["facingNorth"]["k"] > out["facingEast"]["k"]
+ assert out["level"]["hold"] > 0, "a level face holds rain"
+ assert out["level"]["hold"] < out["facingNorth"]["hold"]
+ assert out["under"]["k"] == 0, "a soffit facing away holds nothing"
+ # Turn north a quarter turn and the growth turns with it.
+ assert out["rotEast"]["k"] > 0.5 and out["rotNorth"]["k"] < 0.2, out
+ # A crevice is the thickest growth there is, `amount` 0 is OFF, and a
+ # crevice on a BAKED face keeps only a trace.
+ assert out["crevice"]["hold"] > out["facingNorth"]["hold"]
+ assert out["crevice"]["cover"] >= out["facingNorth"]["cover"] > 0
+ assert out["creviceOff"]["cover"] == 0, out["creviceOff"]
+ assert out["bakedCrevice"]["cover"] < out["crevice"]["cover"], out
+ # Swap up and the face that counts as level swaps too.
+ assert out["zLevel"]["hold"] > out["yLevel"]["hold"]
+ assert out["mixed"], "the growth must mix over the albedo it lands on"
+ moss = out["moss"]
+ # The gate is a FACTOR, so no amount of field can cross it.
+ _find(r"msHold \*= msDry;", moss)
+ _find(r"float msDry = 1\.0 - clamp\(msSun, 0\.0, 1\.0\);", moss)
+ # ...and nothing in the moss reads world Y or a UV for its up: the hue
+ # break projects on the north/up plane, which is why it may not swizzle.
+ assert ".y" not in moss and "vUv" not in moss
+
+
+def test_moisture_reaches_only_within_reach_and_is_zero_beyond_it():
+ """An apron that leaks past its own `reach` is a scene-wide tint: the
+ ground goes dark everywhere and the shore stops meaning anything. The edge
+ has to wander — a level contour is a ruled line no bank has — and a wander
+ added to a ramp is exactly what pushes it past the end, so the wander is
+ faded out by the same ramp that carries it. This evaluates the shipped
+ ramp over a swept height and the whole range of the noise: full damp at the
+ waterline, zero at and beyond `reach` for EVERY noise value, and an edge
+ that still moves by metres in between.
+
+ The port's capillary rim rides the same ramp and is gated at BOTH ends
+ (`moW` past its band and `moT` at the reach), so it cannot smuggle a pale
+ crust onto ground the apron itself does not reach."""
+ out = _probe("""
+const m = std();
+patchMoisture(m, { waterY: 2, reach: 1.5, strength: 0.6 });
+const s = compile(m);
+const code = slice_(s.fragmentShader, ' float moH =', ' float moD =');
+const at = (h, n) => run(code, {
+ vAstraWorld: { y: 2 + h, xz: 0 }, uMoistY: 2, uMoistReach: 1.5,
+ uMoistAmt: 0.6, uMoistSeed: { xz: 0, zx: 0 },
+ astraFbm2: (p) => (p === 0 ? 0.44 + n : 0.44),
+ __out: function () { return [moK, moR]; },
+});
+const sweep = [];
+for (let i = 0; i <= 40; i++) {
+ const h = -0.5 + i * 0.075;
+ sweep.push([+h.toFixed(3), at(h, -0.44), at(h, 0), at(h, 0.44)]);
+}
+console.log(JSON.stringify({
+ sweep,
+ uniforms: {
+ y: m.userData.uniforms.uMoistY.value,
+ reach: m.userData.uniforms.uMoistReach.value,
+ amt: m.userData.uniforms.uMoistAmt.value,
+ },
+ tiny: (() => { const t = std(); patchMoisture(t, { reach: 0 });
+ return t.userData.uniforms.uMoistReach.value; })(),
+ fs: s.fragmentShader,
+}));
+""")
+ assert out["uniforms"] == {"y": 2, "reach": 1.5, "amt": 0.6}
+ assert out["tiny"] > 0, "a zero reach must not divide by zero"
+ sweep = out["sweep"]
+ for h, lo, mid, hi in sweep:
+ if h >= 1.5:
+ for damp, rim in (lo, mid, hi):
+ assert damp == 0, f"damp at {h} m, past a 1.5 m reach"
+ assert rim == 0, f"a crust at {h} m, past a 1.5 m reach"
+ if h <= 0:
+ assert min(lo[0], mid[0], hi[0]) > 0.99, "the waterline is dry"
+ assert max(lo[1], mid[1], hi[1]) == 0, "a crust in the water"
+
+ def edge(col: int) -> float:
+ return max(h for h, *k in sweep if k[col - 1][0] > 0.02)
+
+ # A low noise reaches further up the bank, a high one pulls in.
+ assert 0.2 < edge(3) < edge(2) < edge(1) < 1.5, \
+ [edge(1), edge(2), edge(3)]
+ assert edge(1) - edge(3) > 0.3, "the wander is too small to see"
+ # The crust sits just OUTSIDE the damp, not inside it: its peak is above
+ # the height where the darkening has already gone.
+ rim_peak = max(sweep, key=lambda r: r[2][1])
+ damp_edge = edge(2)
+ assert rim_peak[0] > damp_edge - 0.2, (rim_peak, damp_edge)
+ assert rim_peak[2][1] > 0.15, rim_peak
+ body = _main_body(out["fs"])
+ # The wander is faded by the ramp itself — that is what bounds it.
+ _find(r"float moW = clamp\(moT \+ moN \* [\d.]+ \* moT \* \(1\.0 - moT\),"
+ r" 0\.0, 1\.0\);", body)
+ _find(r"float moT = clamp\(moH / uMoistReach, 0\.0, 1\.0\);", body)
+ # Height above the water plane, which is level by definition.
+ _find(r"float moH = vAstraWorld\.y - uMoistY;", body)
+ # The rim is gated on moW AND on moT: either alone leaves a crust
+ # standing on every surface above the reach, where moW clamps to 1.
+ _find(r"float moR = smoothstep\([\d.]+, [\d.]+, moW\)\s*"
+ r"\* \(1\.0 - smoothstep\([\d.]+, [\d.]+, moW\)\)\s*"
+ r"\* \(1\.0 - smoothstep\([\d.]+, [\d.]+, moT\)\)", body)
+ # Dither against banding on a ramp that runs over metres of near-flat
+ # ground, gated so a surface the apron does not reach is untouched.
+ _find(r"float moD = \(astraHash21\(gl_FragCoord\.xy\) - 0\.5\) \* [\d.]+"
+ r"\s*\* max\(moA, moR\);", body)
+
+
+def test_mud_cracks_are_cells_with_edges_and_not_a_smooth_noise():
+ """What the eye reads in a dried bed is POLYGONS: straight edges, sharp
+ corners, a flat plate between them. A thresholded noise gives none of
+ those — it gives blobs — so the field here is a Voronoi measured to the
+ nearest cell BORDER (F2 - F1 rounds every corner into a blob of its own).
+ The helper is ported line for line from the shipped source and measured:
+ the border field has UNIT gradient almost everywhere, which is what
+ 'distance to a straight edge' means and what smooth noise can never be, and
+ a cell's hash is constant across its whole plate, which is what makes the
+ plates pieces rather than a pattern."""
+ out = _probe("""
+const m = std();
+patchCrackedMud(m, { scale: 0.25, depth: 0.8 });
+const fs = compile(m).fragmentShader;
+// Ported from the shipped helper, line for line; the regexes below pin
+// the port to the source it came from.
+const fract = (x) => x - Math.floor(x);
+function hash21(x, y) {
+ let p = [fract(x * 0.1031), fract(y * 0.1031), fract(x * 0.1031)];
+ const d = p[0] * (p[1] + 33.33) + p[1] * (p[2] + 33.33)
+ + p[2] * (p[0] + 33.33);
+ p = p.map((v) => v + d);
+ return fract((p[0] + p[1]) * p[2]);
+}
+const site = (cx, cy) => [cx + hash21(cx, cy),
+ cy + hash21(cx + 37.7, cy + 37.7)];
+function cells(px, py) {
+ const ix = Math.floor(px), iy = Math.floor(py);
+ let cd = 8, cb = [0, 0], cr = [0, 0];
+ for (let y = -1; y <= 1; y++) for (let x = -1; x <= 1; x++) {
+ const s = site(ix + x, iy + y);
+ const r = [s[0] - px, s[1] - py];
+ const d = r[0] * r[0] + r[1] * r[1];
+ if (d < cd) { cd = d; cb = [x, y]; cr = r; }
+ }
+ cd = 8;
+ for (let y = -1; y <= 1; y++) for (let x = -1; x <= 1; x++) {
+ const s = site(ix + cb[0] + x, iy + cb[1] + y);
+ const r = [s[0] - px, s[1] - py];
+ const e = [r[0] - cr[0], r[1] - cr[1]];
+ const el = Math.hypot(e[0], e[1]);
+ if (el * el > 1e-5) {
+ cd = Math.min(cd, (0.5 * (cr[0] + r[0]) * e[0]
+ + 0.5 * (cr[1] + r[1]) * e[1]) / el);
+ }
+ }
+ return [cd, hash21(ix + cb[0] + 0.37, iy + cb[1] + 0.37)];
+}
+const H = 1e-3, grads = [], noiseGrads = [];
+const hashes = new Set(), noiseVals = new Set();
+const noise = (x, y) => {
+ const i = [Math.floor(x), Math.floor(y)], f = [fract(x), fract(y)];
+ const u = f.map((t) => t * t * (3 - 2 * t));
+ const a = hash21(i[0], i[1]), b = hash21(i[0] + 1, i[1]);
+ const c = hash21(i[0], i[1] + 1), d = hash21(i[0] + 1, i[1] + 1);
+ return (a + (b - a) * u[0]) * (1 - u[1]) + (c + (d - c) * u[0]) * u[1];
+};
+for (let i = 0; i < 60; i++) for (let j = 0; j < 60; j++) {
+ const x = 3.017 + i * 0.1, y = 5.023 + j * 0.1;
+ const d0 = cells(x, y)[0];
+ grads.push(Math.hypot((cells(x + H, y)[0] - d0) / H,
+ (cells(x, y + H)[0] - d0) / H));
+ const n0 = noise(x, y);
+ noiseGrads.push(Math.hypot((noise(x + H, y) - n0) / H,
+ (noise(x, y + H) - n0) / H));
+ if (i < 30 && j < 30) {
+ hashes.add(cells(x, y)[1].toFixed(6));
+ noiseVals.add(noise(x, y).toFixed(6));
+ }
+}
+const med = (a) => a.slice().sort((p, q) => p - q)[a.length >> 1];
+const near1 = (a) => a.filter((g) => g > 0.7 && g < 1.3).length / a.length;
+let changes = 0, worstAt = 0, run_ = 0, longest = 0, prev = null;
+for (let i = 0; i < 400; i++) {
+ const c = cells(3.5 + i * 0.01, 5.5);
+ const h = c[1].toFixed(6);
+ if (prev !== null && h !== prev) {
+ changes++;
+ worstAt = Math.max(worstAt, c[0]);
+ longest = Math.max(longest, run_);
+ run_ = 0;
+ } else { run_++; }
+ prev = h;
+}
+console.log(JSON.stringify({
+ gradMed: med(grads), gradNear1: near1(grads),
+ noiseNear1: near1(noiseGrads),
+ cellCount: hashes.size, noiseCount: noiseVals.size,
+ changes, worstAt, longest,
+ fs,
+}));
+""")
+ # A field of straight edges has |grad| = 1 in cell units; the smooth
+ # noise the alternative would have used does not, anywhere.
+ assert 0.9 < out["gradMed"] < 1.1, out["gradMed"]
+ assert out["gradNear1"] > 0.95, out["gradNear1"]
+ assert out["noiseNear1"] < 0.2, out["noiseNear1"]
+ assert 6 <= out["cellCount"] <= 25, out["cellCount"]
+ assert out["noiseCount"] > 500, out["noiseCount"]
+ # A plate is a PIECE: its id holds across the whole of it and turns over
+ # only where the border distance is zero, which is the border.
+ assert 2 <= out["changes"] <= 10, out["changes"]
+ assert out["worstAt"] < 0.06, out["worstAt"]
+ assert out["longest"] > 30, out["longest"]
+ fs = out["fs"]
+ _find(r"vec2 astraDampSite\(vec2 c\) \{\s*"
+ r"return c \+ vec2\(astraHash21\(c\), astraHash21\(c \+ 37\.7\)\);",
+ fs)
+ _find(r"vec2 astraDampCells\(vec2 p\) \{\s*vec2 ci = floor\(p\);", fs)
+ assert fs.count("for (int y = -1; y <= 1; y++) {") == 2, "one pass only"
+ _find(r"cd = min\(cd, dot\(0\.5 \* \(cr \+ r\), normalize\(e\)\)\);", fs)
+ _find(r"return vec2\(cd, astraHash21\(ci \+ cb \+ [\d.]+\)\);", fs)
+ body = _main_body(fs)
+ _find(r"vec2 mdC = astraDampCells\(mdP \+ mdWp \* [\d.]+\);", body)
+ _find(r"float mdCrk = 1\.0 - smoothstep\(mdW, mdW \* [\d.]+ \+ mdAA,"
+ r" mdC\.x\);", body)
+ _find(r"float mdAA = clamp\(fwidth\(mdC\.x\), 0\.0, [\d.]+\);", body)
+ # The lip: a curled plate is a bright band just inside a dark crack, and
+ # the port makes it WARM as well as bright — it is catching the sun.
+ _find(r"float mdLip = smoothstep\(mdW \* [\d.]+, mdW \* [\d.]+, mdC\.x\)",
+ body)
+ _find(r"mdCol \*= 1\.0 \+ mdLip \* mix\([\d.]+, [\d.]+, uMudDepth\);",
+ body)
+ _find(r"mdCol = mix\(mdCol, mdCol \* vec3\(1\.\d+, 1\.\d+, 0\.\d+\),",
+ body)
+ # A bed is LEVEL: the plates fade off a face an XZ projection smears.
+ _find(r"float mdLie = smoothstep\(0\.[5-9]\d*, 0\.[8-9]\d*, mdN\.y\);",
+ body)
+
+
+def test_every_tone_family_is_derived_and_spreads_the_hue_the_right_way():
+ """The port's aesthetic change, pinned. Each patch used to paint ONE
+ colour with a brightness ramp over it; on the showcase a metre of moss read
+ as felt and a dried bed as a single chip of paint. Each `color` option now
+ derives a FAMILY, and the two things that can silently go wrong are:
+
+ * a tone that is not derived — a caller who sets only `color` would get a
+ cushion and a crust from two different plants;
+ * a hue shifted the WRONG WAY. In HSL, hue rises from yellow through
+ yellow-green to green to blue-green, so the crown (new growth, yellower)
+ must shift DOWN and the shaded depth UP. The first pass had both
+ inverted and rendered an acid-green cushion with a lavender crust —
+ invisible in the source, obvious in a render."""
+ out = _probe("""
+const hsl = (c) => { const o = { h: 0, s: 0, l: 0 }; c.getHSL(o); return o; };
+const fam = (color) => {
+ const m = std();
+ patchMoss(m, { color });
+ patchCrackedMud(m, { color });
+ const u = m.userData.uniforms;
+ const g = {};
+ for (const n of ['uMossColor', 'uMossDeep', 'uMossCrown', 'uMossLichen',
+ 'uMossCrust', 'uMudColor', 'uMudPale', 'uMudDamp']) {
+ g[n] = Object.assign(hsl(u[n].value), { hex: u[n].value.getHex() });
+ }
+ return g;
+};
+const a = fam(0x40592a); // the default damp green
+const b = fam(0x7a3f18); // a rust-brown: the family must follow it
+const wrap = fam(0xc21f6a); // a magenta near the hue seam, to prove wrapping
+console.log(JSON.stringify({ a, b, wrap }));
+""")
+ a, b, wrap = out["a"], out["b"], out["wrap"]
+
+ def dh(fam: dict, tone: str, base: str) -> float:
+ """Signed hue step, wrapped into (-0.5, 0.5]."""
+ d = (fam[tone]["h"] - fam[base]["h"] + 0.5) % 1.0 - 0.5
+ return d
+
+ for fam in (a, b, wrap):
+ # DERIVED, never a default: a different `color` moves every tone.
+ assert len({fam[n]["hex"] for n in
+ ("uMossColor", "uMossDeep", "uMossCrown", "uMossLichen",
+ "uMossCrust")}) == 5, fam
+ assert fam["uMudPale"]["hex"] != fam["uMudDamp"]["hex"]
+ # The crown is the LIGHTER, yellower tone; the depth the darker,
+ # bluer one. Hue direction is the half that renders wrong silently.
+ assert fam["uMossCrown"]["l"] > fam["uMossColor"]["l"] \
+ > fam["uMossDeep"]["l"], fam
+ assert dh(fam, "uMossCrown", "uMossColor") < 0 \
+ < dh(fam, "uMossDeep", "uMossColor"), fam
+ # The depth is the more saturated, the crown less: a cushion goes
+ # deep and rich in its own shade and washes out on its tips.
+ assert fam["uMossDeep"]["s"] > fam["uMossColor"]["s"] \
+ > fam["uMossCrown"]["s"], fam
+ # Both crusts are paler and greyer than the moss, and the ochre one
+ # is a long way round the wheel from the sage one.
+ for crust in ("uMossLichen", "uMossCrust"):
+ assert fam[crust]["l"] > fam["uMossColor"]["l"], fam
+ assert fam[crust]["s"] < fam["uMossColor"]["s"], fam
+ assert abs(dh(fam, "uMossCrust", "uMossLichen")) > 0.12, fam
+ # The bed: the plate that dried first is paler, greyer and yellower;
+ # the one that held its water darker, richer and redder.
+ assert fam["uMudPale"]["l"] > fam["uMudDamp"]["l"], fam
+ assert fam["uMudPale"]["s"] < fam["uMudDamp"]["s"], fam
+ assert dh(fam, "uMudDamp", "uMudColor") < 0 \
+ < dh(fam, "uMudPale", "uMudColor"), fam
+ # No tone may fall off the ends of the range: a lightness clamped to
+ # 0 is a black hole in a cushion, one at 1 is a blown highlight.
+ for n, tone in fam.items():
+ assert 0.02 <= tone["l"] <= 0.80, (n, tone)
+ # A hue near the seam wraps rather than clamping to 0 or 1.
+ assert 0.0 < wrap["uMossCrust"]["h"] < 1.0
+ assert abs(dh(wrap, "uMossCrust", "uMossColor")) > 0.10, wrap
+ # And the shipped GLSL actually consumes the family, rather than
+ # declaring it and painting one colour anyway.
+ for name in ("uMossDeep", "uMossCrown", "uMossCrust", "uMudPale",
+ "uMudDamp"):
+ assert _LIB_SRC.count(name) >= 3, name
+ _find(r"vec3 msCol = mix\(uMossDeep, uMossColor,", _LIB_SRC)
+ _find(r"msCol = mix\(msCol, uMossCrown,", _LIB_SRC)
+ _find(r"vec3 msCr = mix\(uMossCrust, uMossLichen,", _LIB_SRC)
+ _find(r"vec3 mdPl = mix\(uMudDamp, uMudPale,", _LIB_SRC)
+
+
+def test_no_patch_assigns_over_the_colour_it_lands_on():
+ """The defect this library was written after: a triplanar and a slope splat
+ both ASSIGNED diffuseColor.rgb, and whichever ran second erased the other.
+ These three land LAST, on materials that already carry a triplanar, a
+ breakup, a waterline and an aging mark, so every write here must fold in
+ what it was handed: a mix with diffuseColor.rgb on both sides, or a
+ multiply. Nothing may start a new colour — the port's capillary rim
+ included, which is the material's OWN luminance lifted and warmed."""
+ out = _probe("""
+const m = std();
+patchMoss(m); patchMoisture(m); patchCrackedMud(m);
+const chained = std();
+patchTriplanar(chained);
+patchShoreWet(chained);
+patchMoss(chained); patchMoisture(chained); patchCrackedMud(chained);
+console.log(JSON.stringify({
+ fs: compile(m).fragmentShader,
+ chained: compile(chained).fragmentShader,
+}));
+""")
+ body = _main_body(out["fs"])
+ writes = re.findall(r"^\s*diffuseColor\.rgb\s*(\*?=)([^;]*);", body,
+ re.M | re.S)
+ assert len(writes) >= 4, writes
+ for op, rhs in writes:
+ if op == "=":
+ assert "diffuseColor.rgb" in rhs or "moL" in rhs, \
+ f"assigns over: {rhs}"
+ else:
+ assert op == "*=", op
+ # The triplanar underneath survives: its assignment is still the only
+ # one, and every damp write is downstream of it.
+ ch = _main_body(out["chained"])
+ tri = ch.index("diffuseColor.rgb = tpC;")
+ for name in ("msCol", "moA", "mdCol"):
+ assert ch.index(name) > tri, name
+ assert ch.count("diffuseColor.rgb = tpC;") == 1
+
+
+def test_no_patch_declares_a_name_its_neighbours_own():
+ """The silent failure this library is most exposed to: these three ride the
+ same materials as terrain_shade, waterside, surface_wear, aging,
+ accumulation and strata, and patchStandard DROPS a repeated uniform or
+ varying and keeps the first — so a shared name would leave one patch
+ reading the other's value with nothing reported. A repeated main() local
+ is a compile error instead, and a repeated helper now throws. So the
+ uniform sets must be disjoint (uTime excepted, the shared clock) and a
+ material wearing all FIFTEEN patches must declare every name once."""
+ out = _probe("""
+const damp = std();
+patchMoss(damp); patchMoisture(damp); patchCrackedMud(damp);
+const nbr = std();
+patchTriplanar(nbr);
+patchSlopeSplat(nbr, { snowLine: 30 });
+patchShoreWet(nbr);
+patchShoreFoam(nbr);
+patchMicroBreakup(nbr);
+patchEdgeWear(nbr);
+patchDripStains(nbr);
+patchRust(nbr);
+patchDust(nbr);
+patchSnow(nbr);
+patchSand(nbr);
+patchRockStrata(nbr);
+patchErosionStreaks(nbr);
+const all = std();
+for (const p of [patchTriplanar, patchShoreWet, patchShoreFoam,
+ patchMicroBreakup, patchEdgeWear, patchDripStains,
+ patchRust, patchDust, patchSnow, patchSand,
+ patchRockStrata, patchErosionStreaks,
+ patchMoss, patchMoisture, patchCrackedMud]) {
+ p(all);
+}
+patchSlopeSplat(all, { snowLine: 30 });
+const s = compile(all);
+const fns = (src) => (src.match(/^(?:float|vec[234]|int) (\\w+)\\(/gm) || [])
+ .map((m) => m.split(' ')[1].split('(')[0]);
+console.log(JSON.stringify({
+ dampU: Object.keys(damp.userData.uniforms),
+ nbrU: Object.keys(nbr.userData.uniforms),
+ patches: all.userData.astraPatches.map((p) => p.name),
+ dampFns: fns(compile(damp).fragmentShader),
+ nbrFns: fns(compile(nbr).fragmentShader),
+ utilFns: fns(GLSL_UTIL),
+ vs: s.vertexShader, fs: s.fragmentShader,
+}));
+""")
+ shared = set(out["dampU"]) & set(out["nbrU"])
+ assert shared == {"uTime"}, shared
+ # Helpers too, and this one is invisible from inside: two libraries whose
+ # helper shares a name AND a body dedupe silently today and throw the day
+ # either body is edited.
+ util = set(out["utilFns"])
+ clash = (set(out["dampFns"]) - util) & (set(out["nbrFns"]) - util)
+ assert not clash, clash
+ assert {"astraDampAxes", "astraDampCells"} <= set(out["dampFns"])
+ assert {"damp:base", "damp:moss", "damp:moisture",
+ "damp:mud"} <= set(out["patches"])
+ for stage in ("vs", "fs"):
+ src = out[stage]
+ decls = re.findall(
+ r"^\s*(?:uniform|varying)\s+(?:lowp |mediump |highp )?"
+ r"[a-z0-9]+\s+(\w+)\s*;", src, re.M)
+ dupes = [n for n, c in Counter(decls).items() if c > 1]
+ assert not dupes, f"{stage} declares {dupes} twice"
+ fns = re.findall(r"^(?:float|vec[234]|int)\s+(\w+)\s*\(",
+ _unguarded(src), re.M)
+ assert not [n for n, c in Counter(fns).items() if c > 1]
+ locals_ = re.findall(
+ r"^\s*(?:float|vec[234]|int|mat[234])\s+(\w+)\s*=",
+ _main_body(src), re.M)
+ clash = [n for n, c in Counter(locals_).items() if c > 1]
+ assert not clash, f"{stage} main() declares {clash} twice"
+ # Named as the neighbours name them on purpose: ONE world position is
+ # written for the whole chain, not one per library.
+ assert "vAstraWorld" in out["vs"] and "vAstraWorld" in out["fs"]
+ # ...and the base folds in the instance transform, or every copy of a
+ # scattered cobble takes its weather from the mesh ORIGIN.
+ body = _main_body(out["vs"])
+ assert "#ifdef USE_INSTANCING" in body
+ _find(r"dmP = instanceMatrix \* dmP;", body)
+ _find(r"dmN = mat3\(instanceMatrix\) \* dmN;", body)
+ _find(r"vAstraWorld = \(modelMatrix \* dmP\)\.xyz;", body)
+ assert "attribute mat4 instanceMatrix" not in out["vs"]
+ # fwidth, dFdx, gl_FragCoord and astraStroke are fragment-only and the
+ # util block ships in both stages: they may be DEFINED in the vertex
+ # shader, never called from it.
+ assert "fwidth(" not in body and "dFdx(" not in body
+ assert "gl_FragCoord" not in body
+ # Nothing is displaced: the vertex stage is the world base and no more,
+ # or a hard-edged bed would tear open at its rim.
+ assert "transformed +=" not in body and "transformed *=" not in body
+
+
+def test_an_option_is_a_uniform_and_never_baked_into_the_source():
+ """three caches programs by key and the FIRST material to compile a key
+ decides the GLSL every material sharing it gets. Two materials that differ
+ only in options must therefore compile to the same source, or the second
+ silently wears the first's climate — here that would mean one scene's
+ compass, one shoreline's water level and one bed's plate size imposed on
+ every other surface in it. Same key, byte-identical GLSL, different
+ uniform values."""
+ out = _probe("""
+const a = std();
+patchMoss(a, { amount: 0.45, seed: 1 });
+patchMoisture(a, { waterY: 0, reach: 1.5, strength: 0.45, seed: 1 });
+patchCrackedMud(a, { scale: 0.35, depth: 0.5, wet: 0, seed: 1 });
+const b = std();
+patchMoss(b, { amount: 0.95, seed: 99, up: [0, 0, 1], north: [0, 1, 0],
+ color: new THREE.Color(0x112233) });
+patchMoisture(b, { waterY: -7.5, reach: 12, strength: 1, seed: 99 });
+patchCrackedMud(b, { scale: 1.4, depth: 1, wet: 0.8, seed: 99,
+ color: new THREE.Color(0x445566) });
+const sa = compile(a), sb = compile(b);
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ sameKey: a.customProgramCacheKey() === b.customProgramCacheKey(),
+ sameVs: sa.vertexShader === sb.vertexShader,
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ aMoss: [u(a).uMossAmt.value, u(a).uMossUp.value.toArray(),
+ u(a).uMossNorth.value.toArray()],
+ bMoss: [u(b).uMossAmt.value, u(b).uMossUp.value.toArray()],
+ aMoist: [u(a).uMoistY.value, u(a).uMoistReach.value, u(a).uMoistAmt.value],
+ bMoist: [u(b).uMoistY.value, u(b).uMoistReach.value, u(b).uMoistAmt.value],
+ aMud: [u(a).uMudScale.value, u(a).uMudDepth.value, u(a).uMudWet.value],
+ bMud: [u(b).uMudScale.value, u(b).uMudDepth.value, u(b).uMudWet.value],
+ colors: [u(b).uMossColor.value.getHex(), u(b).uMudColor.value.getHex()],
+ lichen: [u(a).uMossLichen.value.getHex(), u(b).uMossLichen.value.getHex()],
+ over: (() => { const m = std();
+ patchMoss(m, { amount: 4 });
+ patchCrackedMud(m, { depth: -2, wet: 9 });
+ return [m.userData.uniforms.uMossAmt.value,
+ m.userData.uniforms.uMudDepth.value,
+ m.userData.uniforms.uMudWet.value]; })(),
+}));
+""")
+ assert out["sameKey"] and out["sameVs"] and out["sameFs"]
+ assert out["aMoss"] == [0.45, [0, 1, 0], [0, 0, -1]]
+ assert out["bMoss"][0] == 0.95 and out["bMoss"][1] == [0, 0, 1]
+ assert out["aMoist"] == [0, 1.5, 0.45]
+ assert out["bMoist"] == [-7.5, 12, 1]
+ assert out["aMud"] == [0.35, 0.5, 0] and out["bMud"] == [1.4, 1, 0.8]
+ assert out["colors"] == [0x112233, 0x445566]
+ # The lichen tone is DERIVED from the moss colour, not a second option,
+ # so one `color` cannot be tuned apart from its own crust.
+ assert out["lichen"][0] != out["lichen"][1]
+ assert out["over"] == [1, 0, 1], "an out-of-range option must clamp"
+
+
+def test_the_gloss_moves_both_ways_through_compose_roughness():
+ """`fragmentBody` lands after <color_fragment> and therefore BEFORE
+ <roughnessmap_fragment> declares roughnessFactor, so no patch here can
+ touch a per-pixel gloss — a mossy boulder that keeps a polished highlight
+ is the tell. All three move the MATERIAL's roughness instead, and they
+ pull OPPOSITE ways on one chain: moss is the mattest thing on a rock, damp
+ ground is the glossiest thing on a shore that is not water, and mud swings
+ from one to the other with `wet`.
+
+ THE TARGETS ARE THE PORT'S, NOT THE REFERENCE'S. Because the factor is
+ per MATERIAL, a wet target polishes the whole surface — the dry terrace
+ metres from any shore included — and under our renderer (baked sky
+ environment, ACES at exposure 1.0, no post chain) the reference's 0.34
+ turned a 0.95-rough bank into a sky mirror: measured on the showcase, the
+ ground went from luminance 0.607 to 0.823, BRIGHTER, when the whole point
+ of the apron is that it is darker. 0.62 is wet soil and 0.55 a crack that
+ is holding water; both keep a broad dull sheen and leave the albedo
+ darkening as the thing the eye reads."""
+ out = _probe("""
+const mossy = std({ roughness: 0.5 });
+patchMoss(mossy, { amount: 1 });
+const mossR = mossy.roughness;
+patchMoss(mossy, { amount: 1 });
+const twice = mossy.roughness;
+const damp = std({ roughness: 0.5 });
+patchMoisture(damp, { strength: 1 });
+const dry = std({ roughness: 0.5 });
+patchCrackedMud(dry, { wet: 0 });
+const wet = std({ roughness: 0.5 });
+patchCrackedMud(wet, { wet: 1 });
+const both = std({ roughness: 0.5 });
+patchMoss(both, { amount: 1 });
+patchMoisture(both, { strength: 1 });
+const rough = std({ roughness: 0.97 });
+patchMoss(rough, { amount: 1 });
+patchCrackedMud(rough, { wet: 0 });
+const none = std({ roughness: 0.5 });
+patchMoss(none, { amount: 0 });
+const ground = std({ roughness: 0.95 });
+patchMoisture(ground, { strength: 0.62 });
+const basic = new THREE.MeshBasicMaterial({ color: 0x445566 });
+patchMoss(basic); patchMoisture(basic); patchCrackedMud(basic);
+console.log(JSON.stringify({
+ mossR, twice, damp: damp.roughness, dry: dry.roughness,
+ wet: wet.roughness, both: both.roughness, rough: rough.roughness,
+ none: none.roughness, ground: ground.roughness,
+ base: both.userData.astraRoughness.base,
+ factors: Object.keys(both.userData.astraRoughness.factors).sort(),
+ basicRough: basic.roughness === undefined,
+ basicPatched: basic.userData.astraPatches.map((p) => p.name),
+}));
+""")
+ assert out["base"] == 0.5, "the authored value is the one to compose on"
+ assert out["factors"] == ["damp:moisture", "damp:moss"]
+ # Moss ROUGHENS and damp ground POLISHES, from the same base.
+ assert out["mossR"] > 0.5 and out["damp"] < 0.5, out
+ assert abs(out["mossR"] - (0.5 + 0.70 * (0.97 - 0.5))) < 1e-9, out
+ # 0.5 * 0.68 = 0.34, under the 0.30 floor's reach: a mid-rough stone
+ # goes to 0.34 when wet, exactly the reference's number.
+ assert abs(out["damp"] - (0.5 + 0.45 * (0.34 - 0.5))) < 1e-9, out
+ assert out["twice"] == out["mossR"], "re-applying compounded the gloss"
+ # Mud swings between the two on one option.
+ assert out["dry"] > 0.5 > out["wet"], out
+ assert abs(out["dry"] - (0.5 + 0.45 * (0.95 - 0.5))) < 1e-9, out
+ assert abs(out["wet"] - (0.5 + 0.45 * (0.31 - 0.5))) < 1e-9, out
+ # THE PORT'S CEILING ON THE POLISH. An outdoor ground is authored rough;
+ # whatever the apron does to it must stay a sheen, not a mirror, because
+ # the whole material wears it. 0.95 -> 0.72 at a strong `strength`; the
+ # reference's numbers gave 0.72 -> 0.58 and rendered brighter than bare.
+ assert out["ground"] > 0.70, out["ground"]
+ # Two factors compose by MULTIPLYING (composeRoughness's contract), so
+ # opposite pulls partly cancel and an already-rough material cannot run
+ # off the top of the range.
+ assert out["damp"] < out["both"] < out["mossR"], out
+ assert 0.04 <= out["rough"] <= 1.0, out["rough"]
+ assert abs(out["none"] - 0.5) < 1e-9, "an absent cover must not retune"
+ # A material with no roughness at all still takes the albedo patch.
+ assert out["basicRough"]
+ assert out["basicPatched"] == ["damp:base", "damp:moss",
+ "damp:moisture", "damp:mud"]
+
+
+def test_one_seed_grows_the_same_moss_every_time():
+ """A render is re-run — for a fix round, for a video, for the judge — and
+ the growth must not move between takes. The seed reaches the GPU only as a
+ noise-space OFFSET (a uniform, because baking it would hand material one's
+ seed to every material sharing the key), so one seed must give one set of
+ offsets, two seeds must not land on the same patches, and the three patches
+ must be decorrelated from each other or every crack would run under a moss
+ cushion. The offsets must also differ from surface_wear's, aging's and
+ accumulation's for the same seed."""
+ out = _probe("""
+const mk = (seed) => {
+ const m = std();
+ patchMoss(m, { seed });
+ patchMoisture(m, { seed });
+ patchCrackedMud(m, { seed });
+ patchMicroBreakup(m, { seed });
+ patchDust(m, { seed });
+ patchSnow(m, { seed });
+ return m;
+};
+const a = mk(7), b = mk(7), c = mk(8);
+const u = (m, n) => m.userData.uniforms[n].value.toArray();
+console.log(JSON.stringify({
+ aMoss: u(a, 'uMossSeed'), bMoss: u(b, 'uMossSeed'), cMoss: u(c, 'uMossSeed'),
+ aMoist: u(a, 'uMoistSeed'), cMoist: u(c, 'uMoistSeed'),
+ aMud: u(a, 'uMudSeed'), cMud: u(c, 'uMudSeed'),
+ aMicro: u(a, 'uMicroSeed'), aDust: u(a, 'uDustSeed'),
+ aSnow: u(a, 'uSnowSeed'),
+ sameSrc: compile(a).fragmentShader === compile(c).fragmentShader,
+}));
+""")
+ assert out["aMoss"] == out["bMoss"], "the same seed moved the moss"
+ assert out["aMoss"] != out["cMoss"] and out["aMud"] != out["cMud"]
+ assert out["aMoist"] != out["cMoist"]
+ assert out["aMoss"] != out["aMud"] != out["aMoist"] != out["aMoss"]
+ for other in ("aMicro", "aDust", "aSnow"):
+ for mine in ("aMoss", "aMoist", "aMud"):
+ assert out[mine] != out[other], f"{mine} rides {other}"
+ assert all(0 <= v <= 40 for v in out["aMoss"] + out["aMud"])
+ # Same GLSL for both seeds: the seed is a uniform, not source.
+ assert out["sameSrc"]
+ assert "Math.random" not in _LIB_SRC
+
+
+def test_moisture_hands_over_to_the_waterline_it_sits_beside():
+ """patchShoreWet owns the waterline — the decimetres either side of it —
+ and this owns the metres beyond. They are meant to be worn together, so
+ the failure to rule out is not a collision of names but a collision of
+ EFFECT: two patches that both assigned the albedo would leave one
+ invisible, and two that both claimed the same uniform would silently share
+ one water level. Both scale what they are handed, so the overlap deepens
+ instead, and the apron is the softer of the two at the same strength — a
+ shore whose apron is darker than its tide mark reads as one flat wet
+ slab."""
+ out = _probe("""
+const m = std();
+patchShoreWet(m, { level: 1.5, band: 0.25, darken: 0.45 });
+patchMoisture(m, { waterY: 1.5, reach: 3, strength: 0.45 });
+const s = compile(m);
+const u = m.userData.uniforms;
+console.log(JSON.stringify({
+ uniforms: Object.keys(u).sort(),
+ wetY: u.uWetY.value, moistY: u.uMoistY.value,
+ key: m.customProgramCacheKey(),
+ fs: s.fragmentShader,
+}));
+""")
+ # Two water levels, two uniforms: one library must never silently take
+ # the other's tide.
+ assert out["wetY"] == out["moistY"] == 1.5
+ assert "uWetY" in out["uniforms"] and "uMoistY" in out["uniforms"]
+ assert out["key"] == ("astra:waterside:base+waterside:shoreWet"
+ "+damp:base+damp:moisture"), out["key"]
+ body = _main_body(out["fs"])
+ # Both fold in what they were handed; neither starts a colour.
+ # waterside's half used to be one multiply (`*= mix(1.0, 1.0 - uWetDark,
+ # wtK)`); it now takes the albedo into a dry/wet pair so wet ground gains
+ # SATURATION as well as depth. The claim under test is unchanged and is
+ # asserted as a chain: the dry end IS what the patch was handed, the wet
+ # end is derived from it, and the assignment only interpolates the two.
+ _find(r"vec3 wtDry = diffuseColor\.rgb;", body)
+ _find(r"vec3 wtWet = mix\(vec3\(wtL\), wtDry, 1\.0 \+ uWetSat\)\s*"
+ r"\* \(1\.0 - uWetDark\);", body)
+ _find(r"diffuseColor\.rgb = mix\(wtDry, max\(wtWet, vec3\(0\.0\)\), wtK\);",
+ body)
+ _find(r"diffuseColor\.rgb = clamp\(\s*"
+ r"mix\(mix\(vec3\(moL\), diffuseColor\.rgb, 1\.0 \+ [\d.]+ \* moA\)"
+ r"\s*\* \(1\.0 - 0\.55 \* moA\),\s*"
+ r"vec3\(moL\) \* vec3\([\d., ]+\), [\d.]+ \* moR\)"
+ r"\s*\+ moD, 0\.0, 1\.0\);", body)
+ # The apron is the SOFTER darkening: shoreWet takes 0.45 of the albedo
+ # at full wet where this takes 0.55 of `strength`.
+ assert 0.55 * 0.45 < 0.45
+ # Wet ground is darker AND deeper in colour, which is the half of "wet"
+ # that a plain multiply cannot say.
+ _find(r"float moL = dot\(diffuseColor\.rgb,"
+ r" vec3\(0\.2126, 0\.7152, 0\.0722\)\);", body)
+ # The JSDoc has to say where the neighbour ends, because nothing in the
+ # source can: they are two patches with one physical edge.
+ doc = _LIB_SRC[:_LIB_SRC.index("export function patchCrackedMud")]
+ assert "patchShoreWet" in doc and "WATERLINE" in doc
diff --git a/harness/tests/scene_runtime/lib/test_dapple.py b/harness/tests/scene_runtime/lib/test_dapple.py
new file mode 100644
index 00000000..f7c8129d
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_dapple.py
@@ -0,0 +1,382 @@
+"""The dappled-light patches: gaps that slide along the sun.
+
+Ported from the reference suite 2026-09-01, plus the four properties the
+port added on our renderer (no post chain, exposure 1.0): a penumbra-wide
+edge, the elongation along the sun's ground track, the crown-scale
+clustering, and the shade that the flecks are flecks ON.
+"""
+
+from __future__ import annotations
+
+from tests.scene_runtime.lib._probe import compile_scene, measure
+
+_LIBS = ("shader.js", "dapple.js")
+
+
+def test_the_pattern_slides_along_the_sun_not_straight_down():
+ """A gap in a canopy projects its patch of light ALONG the sun, so
+ as the canopy drifts the patch travels the way that gap's shadow
+ would. Sampling the pattern at the surface's own xz instead — the
+ obvious way to write it — makes the flecks slide down the world
+ axes, which is the tell that turns dapple into a moving texture.
+ The offset is height / sun.y, so a low sun throws the pattern far
+ across and a noon sun barely offsets it at all."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchDappledLight } from './lib/dapple.js';
+const src = (o) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchDappledLight(m, o);
+ const s = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: '#include <color_fragment>' };
+ m.onBeforeCompile(s);
+ return { fs: s.fragmentShader, u: s.uniforms };
+};
+const a = src({ seed: 1 });
+console.log(JSON.stringify({
+ // The sample point is offset by the sun's horizontal direction over
+ // its vertical one — not by the fragment's own position alone.
+ slidesAlongSun: /vAstraDapW\\.xz\\s*\\+\\s*dpS\\.xz\\s*\\*/.test(a.fs),
+ usesHeightOverUp: /uDapH\\s*\\/\\s*dpUp/.test(a.fs),
+ // Height and sun are uniforms, so two canopies share one program.
+ heightIsUniform: a.u.uDapH !== undefined,
+ sunIsUniform: a.u.uDapSun !== undefined,
+}));
+""", _LIBS)
+ assert out["slidesAlongSun"], "flecks must travel along the sun"
+ assert out["usesHeightOverUp"]
+ assert out["heightIsUniform"] and out["sunIsUniform"]
+
+
+def test_a_sunfleck_is_light_and_not_a_lighter_patch_of_ground():
+ """The one hook the fragment stage gives a patch is ALBEDO, and
+ lifting albedo caps a fleck at the light the surface already gets —
+ which on a shaded forest floor is nearly nothing, exactly where a
+ fleck is the only direct light there is. So it lifts the emissive
+ term, tinted by the albedo underneath, the same choice windows.js
+ and caustics.js document."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchDappledLight } from './lib/dapple.js';
+const m = new THREE.MeshStandardMaterial();
+patchDappledLight(m, {});
+const s = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: '#include <color_fragment>' };
+m.onBeforeCompile(s);
+const body = s.fragmentShader.slice(
+ s.fragmentShader.indexOf('#include <color_fragment>'));
+console.log(JSON.stringify({
+ liftsLight: /totalEmissiveRadiance\\s*\\+=/.test(body),
+ tintedByAlbedo: /totalEmissiveRadiance[^;]*diffuseColor\\.rgb/.test(body),
+ neverWritesAlbedo: !/diffuseColor\\.rgb\\s*[*+]?=/.test(body),
+}));
+""", _LIBS)
+ assert out["liftsLight"], "a fleck is light, not paint"
+ assert out["tintedByAlbedo"]
+ assert out["neverWritesAlbedo"], (
+ "patchDappledLight must leave albedo to whoever owns it")
+
+
+def test_only_what_faces_the_sun_catches_a_fleck():
+ """A fleck lands on what the beam can reach. Without the facing
+ term the underside of a rock lights up as brightly as its top, and
+ the effect reads as glow rather than as light coming through."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchDappledLight } from './lib/dapple.js';
+const m = new THREE.MeshStandardMaterial();
+patchDappledLight(m, {});
+const s = { uniforms: {},
+ vertexShader: 'void main() { #include <begin_vertex> }',
+ fragmentShader: '#include <color_fragment>' };
+m.onBeforeCompile(s);
+console.log(JSON.stringify({
+ facing: /dot\\(normalize\\(vAstraDapN\\), dpS\\)/.test(s.fragmentShader),
+ // The normal is carried in WORLD space, matching the sun it meets.
+ worldNormal: /mat3\\(modelMatrix\\)/.test(s.vertexShader),
+ instanced: /USE_INSTANCING/.test(s.vertexShader),
+}));
+""", _LIBS)
+ assert out["facing"] and out["worldNormal"] and out["instanced"]
+
+
+def test_the_canopy_shade_and_the_flecks_work_at_different_scales():
+ """Crowns are metres across and leaf gaps are centimetres. Given one
+ scale the two patterns beat together and the floor reads as one
+ lumpy texture instead of shade with light coming through it."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchDappledLight, patchCanopyShade } from './lib/dapple.js';
+const m = new THREE.MeshStandardMaterial();
+patchCanopyShade(m, {});
+patchDappledLight(m, {});
+const s = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: '#include <color_fragment>' };
+m.onBeforeCompile(s);
+console.log(JSON.stringify({
+ crown: s.uniforms.uCanScale.value,
+ gap: s.uniforms.uDapScale.value,
+ bothApplied: /uCanCool/.test(s.fragmentShader)
+ && /uDapColor/.test(s.fragmentShader),
+ oneMain: (s.fragmentShader.match(/void main/g) || []).length <= 1,
+}));
+""", _LIBS)
+ assert out["crown"] >= out["gap"] * 5, (
+ "crown and leaf-gap scales must sit an order apart")
+ assert out["bothApplied"] and out["oneMain"]
+
+
+def test_a_fleck_edge_is_the_suns_penumbra_and_never_finer_than_a_pixel():
+ """What separates a sunfleck from a cloud is its EDGE. The sun is
+ 0.53 degrees across, so a canopy 7 m up throws a 6 cm penumbra —
+ under a tenth of a 0.7 m fleck — and the edge has to be built from
+ that height, not from a fixed fraction of the noise's swing (which
+ is what blurred every fleck into fog before the port). The same
+ edge widens to the pixel footprint, so a floor running away from
+ the camera greys out instead of crawling."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchDappledLight } from './lib/dapple.js';
+const m = new THREE.MeshStandardMaterial();
+patchDappledLight(m, { height: 7 });
+const s = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: '#include <color_fragment>' };
+m.onBeforeCompile(s);
+const fs = s.fragmentShader;
+console.log(JSON.stringify({
+ penumbraFromHeight: /dpPen\\s*=\\s*0\\.0046\\d*\\s*\\*\\s*uDapH/.test(fs),
+ antialiased: /fwidth\\(dpP\\.x\\)/.test(fs),
+ widthFeedsTheThreshold: /astraDapGaps\\(dpP, uDapDens, dpW\\)/.test(fs),
+}));
+""", _LIBS)
+ assert out["penumbraFromHeight"], "the edge must come from the height"
+ assert out["antialiased"] and out["widthFeedsTheThreshold"]
+
+
+def test_a_fleck_is_stretched_along_the_suns_ground_track():
+ """A round gap seen from a 38 degree sun lands as an ellipse 1.6x
+ long, and it is that elongation — not the brightness — that says
+ where the sun is. The sample is compressed along the sun's ground
+ track by 1/sin(elevation), clamped so a sun on the horizon does not
+ smear the pattern into stripes."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchDappledLight } from './lib/dapple.js';
+const m = new THREE.MeshStandardMaterial();
+patchDappledLight(m, {});
+const s = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: '#include <color_fragment>' };
+m.onBeforeCompile(s);
+const fs = s.fragmentShader;
+console.log(JSON.stringify({
+ axisIsTheSunsGroundTrack: /vec2 dpAx = dpS\\.xz;/.test(fs),
+ stretch: /dpEl\\s*=\\s*clamp\\(1\\.0 \\/ dpUp, 1\\.0, 3\\.0\\)/.test(fs),
+ compressesAlongIt: /dot\\(dpP, dpAx\\)/.test(fs),
+}));
+""", _LIBS)
+ assert out["axisIsTheSunsGroundTrack"]
+ assert out["stretch"], "the stretch must be capped for a low sun"
+ assert out["compressesAlongIt"]
+
+
+def test_the_shade_tracks_density_and_the_fleck_is_paid_back_for_it():
+ """`density` is coverage: the crown field is THRESHOLDED by it, not
+ scaled by it. Scaling as well (what this did before the port) made
+ the default half-canopy a 9 percent darkening — a flat card, and
+ nothing for a fleck to be bright against. And because the shade is
+ a stand-in for a shadow three will not cast, the albedo it removes
+ must be given back to the fleck: light that came through a gap
+ never met the canopy at all."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchDappledLight, patchCanopyShade } from './lib/dapple.js';
+const run = (shaded) => {
+ const m = new THREE.MeshStandardMaterial();
+ if (shaded) patchCanopyShade(m, { density: 0.6 });
+ patchDappledLight(m, { strength: 0.55 });
+ const s = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: '#include <color_fragment>' };
+ m.onBeforeCompile(s);
+ return s;
+};
+const bare = run(false), shaded = run(true);
+console.log(JSON.stringify({
+ bareAmt: bare.uniforms.uDapAmt.value,
+ shadedAmt: shaded.uniforms.uDapAmt.value,
+ // The darkening is the depth times the coverage mask, with no
+ // second density factor riding on the amplitude.
+ thresholdedByDensity:
+ /cnT = mix\\(0\\.72, 0\\.10, uCanDens\\)/.test(shaded.fragmentShader),
+ depthIsAUniform: shaded.uniforms.uCanDepth.value > 0.5,
+ ditheredAgainstBanding: /astraHash21\\(gl_FragCoord\\.xy\\)/
+ .test(shaded.fragmentShader),
+}));
+""", _LIBS)
+ assert out["bareAmt"] == 0.55, "an unshaded surface pays nothing back"
+ assert 0.55 < out["shadedAmt"] <= 0.55 * 1.7, (
+ "a shaded surface's flecks are lifted by what the shade took")
+ assert out["thresholdedByDensity"] and out["depthIsAUniform"]
+ assert out["ditheredAgainstBanding"]
+
+
+_SCENE = """
+import * as THREE from 'three';
+import { patchDappledLight, patchCanopyShade } from './lib/dapple.js';
+import { patchTriplanar } from './lib/terrain_shade.js';
+import { patchMicroBreakup } from './lib/surface_wear.js';
+import { tickShaders } from './lib/shader.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 10, 20] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ const sun = new THREE.DirectionalLight(0xfff0d8, 3.0);
+ sun.position.set(8, 6, 4);
+ scene.add(sun);
+ scene.add(new THREE.HemisphereLight(0x9fb6d6, 0x4a4436, 1.0));
+
+ // The floor a forest agent really builds: triplanar dirt, micro
+ // breakup, canopy shade, then the flecks — four bodies in one main.
+ const mat = new THREE.MeshStandardMaterial({ color: 0x5f5a43,
+ roughness: 0.95 });
+ patchTriplanar(mat, { scale: 2.0 });
+ patchMicroBreakup(mat, {});
+ patchCanopyShade(mat, { density: 0.6 });
+ patchDappledLight(mat, { height: 7, density: 0.55, seed: 3,
+ sunDir: sun.position.clone().normalize() });
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(24, 24, 8, 8), mat);
+ floor.rotateX(-Math.PI / 2);
+ scene.add(floor);
+
+ // The instancing branch of both vertex bodies, really compiled.
+ const posts = new THREE.InstancedMesh(
+ new THREE.CylinderGeometry(0.2, 0.25, 3, 8), mat, 3);
+ const m4 = new THREE.Matrix4();
+ for (let i = 0; i < 3; i++) {
+ m4.makeTranslation(-3 + i * 3, 1.5, -2);
+ posts.setMatrixAt(i, m4);
+ }
+ posts.castShadow = true;
+ scene.add(posts);
+
+ // A camera, because the host reports a scene with none as not booted
+ // and never reaches the compile stage at all.
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [9, 4, 11], lookAt: [0, 1, 0],
+ fov: 45 }],
+ update(t) { tickShaders(scene, t); },
+ };
+}
+"""
+
+
+def test_the_chain_compiles_on_the_real_renderer():
+ """The only witness that counts. Whether the GPU accepts four
+ chained bodies in one main, an fwidth() inside a patch body, a
+ three-field helper returning a vec2 and the instancing branch of two
+ vertex bodies cannot be asserted from source, and a patch that does
+ not compile is worth nothing."""
+ code, out = compile_scene(
+ _SCENE, ("shader.js", "dapple.js", "terrain_shade.js",
+ "surface_wear.js", "noise.js"))
+ assert code == 0, out
+ assert "every program compiled" in out
+ # A patched built-in keeps the built-in's own depth and fog chunks,
+ # so nothing here may be flagged as discardable.
+ assert "DISCARDED" not in out
+
+
+def test_one_seed_lays_the_same_canopy_twice():
+ out = measure("""
+import * as THREE from 'three';
+import { patchDappledLight } from './lib/dapple.js';
+const key = (seed) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchDappledLight(m, { seed });
+ const s = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: '#include <color_fragment>' };
+ m.onBeforeCompile(s);
+ return { seed: s.uniforms.uDapSeed.value, src: s.fragmentShader.length };
+};
+const a = key(3), b = key(3), c = key(9);
+console.log(JSON.stringify({
+ same: a.seed === b.seed && a.src === b.src,
+ differs: a.seed !== c.seed,
+ // A different seed must NOT recompile: it is a uniform, not source.
+ sameSource: a.src === c.src,
+}));
+""", _LIBS)
+ assert out["same"] and out["differs"] and out["sameSource"]
+
+
+def test_the_fleck_takes_its_colour_from_where_the_sun_is():
+ """A fleck is a picture of the sun, so a dusk scene cannot have noon
+ flecks: with no `color` given, the default is read off `sunDir` —
+ warm-white overhead, orange near the horizon. An explicit colour
+ still wins, and the leaf-transmission rim keeps the fleck from
+ being one flat tone."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchDappledLight } from './lib/dapple.js';
+const at = (y, o = {}) => {
+ const m = new THREE.MeshStandardMaterial();
+ const dir = new THREE.Vector3(0.6, y, 0.3).normalize();
+ patchDappledLight(m, Object.assign({ sunDir: dir }, o));
+ const s = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: '#include <color_fragment>' };
+ m.onBeforeCompile(s);
+ return s;
+};
+const high = at(0.9).uniforms.uDapColor.value;
+const low = at(0.10).uniforms.uDapColor.value;
+const forced = at(0.9, { color: 0x336699 }).uniforms.uDapColor.value;
+const fs = at(0.9).fragmentShader;
+console.log(JSON.stringify({
+ highBlue: high.b, lowBlue: low.b,
+ highWarmth: high.r - high.b, lowWarmth: low.r - low.b,
+ forced: [forced.r, forced.g, forced.b],
+ rimIsLeafTransmission: /mix\\(uDapLeaf, uDapColor, dpCore\\)/.test(fs),
+ hueVariesWithinTheEffect: /astraHueBreak\\(dpTint/.test(fs),
+}));
+""", _LIBS)
+ assert out["lowWarmth"] > out["highWarmth"] > 0, (
+ "a low sun throws warmer flecks than a high one")
+ assert out["lowBlue"] < out["highBlue"]
+ # Colours live in three's LINEAR working space, so 0x336699 is not
+ # (0.2, 0.4, 0.6) here — what matters is that it is the caller's
+ # blue and not the warm default.
+ assert out["forced"][2] > out["forced"][0], "an explicit colour wins"
+ assert out["rimIsLeafTransmission"] and out["hueVariesWithinTheEffect"]
+
+
+def test_gaps_crowd_where_the_crown_is_thin():
+ """An even scatter of flecks reads as camouflage. A canopy is not
+ evenly thin, so the gap threshold is modulated at crown scale — an
+ order coarser than the leaf gaps and coarser again than the branch
+ field — and the flecks cluster into the thin patches the way they
+ do under a real tree."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchDappledLight } from './lib/dapple.js';
+const m = new THREE.MeshStandardMaterial();
+patchDappledLight(m, {});
+const s = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: '#include <color_fragment>' };
+m.onBeforeCompile(s);
+const fs = s.fragmentShader;
+const freq = (re) => Number((fs.match(re) || [0, 0])[1]);
+console.log(JSON.stringify({
+ leaf: 1.0,
+ branch: freq(/astraFbm2\\(p \\* (0\\.\\d+) \\+ 11\\.3, 2\\)/),
+ crown: freq(/astraFbm2\\(p \\* (0\\.\\d+) \\+ 5\\.1, 2\\)/),
+ modulatesTheThreshold: /t = mix\\([^)]*\\) \\+ \\(c - 0\\.375\\)/.test(fs),
+ // Core and rim come out of one call: a second gap evaluation per
+ // pixel to find the middle of a fleck is not worth its samples.
+ oneCall: (fs.match(/astraDapGaps\\(dpP/g) || []).length === 1,
+}));
+""", _LIBS)
+ assert out["crown"] < out["branch"] < out["leaf"], (
+ "leaf gaps, branch gaps and crowns must sit at three scales")
+ assert out["modulatesTheThreshold"] and out["oneCall"]
diff --git a/harness/tests/scene_runtime/lib/test_environment.py b/harness/tests/scene_runtime/lib/test_environment.py
new file mode 100644
index 00000000..0fd8f8f0
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_environment.py
@@ -0,0 +1,266 @@
+"""environment.js — worldShell, makeOutskirts and the sunRig package, measured under node.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference (tests/test_environment_lib.py).
+Changed for OUR renderer: the environment is a linear HALF-FLOAT bake from the graded sky
+model (sampled here through DataUtils.fromHalfFloat), the day horizon is 0xdbe3ea, night is
+a brighter moon rig (2.2 / fill 1.0 — the reference's 0.8 / 0.6 measured 30-40 % of the
+frame under the dark threshold on ACES exposure 1.0), and a SET SUN (elevation < 0) is
+night with a moon opposite the sun.
+"""
+from __future__ import annotations
+
+import math
+
+import pytest
+from _probe import measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "noise.js", "sky.js", "environment.js")
+
+
+def _measure(script: str) -> dict:
+ return measure(script, _LIBS)
+
+
+_SHELL = """
+import * as THREE from 'three';
+import { worldShell } from './lib/environment.js';
+const rand = (() => { let s = 9; return () => (s = (s * 16807) % 2147483647) / 2147483647; })();
+const env = worldShell({ rand, mood: 'day' });
+env.group.updateMatrixWorld(true);
+const hitsFor = (dir) => new THREE.Raycaster(new THREE.Vector3(0, 1.7, 0), dir.normalize()).intersectObject(env.group, true).map((h) => h.object.name);
+const outward = [];
+for (let a = 0; a < 8; a++) outward.push(hitsFor(new THREE.Vector3(Math.cos(a / 8 * Math.PI * 2), 0, Math.sin(a / 8 * Math.PI * 2))));
+const sky = env.group.getObjectByName('SkyGradient');
+const cols = sky.geometry.attributes.color, pos = sky.geometry.attributes.position;
+let zenithB = null, horizonB = null;
+for (let i = 0; i < pos.count; i++) { if (pos.getY(i) > 3990) zenithB = cols.getZ(i); if (Math.abs(pos.getY(i)) < 40) horizonB = cols.getZ(i); }
+let tris = 0;
+env.group.traverse((o) => { if (o.isMesh) tris += o.geometry.attributes.position.count / 3; });
+const noRidge = worldShell({ rand, mood: 'day', ridge: false });
+const T = (rho, d) => Math.exp(-((rho * d) ** 2));
+const mk = () => () => 0.5;
+const big = worldShell({ rand: mk(), mood: 'day', bounds: 1200 });
+const over = worldShell({ rand: mk(), mood: 'overcast', bounds: 1200 });
+console.log(JSON.stringify({ outward, fogHex: env.fog.color.getHexString(), zenithB, horizonB, tris: Math.round(tris),
+ ridgeOptional: !noRidge.group.getObjectByName('HorizonRidge'), fogIsExp2: env.fog.isFogExp2 === true,
+ smallD: worldShell({ rand: mk(), mood: 'day', bounds: 150 }).fog.density, bareD: worldShell({ rand: mk(), mood: 'day' }).fog.density,
+ bigFarT: T(big.fog.density, 2400), overFarT: T(over.fog.density, 2400), unclampedFarT: T(env.fog.density, 2400),
+ explicitWins: worldShell({ rand: mk(), mood: 'day', bounds: 1200, fogDensity: 0.01 }).fog.density === 0.01 }));
+"""
+
+
[email protected](scope="module")
+def shell() -> dict:
+ return _measure(_SHELL)
+
+
+def test_no_outward_ray_escapes_into_void(shell):
+ for hits in shell["outward"]:
+ assert "HorizonRidge" in hits and "SkyGradient" in hits, shell["outward"]
+
+
+def test_the_fog_matches_the_horizon_tint(shell):
+ assert shell["fogHex"] == "dbe3ea" and shell["fogIsExp2"]
+
+
+def test_the_sky_is_a_gradient_not_a_flat_colour(shell):
+ assert abs(shell["zenithB"] - shell["horizonB"]) > 0.1, shell
+
+
+def test_the_shell_is_nearly_free_and_the_ridge_optional(shell):
+ assert shell["tris"] < 2000 and shell["ridgeOptional"]
+
+
+def test_fog_scales_with_the_world_it_wraps(shell):
+ assert shell["smallD"] == pytest.approx(0.0018) and shell["bareD"] == pytest.approx(0.0018)
+ assert shell["bigFarT"] >= 0.30 and shell["overFarT"] >= 0.30
+ assert shell["unclampedFarT"] < 0.01 and shell["explicitWins"]
+
+
+_SUN = """
+import * as THREE from 'three';
+import { sunRig } from './lib/environment.js';
+const out = {};
+const half = THREE.DataUtils.fromHalfFloat;
+const sample = (rig, dir) => {
+ const img = rig.envTex.image;
+ const u = Math.atan2(dir.z, dir.x) / (2 * Math.PI) + 0.5;
+ const v = Math.asin(Math.max(-1, Math.min(1, dir.y))) / Math.PI + 0.5;
+ const x = Math.min(img.width - 1, Math.floor(u * img.width)), y = Math.min(img.height - 1, Math.floor(v * img.height));
+ const i = (y * img.width + x) * 4;
+ return [half(img.data[i]), half(img.data[i + 1]), half(img.data[i + 2])];
+};
+const lum = (c) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
+for (const mood of ['day', 'golden', 'night', 'overcast']) {
+ const rig = sunRig({ mood, bounds: 120, disc: true });
+ const lightDir = rig.sun.position.clone().normalize();
+ const anti = lightDir.clone().multiply(new THREE.Vector3(-1, 1, -1));
+ const img = rig.envTex.image;
+ out[mood] = { envW: img.width, envH: img.height, equirect: rig.envTex.mapping === THREE.EquirectangularReflectionMapping,
+ halfFloat: rig.envTex.type === THREE.HalfFloatType, linear: rig.envTex.colorSpace === THREE.LinearSRGBColorSpace,
+ dot: lightDir.dot(rig.sunDisc.position.clone().normalize()), lightIsSun: lightDir.dot(rig.lightDir) > 0.999,
+ lumSun: lum(sample(rig, lightDir)), lumAway: lum(sample(rig, anti)),
+ zenith: sample(rig, new THREE.Vector3(0, 1, 0)), horizon: sample(rig, new THREE.Vector3(1, 0.01, 0)), nadir: sample(rig, new THREE.Vector3(0, -1, 0)),
+ fill: rig.fill.intensity, sun: rig.sun.intensity, castShadow: rig.sun.castShadow, shadowMap: rig.sun.shadow.mapSize.x,
+ bias: rig.sun.shadow.bias, normalBias: rig.sun.shadow.normalBias,
+ frustumRight: rig.sun.shadow.camera.right, night: rig.night, moodName: rig.mood };
+}
+// The shadow map follows the FRUSTUM: one fixed size gave every scene
+// whatever texel it happened to get (the library default landed at 0.146 m).
+out.texel = {};
+for (const b of [8, 25, 60, 150, 400, 1200]) {
+ const r = sunRig({ bounds: b });
+ out.texel[b] = { map: r.sun.shadow.mapSize.x, size: (2 * b) / r.sun.shadow.mapSize.x,
+ normalBias: r.sun.shadow.normalBias };
+}
+out.nightFloor = sunRig({ mood: 'night', fill: 0.2 }).fill.intensity;
+out.discOptional = sunRig({ mood: 'day', disc: false }).sunDisc === null;
+const floors = (o) => { const r = sunRig(o); return { sun: r.sun.intensity, fill: r.fill.intensity }; };
+out.floors = { dayAsked: floors({ mood: 'day', intensity: 2.8, fill: 0.65 }), goldenAsked: floors({ mood: 'golden', intensity: 2.0, fill: 0.3 }),
+ nightAsked: floors({ mood: 'night', intensity: 0.8, fill: 0.6 }), dayBright: floors({ mood: 'day', intensity: 9.0 }) };
+// A set sun is night: moon opposite, up 30-55 deg; sunDir still the authored sun.
+const set = sunRig({ azimuth: 215, elevation: -20 });
+const moon = set.sun.position.clone().normalize();
+out.set = { night: set.night, mood: set.mood, sunY: set.sunDir.y, moonY: moon.y, moonDot: moon.dot(set.moonDir),
+ opposite: Math.atan2(moon.z, moon.x) * 180 / Math.PI, discName: set.sunDisc.name, discOnMoon: set.sunDisc.position.clone().normalize().dot(moon),
+ lightDirIsMoon: set.lightDir.dot(moon) > 0.999, envZenith: sample(set, new THREE.Vector3(0, 1, 0)), envMoon: lum(sample(set, moon)),
+ envAway: lum(sample(set, moon.clone().multiply(new THREE.Vector3(-1, 1, -1)))), sunIntensity: set.sun.intensity };
+console.log(JSON.stringify(out));
+"""
+
+_MOODS = ("day", "golden", "night", "overcast")
+
+
[email protected](scope="module")
+def sun() -> dict:
+ return _measure(_SUN)
+
+
+def test_the_env_texture_is_a_linear_half_float_equirect(sun):
+ for mood in _MOODS:
+ m = sun[mood]
+ assert m["envW"] >= 64 and m["envH"] >= 32 and m["equirect"], m
+ assert m["halfFloat"] and m["linear"], m
+
+
+def test_the_sun_disc_sits_on_the_light_vector(sun):
+ for mood in _MOODS:
+ assert sun[mood]["dot"] > 0.999 and sun[mood]["lightIsSun"], (mood, sun[mood])
+
+
+def test_the_baked_env_glow_agrees_with_the_shadow_sun(sun):
+ for mood in _MOODS:
+ assert sun[mood]["lumSun"] > sun[mood]["lumAway"] * 1.15, (mood, sun[mood])
+
+
+def test_the_day_env_is_an_hdr_sky_with_a_warm_ground_half(sun):
+ """What chrome, water and glass reflect: a blue zenith, a pale (not white)
+ horizon in the dome's own family, an HDR sun, and a ground bounce below."""
+ d = sun["day"]
+ assert d["zenith"][2] > d["zenith"][0] * 2, d["zenith"]
+ hl = 0.2126 * d["horizon"][0] + 0.7152 * d["horizon"][1] + 0.0722 * d["horizon"][2]
+ assert 0.5 < hl < 2.5, d["horizon"] # toward the sun's azimuth: ~236 sRGB after ACES, not clipped
+ assert d["lumSun"] > 3.0, "the sun in the env is HDR (bloom-friendly), not a clipped band"
+ assert d["nadir"][0] > d["nadir"][2], "ground bounce is warm"
+ assert d["nadir"][0] < d["horizon"][0]
+
+
+def test_the_night_rig_is_dark_but_lit(sun):
+ """Measured on ACES/exposure 1.0: the reference moon (0.8 / fill 0.6) put the
+ ground at 17/255; 2.2 / 1.0 reads moonlit (ground ~45, shade ~14)."""
+ n = sun["night"]
+ assert n["sun"] >= 2.0 and n["fill"] >= 0.8 and n["night"], n
+ assert sun["nightFloor"] >= 0.55
+ zl = 0.2126 * n["zenith"][0] + 0.7152 * n["zenith"][1] + 0.0722 * n["zenith"][2]
+ assert zl < 0.03 and n["zenith"][2] > n["zenith"][0], n["zenith"]
+
+
+def test_the_shadow_sun_is_fitted_and_biased(sun):
+ for mood in _MOODS:
+ m = sun[mood]
+ assert m["castShadow"] and m["frustumRight"] == 120
+ # Acne is cured along the normal by ~a texel, not by pushing the whole
+ # depth back — a constant bias big enough for a coarse map is what
+ # detaches a shadow from the foot of the thing casting it.
+ assert abs(m["bias"]) <= 0.0002, m
+ assert 0 < m["normalBias"] <= 2 * 120 / m["shadowMap"] * 1.001, m
+
+
+def test_the_shadow_map_is_sized_to_the_frustum_it_covers(sun):
+ """Measured 2026-09-01 on OUR PCFSoftShadowMap (no post chain to hide it):
+ a fixed 2048 over the library's default bounds 150 gave 0.146 m/texel and
+ the contact shadow of a 1 m sphere came back a 14-texel staircase."""
+ t = sun["texel"]
+ for b, m in t.items():
+ assert 1024 <= m["map"] <= 4096, (b, m)
+ assert m["map"] == 2 ** round(math.log2(m["map"])), (b, m)
+ # Small worlds are not handed a 4096 map they cannot use...
+ assert t["8"]["map"] == 1024 and t["25"]["map"] == 1024, t
+ # ...and every world up to the 0.05 m target gets there.
+ for b in ("8", "25", "60"):
+ assert t[b]["size"] <= 0.05, (b, t[b])
+ # Past it the map caps and the texel grows with the world, never the reverse.
+ assert t["150"]["map"] == 4096 and t["1200"]["map"] == 4096, t
+ assert t["150"]["size"] < t["400"]["size"] < t["1200"]["size"], t
+ # The library default (bounds 150) is at least twice as fine as the old fixed map.
+ assert t["150"]["size"] <= (2 * 150 / 2048) / 2 + 1e-9, t["150"]
+
+
+def test_the_disc_can_be_skipped(sun):
+ assert sun["discOptional"]
+
+
+def test_daylight_has_a_sun_floor_because_colour_dies_with_the_light(sun):
+ f = sun["floors"]
+ assert f["dayAsked"]["sun"] >= 4.5 and f["dayAsked"]["fill"] >= 1.2
+ assert f["goldenAsked"]["sun"] >= 4.5
+ assert f["nightAsked"]["sun"] == 0.8, "night is legitimately dark: an explicit ask stands"
+ assert f["dayBright"]["sun"] == 9.0
+
+
+def test_a_set_sun_is_night_with_a_moon_opposite(sun):
+ s = sun["set"]
+ assert s["night"] and s["mood"] == "night" and s["sunY"] < 0
+ assert 0.5 < s["moonY"] < 0.82 and s["moonDot"] > 0.999
+ assert abs(((s["opposite"] - 35) + 180) % 360 - 180) < 1.0, s["opposite"]
+ assert s["discName"] == "MoonDisc" and s["discOnMoon"] > 0.999 and s["lightDirIsMoon"]
+ assert s["envMoon"] > s["envAway"] * 1.15
+ assert s["envZenith"][2] > s["envZenith"][0] and s["sunIntensity"] >= 2.0
+
+
+def test_outskirts_meets_the_scene_ground_at_its_seam():
+ out = _measure("""
+import { makeOutskirts } from './lib/environment.js';
+const ground = (x, z) => 2.0 + 0.01 * x;
+const g = makeOutskirts({ inner: 150, baseY: 0, heightAt: ground, relief: 30, seed: 9 });
+const land = g.children.find((o) => o.name === 'OutskirtsLand');
+const pos = land.geometry.attributes.position;
+let seamWorst = 0, maxR = 0, maxY = -1e9, farLift = 0, nFar = 0;
+for (let i = 0; i < pos.count; i++) {
+ const x = pos.getX(i), y = pos.getY(i), z = pos.getZ(i), r = Math.hypot(x, z);
+ maxR = Math.max(maxR, r); maxY = Math.max(maxY, y);
+ if (r < 151) seamWorst = Math.max(seamWorst, Math.abs(y - ground(x, z)));
+ if (r > 900) { farLift += y; nFar++; }
+}
+const copses = g.children.find((o) => o.name === 'OutskirtsCopses');
+const a = makeOutskirts({ inner: 100, seed: 4 }).children[0].geometry.attributes.position;
+const b = makeOutskirts({ inner: 100, seed: 4 }).children[0].geometry.attributes.position;
+const c = makeOutskirts({ inner: 100, seed: 5 }).children[0].geometry.attributes.position;
+let same = true, differ = false;
+for (let i = 0; i < a.count * 3; i++) { if (a.array[i] !== b.array[i]) same = false; if (a.array[i] !== c.array[i]) differ = true; }
+const reach = (o) => { const p = o.children[0].geometry.attributes.position; let r = 0;
+ for (let i = 0; i < p.count; i++) r = Math.max(r, Math.hypot(p.getX(i), p.getZ(i))); return r; };
+console.log(JSON.stringify({ seamWorst, maxR, maxY, meanFarY: farLift / nFar, meshes: g.children.length,
+ copseCount: copses ? copses.count : 0, patched: !!land.material.userData.astraShader, same, differ,
+ small: reach(makeOutskirts({ inner: 120, shellRadius: 1200, seed: 2 })), big: reach(makeOutskirts({ inner: 300, shellRadius: 9000, seed: 2 })),
+ clamped: reach(makeOutskirts({ inner: 120, shellRadius: 1200, outer: 5000, seed: 2 })),
+ shorter: reach(makeOutskirts({ inner: 120, shellRadius: 1200, outer: 600, seed: 2 })) }));
+""")
+ assert out["seamWorst"] < 0.05, out
+ assert 3279 <= out["maxR"] <= 3281 and out["maxY"] < 80 and out["meanFarY"] > 1.0, out
+ assert out["meshes"] == 2 and out["copseCount"] > 50 and out["patched"], out
+ assert out["same"] and out["differ"]
+ assert abs(out["small"] - 984) < 1.5 and abs(out["big"] - 7380) < 2.0
+ assert abs(out["clamped"] - 984) < 1.5 and abs(out["shorter"] - 600) < 1.5
diff --git a/harness/tests/scene_runtime/lib/test_figure.py b/harness/tests/scene_runtime/lib/test_figure.py
new file mode 100644
index 00000000..bd605b25
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_figure.py
@@ -0,0 +1,512 @@
+"""figure.js: a person is arithmetic, and this file is the arithmetic.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_figure_lib.py). Their scenarios are kept whole — the seat height
+determines the pose, the stride covers the ground the route moves, a knee
+bends one way, the wrist lands at the crotch — and their last test (the
+reference repo's own prompt files must name every asset library) is dropped
+because those prompts are not in this harness.
+
+Then the two bugs this port found by LOOKING at a render on our host, each
+pinned here so no later edit can put them back:
+
+1. ``MAT.skin({ color: opts.skin })`` with no ``skin`` option handed
+ ``Object.assign`` an explicit ``color: undefined``, which OVERWROTE the
+ material's own default — so every face, neck, forearm and hand in every
+ scene rendered at albedo 1.0. Measured on the showcase frame: a cold
+ (190,204,215) ball where a head should be, blown_frac 0.0035 over the
+ figure pixels. The fix picks a complexion off SKIN_TONES from the same
+ random draw that sets the material variant, so a crowd is MIXED without
+ multiplying the material cache.
+2. ``carry(fig, held)`` parented the held object to the WAIST pivot — which
+ already sits at hipHeight — while offsetting it by a figure-root height
+ (0.52 h). The tray landed 0.85 m above the hands: the render showed a
+ crate balanced on the carrier's head. The fix MEASURES the posed hands.
+
+And the grading law the improvement pass added, which is the part a later
+"tidy-up" would silently undo: every albedo on a figure stays inside the
+non-emissive window (linear 0.02..0.8, dark hair floored off a light-
+swallowing void), and the shoe presents no large horizontal facet — a flat
+up-face under an open sky is the brightest thing in the frame, and the box
+shoe measured sRGB 159 on a 0x3a albedo, i.e. a white plate on a black shoe,
+on every figure in the frame.
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("figure.js", "materials.js")
+
+
+def _measure(script: str) -> dict:
+ return measure(script, _LIBS)
+
+
+_PROBE_SEATED = """
+import * as THREE from 'three';
+import { figure, sit, walk } from './lib/figure.js';
+
+const SEAT = 0.45;
+const f = figure({ height: 1.72, rand: (() => { let s = 7;
+ return () => (s = (s * 16807) % 2147483647) / 2147483647; })() });
+sit(f, SEAT);
+f.updateMatrixWorld(true);
+
+const find = (root, name) => {
+ let hit = null;
+ root.traverse((o) => { if (o.name === name) hit = o; });
+ return hit;
+};
+const world = (name) => new THREE.Vector3()
+ .setFromMatrixPosition(find(f, name).matrixWorld);
+const box = (name) => new THREE.Box3().setFromObject(find(f, name));
+
+const waist = world('waist');
+const kneeL = world('kneeL');
+const footL = box('footL');
+const head = box('head');
+const whole = new THREE.Box3().setFromObject(f);
+
+// Standing figure, for the proportion checks.
+const g = figure({ height: 1.72 });
+g.updateMatrixWorld(true);
+const gbox = new THREE.Box3().setFromObject(g);
+const tp = find(g, 'thighL').geometry.parameters;
+
+// A walk cycle must never hyperextend a knee forward.
+let worstKnee = -1e9;
+for (let i = 0; i < 40; i++) {
+ walk(g, i / 40);
+ worstKnee = Math.max(worstKnee, g.userData.joints.kneeL.rotation.x,
+ g.userData.joints.kneeR.rotation.x);
+}
+
+console.log(JSON.stringify({
+ seat: SEAT,
+ pelvisY: waist.y,
+ kneeY: kneeL.y,
+ kneeZ: kneeL.z,
+ footMinY: footL.min.y,
+ headMinY: head.min.y,
+ seatedTop: whole.max.y,
+ standHeight: gbox.max.y - gbox.min.y,
+ standFeetY: gbox.min.y,
+ forward: f.userData.forward,
+ thighTopR: tp.radiusBottom,
+ thighEndR: tp.radiusTop,
+ worstKnee,
+}));
+"""
+
+
[email protected](scope="module")
+def seated() -> dict:
+ """One node launch of _PROBE_SEATED, shared by every test that reads it."""
+ return _measure(_PROBE_SEATED)
+
+
+_PROBE_GAIT = """
+import * as THREE from 'three';
+import { figure, walk, carry } from './lib/figure.js';
+
+const find = (root, name) => {
+ let hit = null;
+ root.traverse((o) => { if (o.name === name) hit = o; });
+ return hit;
+};
+const world = (f, name) => new THREE.Vector3()
+ .setFromMatrixPosition(find(f, name).matrixWorld);
+
+// Implied ground speed of the gait: stride length (from the measured
+// hip amplitude) times the stride rate (from hip zero crossings).
+const implied = (opts) => {
+ const f = figure({ height: 1.72 });
+ const L = f.userData.hipHeight;
+ const j = f.userData.joints;
+ const dt = 0.002;
+ let amax = 0;
+ const cross = [];
+ let prev = null;
+ for (let i = 0; i < 5000; i++) {
+ const t = i * dt;
+ walk(f, t, opts);
+ const x = j.hipL.rotation.x;
+ amax = Math.max(amax, x);
+ if (prev !== null && prev <= 0 && x > 0) cross.push(t);
+ prev = x;
+ }
+ const T = (cross[cross.length - 1] - cross[0]) / (cross.length - 1);
+ return { speed: 2 * L * Math.sin(amax) * 2 / T, strideRate: 1 / T };
+};
+const v09 = implied({ speed: 0.9 });
+const v15 = implied({ speed: 1.5 });
+const legacy = implied({});
+
+// One full stride at rate 1: joint sweeps and phase relations.
+const f = figure({ height: 1.72 });
+const j = f.userData.joints;
+let armLeg = 0, elbMin = 1e9, elbMax = -1e9;
+let heel = null, toeOff = null;
+const ys = [];
+for (let i = 0; i < 200; i++) {
+ walk(f, i / 200, { rate: 1, stride: 0.45 });
+ armLeg += j.hipL.rotation.x * j.shoulderL.rotation.x;
+ elbMin = Math.min(elbMin, j.elbowL.rotation.x);
+ elbMax = Math.max(elbMax, j.elbowL.rotation.x);
+ if (i % 50 === 0) ys.push(j.waist.position.y);
+ if (i === 50) heel = j.ankleL.rotation.x; // left leg at max forward
+ if (i === 150) toeOff = j.ankleL.rotation.x; // left leg at max trailing
+}
+
+// carry(): the hands must land ON the held thing, in FRONT of the body,
+// and the held thing must land at the HANDS and nowhere near the head.
+const c = figure({ height: 1.72 });
+const held = new THREE.Object3D();
+carry(c, held);
+c.updateMatrixWorld(true);
+held.updateMatrixWorld(true);
+const ch = world(c, 'handL');
+const heldW = new THREE.Vector3().setFromMatrixPosition(held.matrixWorld);
+const headBox = new THREE.Box3().setFromObject(find(c, 'head'));
+// carry() again on the SAME figure must not walk the object upward.
+carry(c, held);
+c.updateMatrixWorld(true);
+held.updateMatrixWorld(true);
+const heldW2 = new THREE.Vector3().setFromMatrixPosition(held.matrixWorld);
+
+// Silhouette: torso lathe profile and the fem shoulder:hip slider.
+const radii = (fig) => find(fig, 'torso').geometry.parameters.points
+ .map((p) => p.x);
+const male = figure({ height: 1.72 });
+const female = figure({ height: 1.72, fem: 1 });
+male.updateMatrixWorld(true);
+const wristY = world(male, 'handL').y / male.userData.height;
+
+console.log(JSON.stringify({
+ v09: v09.speed, v15: v15.speed, legacyStrideRate: legacy.strideRate,
+ armLeg, elbMin, elbMax, heel, toeOff, ys,
+ carryHandY: ch.y, carryHandZ: ch.z,
+ heldY: heldW.y, heldZ: heldW.z, heldY2: heldW2.y,
+ headMinY: headBox.min.y,
+ maleTorso: radii(male), femaleTorso: radii(female),
+ maleShoulderX: Math.abs(male.userData.joints.shoulderL.position.x),
+ femaleShoulderX: Math.abs(female.userData.joints.shoulderL.position.x),
+ hasAnkles: 'ankleL' in male.userData.joints
+ && 'ankleR' in male.userData.joints,
+ wristY,
+}));
+"""
+
+
[email protected](scope="module")
+def gait() -> dict:
+ """One node launch of _PROBE_GAIT, shared by every test that reads it."""
+ return _measure(_PROBE_GAIT)
+
+
+_PROBE_LOOK = """
+import * as THREE from 'three';
+import { figure } from './lib/figure.js';
+
+const find = (root, name) => {
+ let hit = null;
+ root.traverse((o) => { if (o.name === name) hit = o; });
+ return hit;
+};
+// three stores colours LINEAR, so these read as albedo directly.
+const lum = (c) => 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
+const peak = (c) => Math.max(c.r, c.g, c.b);
+
+const seeded = (n) => { let s = n; return () => (s = (s * 16807) % 2147483647)
+ / 2147483647; };
+
+// A crowd: complexions must SPREAD, not repeat one flesh colour, and the
+// material cache must not blow up doing it.
+const tones = [];
+const mats = new Set();
+for (let i = 1; i <= 24; i++) {
+ const f = figure({ height: 1.7, rand: seeded(i * 7919) });
+ const skinMat = find(f, 'head').material;
+ tones.push(skinMat.color.getHex());
+ mats.add(skinMat.uuid);
+}
+
+// Every albedo a default figure ships, plus a deliberately near-black hair.
+const plain = figure({ height: 1.72, hair: 0x0a0806 });
+const albedos = [];
+plain.traverse((o) => {
+ if (o.material && o.material.color && !o.material.emissive?.getHex()) {
+ albedos.push({ name: o.name || o.type, peak: peak(o.material.color),
+ lum: lum(o.material.color) });
+ }
+});
+const skinC = find(plain, 'head').material.color;
+// The hair is the only partial sphere on a figure.
+let hairMat = null;
+plain.traverse((o) => {
+ if (o.geometry && o.geometry.type === 'SphereGeometry'
+ && o.geometry.parameters.thetaLength < 3) hairMat = o.material;
+});
+
+// The shoe: no near-mirror roughness map, and no big flat up-face.
+const foot = find(plain, 'footL');
+const fm = foot.material;
+const g = foot.geometry.index ? foot.geometry.toNonIndexed() : foot.geometry;
+const pos = g.attributes.position;
+let flatUp = 0, total = 0;
+const a = new THREE.Vector3(), b = new THREE.Vector3(), c2 = new THREE.Vector3();
+for (let i = 0; i < pos.count; i += 3) {
+ a.fromBufferAttribute(pos, i);
+ b.fromBufferAttribute(pos, i + 1);
+ c2.fromBufferAttribute(pos, i + 2);
+ const n = new THREE.Vector3().subVectors(b, a)
+ .cross(new THREE.Vector3().subVectors(c2, a));
+ const area = n.length() / 2;
+ if (area <= 0) continue;
+ n.normalize();
+ total += area;
+ if (n.y > 0.985) flatUp += area;
+}
+
+// Face: eyes and a nose by default, gone (and cheaper) on face:false.
+const tri = (root) => { let n = 0; root.traverse((o) => {
+ if (o.geometry) n += (o.geometry.index ? o.geometry.index.count
+ : o.geometry.attributes.position.count) / 3; }); return n; };
+// the SAME figure minus the face, hair included, or the diff measures
+// the hair the comparison figure never asked for.
+const bare = figure({ height: 1.72, hair: 0x0a0806, face: false });
+
+console.log(JSON.stringify({
+ toneCount: new Set(tones).size,
+ skinMatCount: mats.size,
+ skinPeak: peak(skinC), skinLum: lum(skinC),
+ skinWarm: skinC.r - skinC.b,
+ maxPeak: Math.max(...albedos.map((x) => x.peak)),
+ minLum: Math.min(...albedos.map((x) => x.lum)),
+ hairLum: lum(hairMat.color), hairRough: hairMat.roughness,
+ shoeRough: fm.roughness, shoeHasRoughMap: !!fm.roughnessMap,
+ flatUpFrac: flatUp / total,
+ hasEyes: !!find(plain, 'eyeL') && !!find(plain, 'eyeR'),
+ bareEyes: !!find(bare, 'eyeL'),
+ triFace: tri(plain), triBare: tri(bare),
+}));
+"""
+
+
[email protected](scope="module")
+def look() -> dict:
+ """One node launch of _PROBE_LOOK, shared by every grading test."""
+ return _measure(_PROBE_LOOK)
+
+
+# --------------------------------------------------------------- the pose
+
+
+def test_seated_pelvis_lands_on_the_seat(seated):
+ """The seat height determines the pose; the author never types a y.
+
+ A standing figure translated upward — the measured failure — drives
+ the thighs through the seat surface.
+ """
+ m = seated
+ assert abs(m["pelvisY"] - m["seat"]) < 0.01, m
+
+
+def test_seated_legs_reach_the_floor_and_bend_forward(seated):
+ """Thighs level and forward, shins down, feet on the ground."""
+ m = seated
+ assert abs(m["kneeY"] - m["seat"]) < 0.10, f"thigh angle wrong: {m}"
+ assert m["kneeZ"] < -0.2, f"knees must go FORWARD (-Z), got {m['kneeZ']}"
+ assert abs(m["footMinY"]) < 0.06, f"feet off the floor: {m}"
+ assert m["headMinY"] > m["seat"], "head below the seat"
+
+
+def test_a_seated_person_is_shorter_than_a_standing_one(seated):
+ """The sanity check a human does at a glance."""
+ assert 1.15 < seated["seatedTop"] < 1.45, seated["seatedTop"]
+
+
+def test_standing_figure_is_its_requested_height_with_feet_at_zero(seated):
+ """`seat()` and `alongPath()` both assume origin-at-feet — and the
+ domed shoe this port fitted must not have moved the sole plane."""
+ m = seated
+ assert abs(m["standFeetY"]) < 0.02, m["standFeetY"]
+ assert abs(m["standHeight"] - 1.72) < 0.09, m["standHeight"]
+ assert m["forward"] == "-Z"
+
+
+def test_limbs_taper(seated):
+ """Constant-radius limbs are what make a crowd read as pipes."""
+ m = seated
+ assert m["thighEndR"] < m["thighTopR"] * 0.9, m
+
+
+def test_the_walk_cycle_never_hyperextends_a_knee(seated):
+ """A knee flexes backward only. Forward is the uncanny-crowd tell."""
+ assert seated["worstKnee"] <= 1e-6, seated["worstKnee"]
+
+
+def test_walk_speed_matches_stride_times_cadence(gait):
+ """The anti-moonwalk contract: stepLength x cadence === speed."""
+ m = gait
+ assert abs(m["v09"] - 0.9) < 0.05, m["v09"]
+ assert abs(m["v15"] - 1.5) < 0.08, m["v15"]
+
+
+def test_default_gait_is_a_walk_not_a_sprint(gait):
+ """The plain two-arg call must stay backward compatible AND pace a
+ human walk (the old default, 2.2 strides/s, was 264 steps/min)."""
+ assert 0.7 < gait["legacyStrideRate"] < 1.25, gait["legacyStrideRate"]
+
+
+def test_arms_counter_swing_the_legs(gait):
+ """Same-side arm and leg anti-phase, elbow pumping with the swing; a
+ NEGATIVE elbow angle is an anatomically impossible backward bend."""
+ m = gait
+ assert m["armLeg"] < -5, f"arm/leg not counter-phase: {m['armLeg']}"
+ assert m["elbMax"] - m["elbMin"] > 0.15, "elbows frozen"
+ assert m["elbMin"] > 0, f"elbow bends backward: {m['elbMin']}"
+
+
+def test_pelvis_bobs_twice_per_stride(gait):
+ """Dip at double support, rise at midstance, twice per stride: once
+ reads as a limp, never as ice-skating."""
+ high0, low1, high2, low3 = gait["ys"]
+ assert high0 - low1 > 0.015, f"no visible bob: {gait['ys']}"
+ assert high0 - low1 < 0.09, f"bouncing, not walking: {gait['ys']}"
+ assert abs(high0 - high2) < 0.005 and abs(low1 - low3) < 0.005, gait["ys"]
+
+
+def test_ankles_pitch_heel_strike_and_toe_off(gait):
+ """The only two moments the eye reads as ground contact."""
+ m = gait
+ assert m["hasAnkles"], "no ankle pivots in userData.joints"
+ assert m["heel"] > 0.05, f"no heel-strike dorsiflexion: {m['heel']}"
+ assert m["toeOff"] < -0.15, f"no toe-off push: {m['toeOff']}"
+
+
+def test_torso_has_a_waist_and_fem_slides_shoulder_hip_ratio(gait):
+ """The shoulder-waist-hip S-curve is the strongest silhouette cue at
+ 10-30 m; `fem` slides shoulder:hip from the male 1.4 to 1.2."""
+ m = gait
+ hip, waist, chest = m["maleTorso"][0], m["maleTorso"][1], m["maleTorso"][2]
+ assert waist < hip * 0.9 and waist < chest * 0.75, m["maleTorso"]
+ assert m["femaleShoulderX"] < m["maleShoulderX"] * 0.9, m
+ assert m["femaleTorso"][0] > m["maleTorso"][0] * 1.05, \
+ "fem does not widen the hips"
+
+
+def test_wrist_lands_near_the_crotch(gait):
+ """Canon arm length: the wrist falls at ~0.485h. The old forearm
+ (0.16h) put it at 0.44h — gorilla arms on every standing figure."""
+ assert 0.41 < gait["wristY"] < 0.50, gait["wristY"]
+
+
+# ------------------------------------------------- what carry() holds, where
+
+
+def test_carry_hands_land_on_the_held_object(gait):
+ """carry() parents the tray in FRONT of the chest; the hands must be
+ there too (the old elbow sign left them BEHIND the body plane)."""
+ m = gait
+ assert m["carryHandZ"] < -0.25, f"hands behind: {m['carryHandZ']}"
+ assert 0.80 < m["carryHandY"] < 1.10, m["carryHandY"]
+
+
+def test_the_held_object_sits_at_the_hands_not_on_the_head(gait):
+ """THE PORT'S BUG. `held` is parented to the waist pivot, which is
+ already at hipHeight, and the old code then offset it by a
+ figure-ROOT height (0.52 h) — 0.85 m above the hands. The render
+ showed a crate balanced on the carrier's head."""
+ m = gait
+ assert m["heldY"] > m["carryHandY"], "the object hangs below the hands"
+ assert m["heldY"] - m["carryHandY"] < 0.12, \
+ f"held {m['heldY']:.3f} vs hands {m['carryHandY']:.3f}: floating"
+ assert m["heldY"] < m["headMinY"], \
+ f"held at {m['heldY']:.3f} is up at the head ({m['headMinY']:.3f})"
+ assert m["heldZ"] < -0.25, f"held behind the body: {m['heldZ']}"
+
+
+def test_carry_is_idempotent_on_the_same_figure(gait):
+ """Measuring the posed hands must read the SAME pose each time: a
+ re-parent that accumulated its own offset would walk a tray up the
+ body one call per frame."""
+ m = gait
+ assert abs(m["heldY2"] - m["heldY"]) < 1e-9, (m["heldY"], m["heldY2"])
+
+
+# ------------------------------------------------------- the grading law
+
+
+def test_skin_is_never_the_undefined_white_ball(look):
+ """THE PORT'S OTHER BUG. `MAT.skin({ color: opts.skin })` with no
+ `skin` option passed an explicit `color: undefined`, and
+ `Object.assign` copied it OVER the material's default — albedo 1.0
+ on every face, neck, forearm and hand. Measured on the showcase
+ frame: a cold (190,204,215) ball where a head should be."""
+ m = look
+ assert m["skinPeak"] < 0.72, f"skin albedo {m['skinPeak']:.3f} is a lamp"
+ assert m["skinLum"] > 0.03, f"skin albedo {m['skinLum']:.3f} is a void"
+ assert m["skinWarm"] > 0.05, \
+ "skin must be WARMER than it is blue; white is what the bug gave"
+
+
+def test_a_crowd_is_mixed_without_multiplying_the_material_cache(look):
+ """The complexion is drawn from the SAME number that sets the
+ material variant, so a ladder of tones costs no more materials than
+ the single tone it replaced (one per variant bucket, 9 of them)."""
+ m = look
+ assert m["toneCount"] >= 3, f"a cloned crowd: {m['toneCount']} tone(s)"
+ assert m["skinMatCount"] <= 9, \
+ f"{m['skinMatCount']} skin materials for 24 people — cache blown"
+
+
+def test_every_albedo_stays_inside_the_non_emissive_window(look):
+ """Linear 0.02..0.8. Above it a surface is a light source the tone
+ map cannot hold; below it, a hole no environment can fill — and the
+ figure ships one deliberately near-black hair colour (0x0a0806) to
+ prove the floor is applied rather than merely documented."""
+ m = look
+ assert m["maxPeak"] <= 0.8, f"peak albedo {m['maxPeak']:.3f}"
+ assert m["minLum"] >= 0.02, f"darkest albedo {m['minLum']:.4f}"
+ assert m["hairLum"] >= 0.02, f"hair floored to a void: {m['hairLum']:.4f}"
+ assert m["hairRough"] < 0.8, \
+ "hair needs a broad specular band or it reads as a felt helmet"
+
+
+def test_the_shoe_presents_no_flat_horizontal_facet(look):
+ """A horizontal facet under an open sky is the brightest thing in
+ the frame: the box shoe measured sRGB 159 on a 0x3a albedo — a white
+ plate stuck to a black shoe, on every figure in the render. A domed
+ upper spreads the same light over a curve. The near-mirror dips of
+ the noise roughness map made the same face worse.
+
+ Measured on the same probe: the box presented 27.2% of its area
+ straight up, the dome 6.4% (a small cap at the top of the toe) —
+ the sole, correctly, still reads 12.7% straight DOWN.
+ """
+ m = look
+ assert m["flatUpFrac"] < 0.12, \
+ f"{m['flatUpFrac']:.2%} of the shoe faces straight up"
+ assert not m["shoeHasRoughMap"], "the shoe's roughness map mirrors the sky"
+ assert m["shoeRough"] >= 0.7, f"shoe roughness {m['shoeRough']}"
+
+
+def test_a_head_has_a_face_and_face_false_takes_it_back(look):
+ """A ball is what makes a close figure read as a shop dummy however
+ good the gait is; a crowd that stays past ~15 m pays nothing for it.
+
+ Measured: 90 triangles of 1 718, 5.2% of a figure. The first cut
+ was 372 (20.5%) at six-segment spheres, which is not what a face
+ the size of a thumbnail is worth.
+ """
+ m = look
+ assert m["hasEyes"], "no eyes on a default figure"
+ assert not m["bareEyes"], "face:false still built eyes"
+ assert m["triBare"] < m["triFace"], "face:false saved nothing"
+ assert m["triFace"] - m["triBare"] < 0.10 * m["triFace"], (
+ f"a face costs {m['triFace'] - m['triBare']:.0f} of "
+ f"{m['triFace']:.0f} triangles")
diff --git a/harness/tests/scene_runtime/lib/test_finish.py b/harness/tests/scene_runtime/lib/test_finish.py
new file mode 100644
index 00000000..1b71c19e
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_finish.py
@@ -0,0 +1,683 @@
+"""finish.js: light through a thin solid, and the colour a film splits.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_finish_lib.py). Their renderer-contract assertions are dropped;
+the physics claims, the shared-name contract and the option-is-a-uniform law
+are kept. Two claims the port ADDED are pinned here so a later edit cannot
+quietly undo them, both measured on our host (exposure 1.0, ACES in the
+fragment tail, no post chain):
+
+* translucency absorbs PER CHANNEL and caps its peak with one scalar knee.
+ On the original, a lamp inside a paper shade drove the transmitted term
+ past 6 and 48% of the shade's pixels came back pure white (255 on every
+ channel), which is the colour that IS the effect thrown away. After: no
+ white pixels at all and the shade's saturation up 75%.
+* the film SPLITS the light the scene actually has (ambient + the
+ hemisphere fill + a glint share of each sun and lamp) around its own
+ mean, instead of adding a fixed white veil. A veil cannot be seen on a
+ puddle already reflecting a bright sky, and it glows in the dark.
+
+The GPU compile is the only witness that counts for either: three's light
+uniforms, `getDistanceAttenuation`, the `NUM_*_LIGHTS` branches and three
+chained bodies in one main cannot be checked from source.
+"""
+from __future__ import annotations
+
+import math
+import re
+
+import pytest
+from _probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "finish.js")
+
+# One compile of a patched material, as the renderer does it: the patch
+# only writes GLSL inside onBeforeCompile, so nothing is readable until a
+# shader object has been through it.
+_COMPILE = """
+const compile = (m) => {
+ const s = { uniforms: {},
+ vertexShader: 'void main() { #include <begin_vertex> }',
+ fragmentShader: '#include <color_fragment>' };
+ m.onBeforeCompile(s);
+ return s;
+};
+const bodyOf = (s) => s.fragmentShader.slice(
+ s.fragmentShader.indexOf('#include <color_fragment>'));
+const flat = (s) => s.replace(/\\s+/g, ' ');
+const constOf = (src, name) => parseFloat(
+ (src.match(new RegExp(name + '\\\\s*=\\\\s*([0-9.]+)')) || [0, 'NaN'])[1]);
+"""
+
+
+# A lantern that is also worn and dusty, which is how a scene actually
+# uses these: both finishes plus both wear passes on ONE material. The
+# InstancedMesh is not decoration — `vertexBody` runs before
+# <project_vertex>, so the USE_INSTANCING branch is a second program —
+# and the lamp, the hemisphere fill and the sun make the point, hemi and
+# directional branches of BOTH patches compile.
+_SCENE = """
+import * as THREE from 'three';
+import { patchTranslucency, patchIridescence } from './lib/finish.js';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+import { tickShaders } from './lib/shader.js';
+
+export const BOUNDS = { min: [-8, 0, -8], max: [8, 6, 8] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ const sun = new THREE.DirectionalLight(0xfff0d8, 5.4);
+ sun.position.set(6, 7, 4);
+ sun.castShadow = true;
+ scene.add(sun);
+ scene.add(new THREE.HemisphereLight(0x9db8e8, 0x8a7f6a, 1.4));
+
+ const mat = new THREE.MeshStandardMaterial({ color: 0xd8cdb4,
+ roughness: 0.6, side: THREE.DoubleSide });
+ patchMicroBreakup(mat, { scale: 0.4, seed: 2 });
+ patchEdgeWear(mat, { strength: 0.4, width: 0.2, seed: 5 });
+ patchTranslucency(mat, { thickness: 0.01, strength: 1.1, seed: 3 });
+ patchIridescence(mat, { strength: 0.35, scale: 0.25, ior: 1.45,
+ seed: 7 });
+ const shell = new THREE.Mesh(new THREE.SphereGeometry(0.3, 32, 24), mat);
+ shell.position.y = 0.3;
+ scene.add(shell);
+
+ const lamp = new THREE.PointLight(0xffb862, 2.4, 6, 2);
+ lamp.position.set(0, 0.3, 0);
+ scene.add(lamp);
+
+ const posts = new THREE.InstancedMesh(
+ new THREE.CylinderGeometry(0.04, 0.05, 0.6, 10), mat, 4);
+ const m4 = new THREE.Matrix4();
+ for (let i = 0; i < 4; i++) {
+ m4.makeTranslation(0.5 + i * 0.2, 0.3, 0.1 * i);
+ posts.setMatrixAt(i, m4);
+ }
+ posts.instanceMatrix.needsUpdate = true;
+ scene.add(posts);
+
+ // A film on a flat, lamp-lit slab: the reflect()/glint branch again,
+ // on a surface whose normal never turns.
+ const slick = new THREE.MeshStandardMaterial({ color: 0x2a2622,
+ roughness: 0.2 });
+ patchIridescence(slick, { strength: 0.4, scale: 0.3, seed: 11 });
+ const pool = new THREE.Mesh(new THREE.CircleGeometry(1.2, 48), slick);
+ pool.rotation.x = -Math.PI / 2;
+ pool.position.set(0, 0.01, 1.6);
+ pool.receiveShadow = true;
+ scene.add(pool);
+
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [3, 1.6, 4], lookAt: [0, 0.4, 0],
+ fov: 45 }],
+ update(t) { tickShaders(scene, t); },
+ };
+}
+"""
+
+
+def test_the_four_patch_chain_compiles_on_the_real_renderer():
+ """Both finishes plus the two wear passes land on ONE material, which
+ is how a scene actually uses them — a lantern is also dusty and worn.
+ This is the only witness for the light loops: the hemisphere, sun and
+ lamp branches of the film's own irradiance estimate exist purely as
+ `#if NUM_*_LIGHTS` text until a GL context accepts them."""
+ code, out = compile_scene(
+ _SCENE, ("shader.js", "finish.js", "surface_wear.js"))
+ assert code == 0, out
+ assert "every program compiled" in out
+ # A patched built-in keeps the built-in's own depth and fog chunks.
+ assert "DISCARDED" not in out
+
+
+def test_a_thick_sample_transmits_less_than_a_thin_one():
+ """The whole difference between translucency and a pale repaint is
+ that the glow is spent by the material it crossed. The path is the
+ chord through a convex body — the widest crossing times how squarely
+ the surface is faced — and what survives is Beer-Lambert over it, so
+ doubling the thickness must not merely dim the glow, it must
+ extinguish it. (The port split the reference's one `trT = exp(...)`
+ line into the PATH and its transmittance, because the path is now
+ read twice: once for the level and once for the colour.)"""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchTranslucency } from './lib/finish.js';
+const one = (thickness) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchTranslucency(m, { thickness });
+ const s = compile(m);
+ return { thick: s.uniforms.uTrsThick.value, fs: s.fragmentShader };
+};
+const a = one(0.0005), b = one(0.02), c = one(0.30);
+const f = flat(a.fs);
+console.log(JSON.stringify({
+ thin: a.thick, mid: b.thick, thick: c.thick,
+ path: (f.match(/float trPath = [^;]*;/) || [''])[0],
+ expr: (f.match(/float trT = [^;]*;/) || [''])[0],
+ mfp: constOf(a.fs, 'ASTRA_TRS_MFP'),
+}));
+""", _LIBS)
+ # The path, not just the thickness: without the facing term every
+ # pixel of a solid would transmit the same and the object would be a
+ # lamp rather than a body with a thin edge and a thick middle.
+ assert re.fullmatch(
+ r"float trPath = uTrsThick \* astraFacing\(trN, trV\) \* trG;",
+ out["path"]), out["path"]
+ assert re.fullmatch(r"float trT = exp\(-trPath / ASTRA_TRS_MFP\);",
+ out["expr"]), out["expr"]
+ mfp = out["mfp"]
+ assert 0.005 < mfp < 0.2, mfp
+
+ def survives(thickness, facing):
+ return math.exp(-thickness * facing / mfp)
+
+ # Squarely faced, where the chord is longest.
+ thin, mid, thick = (survives(out[k], 0.9)
+ for k in ("thin", "mid", "thick"))
+ assert thin > 0.95, thin
+ assert mid < thin / 1.5, (mid, thin)
+ assert thick < 1e-3, thick
+ # And ONE body glows where it is THIN: the chord runs out toward the
+ # silhouette, so the block that is opaque through its core still
+ # comes back at its edge. That gradient is the cue itself.
+ assert survives(out["thick"], 0.05) > 100 * survives(out["thick"], 0.9)
+
+
+def test_the_light_has_to_be_behind_the_surface_to_come_through():
+ """Backlit is the other half of the cue, and it is a GATE, not a
+ weighting: a candle with the sun on its face must gain nothing at
+ all, or the patch is an ambient glow with a directional flavour."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchTranslucency } from './lib/finish.js';
+const m = new THREE.MeshStandardMaterial();
+patchTranslucency(m, {});
+const s = compile(m);
+const fn = (flat(s.fragmentShader).match(
+ /float astraTrsWeight\\([^)]*\\) \\{[^}]*\\}/) || [''])[0];
+console.log(JSON.stringify({
+ fn,
+ gate: /float b = max\\(-dot\\(n, l\\), 0\\.0\\);/.test(fn),
+ ret: (fn.match(/return ([^;]*);/) || ['', ''])[1],
+ lobe: /vec3 h = normalize\\(-l \\+ n \\* ASTRA_TRS_BEND\\);/.test(fn),
+ facesViewer: /trN \\*= sign\\(dot\\(trN, trV\\)/.test(s.fragmentShader),
+ bothLights: /directionalLights\\[i\\]\\.direction/.test(s.fragmentShader)
+ && /pointLights\\[i\\]\\.position/.test(s.fragmentShader),
+}));
+""", _LIBS)
+ assert out["gate"], out["fn"]
+ # Everything the function returns sits inside the gate's one factor,
+ # so a light on the viewer's side contributes exactly zero and not a
+ # floor. Checked by balancing the parens, not by a regex that would
+ # pass an unbracketed second term.
+ ret = out["ret"]
+ assert ret.startswith("b * ("), ret
+ depth = 0
+ for i, ch in enumerate(ret[4:], start=4):
+ depth += (ch == "(") - (ch == ")")
+ if depth == 0:
+ assert i == len(ret) - 1, ret
+ break
+ assert out["lobe"], out["fn"]
+ assert out["facesViewer"]
+ # A lamp inside a shade is a point light; a sun behind a leaf is a
+ # directional. Summing only one of them halves what this can shade.
+ assert out["bothLights"]
+
+
+def test_transmitted_light_is_added_not_painted_onto_the_albedo():
+ """A lantern at dusk is brighter than anything falling on its front,
+ so an albedo lift would cap it at the ambient and read as pale paper.
+ The film is a reflection sitting on top of the surface for the same
+ reason. Neither may touch `diffuseColor`, which belongs to whichever
+ wear or aging patch shares the material."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchTranslucency, patchIridescence } from './lib/finish.js';
+const bodyFor = (fn) => {
+ const m = new THREE.MeshStandardMaterial();
+ fn(m, {});
+ return bodyOf(compile(m));
+};
+const t = bodyFor(patchTranslucency), i = bodyFor(patchIridescence);
+console.log(JSON.stringify({
+ transAdds: /totalEmissiveRadiance\\s*\\+=/.test(t),
+ iriAdds: /totalEmissiveRadiance\\s*\\+=/.test(i),
+ transKeepsAlbedo: !/diffuseColor[.\\w]*\\s*[*+-]?=/.test(t),
+ iriKeepsAlbedo: !/diffuseColor[.\\w]*\\s*[*+-]?=/.test(i),
+}));
+""", _LIBS)
+ assert out["transAdds"] and out["iriAdds"]
+ assert out["transKeepsAlbedo"], "translucency must not repaint albedo"
+ assert out["iriKeepsAlbedo"], "a film reflects, it does not repaint"
+
+
+def test_the_transmitted_colour_deepens_along_the_path():
+ """PORT ADDITION. Absorption is per channel, so the colour light
+ comes out as is the colour of the path it crossed: a thin crossing is
+ a pale wash of `color` and a long one is `color` itself. One flat
+ tint over the whole body — what the reference had — is why a wax
+ candle came back as a white stick with a warm edge. Measured on the
+ close render: the candle's local hue spread went 3.5 -> 5.9 degrees
+ and the jade egg's saturation 0.167 -> 0.271 with its luminance DOWN,
+ which is the gradient appearing rather than a brightness lift."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchTranslucency } from './lib/finish.js';
+const m = new THREE.MeshStandardMaterial();
+patchTranslucency(m, {});
+const s = compile(m);
+const f = flat(s.fragmentShader);
+console.log(JSON.stringify({
+ tint: (f.match(/vec3 trTint = [^;]*;/) || [''])[0],
+ out: (f.match(/vec3 trOut = [^;]*;/) || [''])[0],
+ t0: constOf(s.fragmentShader, 'ASTRA_TRS_TINT0'),
+ tk: constOf(s.fragmentShader, 'ASTRA_TRS_TINTK'),
+ color: s.uniforms.uTrsColor.value.toArray(),
+}));
+""", _LIBS)
+ # The exponent rides the PATH — the same path the level uses, so the
+ # two cannot drift — and nothing else.
+ assert "pow(uTrsColor" in out["tint"], out["tint"]
+ assert "trPath / ASTRA_TRS_MFP" in out["tint"], out["tint"]
+ assert "trTint *" in out["out"] or "trTint * (" in out["out"], out["out"]
+ t0, tk = out["t0"], out["tk"]
+ # Even the thinnest crossing is already tinted (lantern paper is warm
+ # at half a millimetre), and a long one is deeper than the option.
+ assert 0.2 < t0 < 1.0, t0
+ assert tk > 0.5, tk
+ # A real gradient, not a rounding: on the default parchment the thin
+ # crossing must come back PALER than the medium itself and one mean
+ # free path deeper must lose a visible share of that.
+ g = out["color"][1]
+ near, far = g ** t0, g ** (t0 + tk)
+ assert near > g * 1.10, (near, g)
+ assert far < 0.75 * near, (near, far)
+
+
+def test_the_transmitted_peak_is_capped_in_colour_not_clipped_to_white():
+ """PORT ADDITION. A lamp pressed against a paper shade drives the
+ transmitted term past 6 on our host, which tone-maps in the fragment
+ tail with no post chain: 48% of the shade's pixels came back 255 on
+ every channel and the warmth that IS the effect was the first thing
+ lost. The knee is ONE scalar on the peak channel — scaling all three
+ by the same number moves the level and leaves the hue exactly where
+ it was, which a per-channel clamp does not — and it opens at half the
+ ceiling, so every ordinary glow passes through untouched. Measured
+ after: white pixels 0.4834 -> 0.0000 of the shade, saturation 0.0825
+ -> 0.1443, and the frame's own blown_frac still 0."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchTranslucency } from './lib/finish.js';
+const m = new THREE.MeshStandardMaterial();
+patchTranslucency(m, {});
+const s = compile(m);
+const f = flat(s.fragmentShader);
+console.log(JSON.stringify({
+ peakLine: (f.match(/float trPk = [^;]*;/) || [''])[0],
+ knee: (f.match(/trOut \\*= [^;]*;/) || [''])[0],
+ emit: (f.match(/totalEmissiveRadiance \\+= trOut;/) || [''])[0],
+ peak: constOf(s.fragmentShader, 'ASTRA_TRS_PEAK'),
+}));
+""", _LIBS)
+ assert "max(max(trOut.r, trOut.g), trOut.b)" in out["peakLine"], out
+ assert out["knee"].startswith("trOut *= "), out["knee"]
+ assert out["emit"], "the compressed value is what gets added"
+ peak = out["peak"]
+ # Bloom-friendly: an emissive that peaks at 20 is a white hole on any
+ # host, with or without a bloom pass.
+ assert 1.5 <= peak <= 4.0, peak
+
+ def knee(x):
+ return x * peak / (peak + max(x - 0.5 * peak, 0.0))
+
+ # Ordinary glows are untouched, a lamp against the shade is bounded,
+ # and the map never turns over (brighter in must stay brighter out).
+ assert knee(0.4) == pytest.approx(0.4)
+ assert knee(peak * 0.5) == pytest.approx(peak * 0.5)
+ assert knee(6.5) < peak
+ assert knee(1e4) < peak * 1.001
+ assert knee(9.0) > knee(6.5) > knee(3.0)
+
+
+def test_the_film_hue_rides_the_view_angle_not_the_surface():
+ """A hue that only varies over the surface is a rainbow decal. The
+ ray bends INSIDE the film (Snell off `ior`), so the optical path it
+ crosses shortens toward grazing and the fringe order slides as the
+ camera moves — that shortening is the sweep. The film's own
+ thickness field varies too, and it must stay the SMALLER of the two
+ or the decal wins."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchIridescence } from './lib/finish.js';
+const m = new THREE.MeshStandardMaterial();
+patchIridescence(m, {});
+const s = compile(m);
+const fs = flat(s.fragmentShader);
+const line = (name) => (fs.match(
+ new RegExp('float ' + name + ' = [^;]*;')) || [''])[0];
+console.log(JSON.stringify({
+ ior: s.uniforms.uIriIor.value,
+ d0: constOf(fs, 'ASTRA_IRI_D0'),
+ dv: constOf(fs, 'ASTRA_IRI_DV'),
+ cosLine: line('irCos'),
+ ctLine: line('irCt'),
+ opdLine: line('irOpd'),
+ thicknessLine: line('irD'),
+ filmTakesOpd: /astraIriFilm\\(irOpd\\)/.test(fs),
+}));
+""", _LIBS)
+ assert "dot(irN, irV)" in out["cosLine"], out["cosLine"]
+ assert "irCos * irCos" in out["ctLine"] and "uIriIor" in out["ctLine"]
+ # Both the bend and the path it crosses ride the option, so a baked
+ # index would freeze the sweep for every other caller.
+ assert "irCt" in out["opdLine"] and "uIriIor" in out["opdLine"]
+ assert out["filmTakesOpd"]
+ # The thickness field is position only: if the angle leaked into it
+ # the two would be indistinguishable and this test would prove
+ # nothing.
+ assert "vAstraWorld" in out["thicknessLine"]
+ assert "irCos" not in out["thicknessLine"]
+ assert "irCt" not in out["thicknessLine"]
+ # Now the sizes. Walking round the object shortens the path by
+ # 1 - cos(theta_t) at grazing; walking ACROSS it swings the film by
+ # +/- dv. The angular swing must be the bigger of the two — the port
+ # raised dv 45 -> 60 nm so a FLAT film bands at all, and this is the
+ # law that bounds how far that could go.
+ ior = out["ior"]
+ angular = 1 - math.sqrt(1 - 1 / (ior * ior))
+ positional = 2 * out["dv"] / out["d0"]
+ assert angular > positional, (angular, positional)
+
+
+def test_the_film_is_strongest_at_grazing_and_its_ior_says_how_much():
+ """A film's colour is a reflection, so it is faint face-on and takes
+ the surface over at the rim — that ramp is as much of the cue as the
+ hue itself. Both ends come from `ior`: four times the single-surface
+ Fresnel face-on (where two-beam interference peaks) rising to total
+ reflection at grazing."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchIridescence } from './lib/finish.js';
+const one = (ior) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchIridescence(m, { ior });
+ const s = compile(m);
+ return { ior: s.uniforms.uIriIor.value, fs: flat(s.fragmentShader) };
+};
+const a = one(1.33), b = one(1.8);
+console.log(JSON.stringify({
+ soap: a.ior, chitin: b.ior,
+ weight: (a.fs.match(/float irW = [^;]*;/) || [''])[0],
+ r0: (a.fs.match(/irR0 = [^;]*;/g) || []).join(' '),
+ sameSource: a.fs === b.fs,
+}));
+""", _LIBS)
+ assert "astraFresnel(irN, irV, 4.0)" in out["weight"], out["weight"]
+ assert "mix(irR0, 1.0" in out["weight"], out["weight"]
+ assert "4.0 * irR0 * irR0" in out["r0"], out["r0"]
+
+ def face_on(n):
+ return 4 * ((n - 1) / (n + 1)) ** 2
+
+ # Faint face-on, and a denser film returns more of it.
+ assert face_on(out["soap"]) < 0.15
+ assert face_on(out["chitin"]) > 2 * face_on(out["soap"])
+ # ...all of it by UNIFORM, so two films share one compiled program.
+ assert out["sameSource"]
+
+
+def test_the_film_splits_the_light_the_scene_actually_has():
+ """PORT ADDITION, and the biggest one. The reference added the film
+ as a fixed white veil, independent of every light: it glowed in the
+ dark, it carried no scene colour, and on a puddle already reflecting
+ a bright sky it only washed the pool out (measured: hue spread 98 deg
+ at saturation 0.054 — noise, not colour).
+
+ What it adds now is the light the scene HAS: ambient, plus the
+ hemisphere fill as a wash (a film reflects the whole sky), plus a
+ glint share of every sun and lamp — punctual, so what a mirror
+ returns of them is a lobe around the reflect() direction, not a wash.
+ That last distinction is not cosmetic: as a wash, one lamp two metres
+ off a night puddle lit the WHOLE pool rainbow (night render, first
+ pass). Split into a unit-luminance tint and a saturating level, so
+ `strength` keeps meaning what the docs say and a near lamp cannot
+ turn a slick into a second lamp."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchIridescence } from './lib/finish.js';
+const m = new THREE.MeshStandardMaterial();
+patchIridescence(m, {});
+const s = compile(m);
+const fs = flat(s.fragmentShader);
+console.log(JSON.stringify({
+ seed: (fs.match(/vec3 irLit = [^;]*;/) || [''])[0],
+ hemi: /hemisphereLights\\[i\\]\\.skyColor/.test(fs)
+ && /hemisphereLights\\[i\\]\\.groundColor/.test(fs),
+ hemiGuard: /#if NUM_HEMI_LIGHTS > 0/.test(s.fragmentShader),
+ dirGuard: /#if NUM_DIR_LIGHTS > 0/.test(s.fragmentShader),
+ pointGuard: /#if NUM_POINT_LIGHTS > 0/.test(s.fragmentShader),
+ mirror: (fs.match(/vec3 irRef = [^;]*;/) || [''])[0],
+ dirTerm: (fs.match(
+ /irLit \\+= directionalLights\\[i\\]\\.color [^;]*;/) || [''])[0],
+ pointTerm: (fs.match(
+ /irLit \\+= pointLights\\[i\\]\\.color [^;]*;/) || [''])[0],
+ lumLine: (fs.match(/float irLum = [^;]*;/) || [''])[0],
+ tintLine: (fs.match(/vec3 irTint = [^;]*;/) || [''])[0],
+ levelLine: (fs.match(/float irLevel = [^;]*;/) || [''])[0],
+ emit: (fs.match(/totalEmissiveRadiance \\+= irTint[^;]*;/) || [''])[0],
+ veil: constOf(s.fragmentShader, 'ASTRA_IRI_VEIL'),
+ ref: constOf(s.fragmentShader, 'ASTRA_IRI_REF'),
+ haze: constOf(s.fragmentShader, 'ASTRA_IRI_HAZE'),
+ lobe: constOf(s.fragmentShader, 'ASTRA_IRI_LOBE'),
+}));
+""", _LIBS)
+ # It starts from the scene's ambient and adds the sky the same way
+ # three's own hemisphere term does — no hardcoded light colour.
+ assert out["seed"] == "vec3 irLit = ambientLightColor;", out["seed"]
+ assert out["hemi"], "the hemisphere fill IS the sky for a sunRig scene"
+ assert out["hemiGuard"] and out["dirGuard"] and out["pointGuard"], out
+ # A punctual light arrives as a GLINT: weighted around the mirror
+ # direction, with only a haze share everywhere else.
+ assert "reflect(-irV, irN)" in out["mirror"], out["mirror"]
+ for term in ("dirTerm", "pointTerm"):
+ assert "ASTRA_IRI_HAZE" in out[term], out[term]
+ assert "dot(irRef," in out[term], out[term]
+ assert "ASTRA_IRI_LOBE" in out[term], out[term]
+ assert 0.0 < out["haze"] <= 0.25, out["haze"]
+ assert out["lobe"] >= 4.0, out["lobe"]
+ # Colour and level are separated, and the level SATURATES.
+ assert "0.2126" in out["lumLine"], out["lumLine"]
+ assert out["tintLine"].startswith("vec3 irTint = irLit /"), out
+ assert "irLum + ASTRA_IRI_REF" in out["levelLine"], out["levelLine"]
+ ref = out["ref"]
+ level = lambda lum: lum / (lum + ref) # noqa: E731
+ assert level(0.0) == 0.0, "a film in the dark must not glow"
+ assert level(4.0) < 1.0 and level(4.0) > 2 * level(0.3)
+ assert level(40.0) - level(8.0) < 0.15, "a near lamp must not run away"
+ # And what is added is the scene's tint times a swing about the mean,
+ # not a white veil: VEIL is only the share left as a plain lift.
+ assert out["emit"].startswith("totalEmissiveRadiance += irTint"), out
+ assert "astraIriFilm(irOpd) - (1.0 - ASTRA_IRI_VEIL)" in out["emit"]
+ assert 0.0 < out["veil"] < 0.6, out["veil"]
+
+
+def test_the_film_holds_its_mean_so_the_swing_is_hue_not_brightness():
+ """A fringe that swings brightness as well as hue reads as a stain,
+ and after the mean is subtracted it would also mean the film could
+ only ever darken or only ever brighten. `astraIriFilm` is normalised
+ to a mean of one before the order wash mixes it toward white, so the
+ swing is symmetric about zero — replicated here in Python from the
+ constants the GLSL actually carries."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchIridescence } from './lib/finish.js';
+const m = new THREE.MeshStandardMaterial();
+patchIridescence(m, { ior: 1.4 });
+const s = compile(m);
+const fs = flat(s.fragmentShader);
+console.log(JSON.stringify({
+ norm: (fs.match(/c \\/= [^;]*;/) || [''])[0],
+ wash: (fs.match(/return mix\\(vec3\\(1\\.0\\), c, [^;]*;/) || [''])[0],
+ lam: (fs.match(/vec3 lam = [^;]*;/) || [''])[0],
+ veil: constOf(s.fragmentShader, 'ASTRA_IRI_VEIL'),
+ floor: parseFloat((fs.match(
+ /c \\/= max\\(\\(c\\.r \\+ c\\.g \\+ c\\.b\\) \\/ 3\\.0, ([0-9.]+)\\)/)
+ || [0, 'NaN'])[1]),
+}));
+""", _LIBS)
+ assert "0.5 + 0.5 * cos" not in out["norm"]
+ assert "(c.r + c.g + c.b) / 3.0" in out["norm"], out["norm"]
+ assert "exp(-0.12 * ord * ord)" in out["wash"], out["wash"]
+ lam = [float(v) for v in re.findall(r"[0-9]+\.[0-9]+", out["lam"])]
+ assert len(lam) == 3 and min(lam) > 400 and max(lam) < 700, lam
+
+ floor, veil = out["floor"], out["veil"]
+
+ def film(opd):
+ c = [0.5 + 0.5 * math.cos(2 * math.pi * opd / w + math.pi)
+ for w in lam]
+ m = max(sum(c) / 3, floor)
+ c = [v / m for v in c]
+ ordr = opd / 550.0
+ w = math.exp(-0.12 * ordr * ordr)
+ return [1 - w + w * v for v in c]
+
+ # Over one sweep of the first two orders the mean channel stays at
+ # one, so `- (1 - VEIL)` leaves a swing that is as much below zero as
+ # above it plus exactly VEIL of a lift.
+ samples = [film(400 + 8 * i) for i in range(150)]
+ mean = sum(sum(s) / 3 for s in samples) / len(samples)
+ assert 0.9 < mean < 1.12, mean
+ lift = mean - (1 - veil)
+ assert abs(lift - veil) < 0.12, (lift, veil)
+ # And the swing is real: some sample is a long way off its own mean.
+ swing = max(max(s) - min(s) for s in samples)
+ assert swing > 0.5, swing
+ # ...but bounded, or a beetle's back reads as a hologram. The floor
+ # on the normaliser is what caps it (the port raised it 0.18 -> 0.26;
+ # measured on the close render, the shell's saturation went 0.234 ->
+ # 0.452 while its luminance FELL 0.585 -> 0.457, which is colour
+ # arriving rather than a white lift).
+ assert max(max(s) for s in samples) < 1 / floor + 0.01
+ assert floor >= 0.2, floor
+
+
+def test_every_option_is_a_uniform_not_baked_source():
+ """The first material to compile a cache key decides the GLSL every
+ material with that key gets, so an option baked into the source would
+ be silently forced on every other caller. Two very differently tuned
+ materials must therefore differ in their uniforms and not by one
+ character of shader."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchTranslucency, patchIridescence } from './lib/finish.js';
+const one = (t, i) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchTranslucency(m, t);
+ patchIridescence(m, i);
+ const s = compile(m);
+ const u = {};
+ for (const k of Object.keys(s.uniforms)) {
+ const v = s.uniforms[k].value;
+ u[k] = (v && v.toArray) ? v.toArray()
+ : ((v && v.getHex) ? v.getHex() : v);
+ }
+ return { u, fs: s.fragmentShader, vs: s.vertexShader,
+ key: m.customProgramCacheKey() };
+};
+const a = one({ thickness: 0.001, strength: 0.5, power: 1.5,
+ color: 0x223344, seed: 2 },
+ { strength: 0.2, scale: 0.1, ior: 1.2, seed: 3 });
+const b = one({ thickness: 0.4, strength: 3.0, power: 8,
+ color: 0xffeecc, seed: 41 },
+ { strength: 0.9, scale: 4.0, ior: 1.9, seed: 77 });
+const differs = Object.keys(a.u).filter(
+ (k) => JSON.stringify(a.u[k]) !== JSON.stringify(b.u[k]));
+console.log(JSON.stringify({
+ sameSource: a.fs === b.fs && a.vs === b.vs,
+ sameKey: a.key === b.key,
+ differs: differs.sort(),
+}));
+""", _LIBS)
+ assert out["sameSource"], "an option was baked into the GLSL"
+ assert out["sameKey"]
+ assert out["differs"] == [
+ "uIriAmt", "uIriIor", "uIriScale", "uIriSeed",
+ "uTrsAmt", "uTrsColor", "uTrsPow", "uTrsSeed", "uTrsThick",
+ ], out["differs"]
+
+
+def test_the_patch_names_are_disjoint_from_the_libraries_it_chains_with():
+ """Patches chain, and the cache key is every name in the chain. Two
+ libraries that reused a name would collide into one program while the
+ second one's GLSL was never compiled — a defect with no error and no
+ visible cause."""
+ out = measure("""
+import * as THREE from 'three';
+const names = async (file) => {
+ const mod = await import(file);
+ const out = [];
+ for (const key of Object.keys(mod)) {
+ if (!/^patch/.test(key) || typeof mod[key] !== 'function') continue;
+ const m = new THREE.MeshStandardMaterial();
+ try { mod[key](m, {}); } catch (e) { continue; }
+ for (const p of (m.userData.astraPatches || [])) out.push(p.name);
+ }
+ return out;
+};
+const mine = await names('./lib/finish.js');
+const theirs = {};
+for (const f of ['foliage_shade.js', 'surface_wear.js', 'aging.js',
+ 'terrain_shade.js', 'waterside.js', 'dapple.js']) {
+ theirs[f] = await names('./lib/' + f);
+}
+console.log(JSON.stringify({ mine, theirs }));
+""", _LIBS + ("foliage_shade.js", "surface_wear.js", "aging.js",
+ "terrain_shade.js", "waterside.js", "dapple.js"))
+ mine = set(out["mine"])
+ assert mine == {"finish:base", "finish:translucency",
+ "finish:iridescence"}, sorted(mine)
+ for lib, names in out["theirs"].items():
+ assert names, f"{lib} registered no patches — probe is blind"
+ assert not (mine & set(names)), (lib, sorted(mine & set(names)))
+
+
+def test_one_seed_lays_the_same_grain_and_the_same_film_twice():
+ """A scene is rendered many times and re-rendered after a fix; a
+ surface that reshuffled between rounds would make every judge
+ comparison meaningless. The seed is the only randomness here, it is
+ a uniform, and it must move the field far rather than by one cell."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchTranslucency, patchIridescence } from './lib/finish.js';
+const one = (seed) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchTranslucency(m, { seed });
+ patchIridescence(m, { seed });
+ const s = compile(m);
+ return { trs: s.uniforms.uTrsSeed.value.toArray(),
+ iri: s.uniforms.uIriSeed.value.toArray(),
+ src: s.fragmentShader };
+};
+const a = one(3), b = one(3), c = one(4);
+const dist = (p, q) => Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
+console.log(JSON.stringify({
+ repeatable: JSON.stringify(a.trs) === JSON.stringify(b.trs)
+ && JSON.stringify(a.iri) === JSON.stringify(b.iri),
+ trsMoved: dist(a.trs, c.trs),
+ iriMoved: dist(a.iri, c.iri),
+ apart: dist(a.trs, a.iri),
+ sameSource: a.src === c.src,
+}));
+""", _LIBS)
+ assert out["repeatable"], "same seed, different field"
+ assert out["trsMoved"] > 5, out["trsMoved"]
+ assert out["iriMoved"] > 5, out["iriMoved"]
+ assert out["apart"] > 5, out["apart"]
+ assert out["sameSource"], "the seed reached the GLSL"
diff --git a/harness/tests/scene_runtime/lib/test_flock.py b/harness/tests/scene_runtime/lib/test_flock.py
new file mode 100644
index 00000000..44e45ff2
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_flock.py
@@ -0,0 +1,342 @@
+"""flock.js: a skein of birds (or a school of fish) animated entirely in
+the vertex shader.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_flock_lib.py). Their cost contract is kept verbatim in spirit —
+one draw call at any count, a tick that moves exactly one float, a skein
+strung down the route, a bounding box that states the volume the shader
+flies through — because that contract is the whole reason the module
+exists. Their renderer-contract assertions are dropped, and the compile
+check is staged as a SCENE (`_probe.compile_scene`).
+
+THE PORT'S OWN LAWS, each one a frame rendered on our host and looked at
+(fx/out/flock/{before,after,night,fish}):
+
+1. THE BIRD IS LIT, NOT PAINTED. The old fragment mixed the silhouette
+ toward `vec3(1.0)` on the downstroke, so half the flock arrived as flat
+ WHITE marks in the same instant, all the same value: measured over the
+ bird pixels of the showcase frame, 836 distinct colours in 1757 core
+ pixels, with the top four accounting for 13% of them in the close view.
+ Colour now comes out of an irradiance — `skyColor` on the shaded side,
+ `sunColor` where the wing faces the sun — and the same measurement
+ gives 998 distinct in 1243, top four 3.3%. Hue spread across the flock
+ went 0.086 -> 0.164 (mid) and 0.018 -> 0.140 (close).
+
+2. A SHADED BIRD IS NOT A HOLE. `0x23262c` is a 1.5% albedo and the sky
+ ambient was a fraction of the sky rather than its integral, which put
+ bird cores at 7/255 — pure black against a 0.70 sky. The default
+ albedo is a rook's (~3.6%) and the ambient is an irradiance; core
+ minimum measured 0.127 (mid) / 0.091 (close) with no pixel crushed.
+
+3. THE TWO WINGS ROLL OPPOSITE WAYS. A flash keyed on the beat alone
+ lights every bird identically; mirrored roll is what makes a real skein
+ shimmer through a turn, and it is why the sun has to reach the fragment
+ in the bird's own frame (`vLit`), not as a single scalar.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "noise.js", "materials.js", "flock.js")
+
+
+def test_both_kinds_compile_on_the_headless_gpu():
+ """One material carries the path, the formation, the wingbeat, the
+ silhouette AND the lighting — only the GPU can say whether that GLSL is
+ legal, and the fish branch is a second program nothing else builds."""
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import { makeFlock } from './lib/flock.js';
+
+export const BOUNDS = { min: [-40, 0, -40], max: [40, 40, 40] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ scene.add(makeFlock({ count: 110, extent: 22, height: 14, speed: 7,
+ seed: 4 }));
+ scene.add(makeFlock({ count: 60, kind: 'fish', extent: 8, height: 3,
+ seed: 5, sunColor: 0xffe0b0, skyColor: 0x2f5a6e }));
+ const cameras = [
+ { name: 'sky', position: [0, 3, 26], lookAt: [0, 12, 0], fov: 50 },
+ ];
+ return { scene, cameras, update() {} };
+}
+""", _LIBS)
+ assert code == 0, out
+ assert "WARN" not in out, out
+
+
+def test_the_quad_keeps_position_at_the_origin():
+ """A depth or AO pass redraws with an override material that ignores
+ custom vertex shaders, so a billboard that keeps its quad in `position`
+ burns a rectangle at the world origin."""
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const mesh = makeFlock({ count: 64 }).children[0];
+const g = mesh.geometry;
+console.log(JSON.stringify({
+ posAllZero: Array.from(g.attributes.position.array).every((v) => v === 0),
+ hasCorner: !!g.attributes.aCorner,
+ cornerSpan: Math.max(...Array.from(g.attributes.aCorner.array)),
+ instances: g.instanceCount,
+ offs: g.attributes.iOff.count,
+ extras: g.attributes.iExtra.count,
+}));
+""", _LIBS)
+ assert out["posAllZero"] and out["hasCorner"]
+ assert out["cornerSpan"] > 0, out
+ assert out["instances"] == 64
+ assert out["offs"] == 64 and out["extras"] == 64
+
+
+def test_ten_thousand_birds_are_one_draw_call():
+ """The whole bet: instances are free, meshes are not. Ten thousand
+ birds must cost the same submission — and the same four vertices — as a
+ hundred, or the flock gets cut down until it reads as specks."""
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const shape = (n) => {
+ const g = makeFlock({ count: n });
+ const drawn = [];
+ g.traverse((o) => { if (o.isMesh || o.isLine || o.isPoints) drawn.push(o); });
+ const m = drawn[0];
+ return {
+ meshes: drawn.length,
+ instanced: !!m.geometry.isInstancedBufferGeometry,
+ verts: m.geometry.attributes.position.count,
+ groups: m.geometry.groups.length,
+ materials: [].concat(m.material).length,
+ instances: m.geometry.instanceCount,
+ };
+};
+console.log(JSON.stringify({ small: shape(100), big: shape(10000) }));
+""", _LIBS)
+ for k in ("small", "big"):
+ assert out[k]["meshes"] == 1, out
+ assert out[k]["instanced"] and out[k]["materials"] == 1, out
+ # Geometry groups are per-material sub-draws: one draw call means
+ # none of them.
+ assert out[k]["groups"] == 0, out
+ assert out["small"]["verts"] == out["big"]["verts"], out
+ assert out["small"]["instances"] == 100
+ assert out["big"]["instances"] == 10000
+
+
+def test_tick_rebuilds_no_per_instance_matrix():
+ """The motion is in the shader: a tick may move exactly one float.
+ Anything else — a rewritten offset buffer, a touched matrix, an
+ InstancedMesh matrix upload — is the per-frame CPU cost this library
+ exists to avoid, and it would not show up in a render."""
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const g = makeFlock({ count: 300, seed: 6 });
+const mesh = g.children[0];
+const snap = () => {
+ const parts = [];
+ g.traverse((o) => {
+ parts.push(o.matrix.elements.join(','), o.matrixWorld.elements.join(','));
+ const geo = o.geometry;
+ if (!geo) return;
+ for (const k of Object.keys(geo.attributes)) {
+ parts.push(k + ':' + Array.from(geo.attributes[k].array).join(','));
+ }
+ });
+ return parts.join('|');
+};
+const before = snap();
+g.userData.tick(4.25);
+console.log(JSON.stringify({
+ unchanged: before === snap(),
+ isInstancedMesh: !!mesh.isInstancedMesh,
+ hasInstanceMatrix: !!mesh.instanceMatrix,
+ uploads: Object.values(mesh.geometry.attributes)
+ .map((a) => a.version).reduce((s, v) => s + v, 0),
+ uTime: mesh.material.uniforms.uTime.value,
+}));
+""", _LIBS)
+ assert out["unchanged"], out
+ # An InstancedMesh would carry a matrix per bird to re-upload.
+ assert not out["isInstancedMesh"] and not out["hasInstanceMatrix"]
+ assert out["uploads"] == 0, out
+ assert out["uTime"] == 4.25
+
+
+def test_two_flocks_with_one_seed_are_identical():
+ """Determinism is the contract for every shipped factory: a re-run that
+ reshuffles the formation is a re-run nobody can compare. The plumage
+ variance rides `iExtra.x` through a shader hash, so this covers the
+ colours as well as the formation."""
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const attrs = (s) => {
+ const g = makeFlock({ seed: s, count: 50 }).children[0].geometry;
+ return JSON.stringify([
+ Array.from(g.attributes.iOff.array),
+ Array.from(g.attributes.iExtra.array),
+ ]);
+};
+console.log(JSON.stringify({
+ same: attrs(3) === attrs(3), differs: attrs(3) !== attrs(9),
+}));
+""", _LIBS)
+ assert out["same"] and out["differs"]
+
+
+def test_the_birds_are_strung_out_along_the_path():
+ """A skein, not a slab: each bird holds its own lag down the route (so
+ it FOLLOWS through the turns) plus its own offset off it. Lags that
+ reached a full loop would wrap the skein onto its own tail."""
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const g = makeFlock({ count: 120, extent: 30, seed: 2 }).children[0].geometry;
+const off = g.attributes.iOff.array;
+const lag = [], side = [], up = [];
+for (let i = 0; i < g.attributes.iOff.count; i++) {
+ side.push(off[i * 3]); up.push(off[i * 3 + 1]); lag.push(off[i * 3 + 2]);
+}
+const span = (a) => Math.max(...a) - Math.min(...a);
+const phases = Array.from(g.attributes.iExtra.array)
+ .filter((_, i) => i % 4 === 0);
+console.log(JSON.stringify({
+ lagSpan: span(lag), sideSpan: span(side), upSpan: span(up),
+ phaseSpan: span(phases),
+}));
+""", _LIBS)
+ assert 0.05 < out["lagSpan"] < 1.0, out
+ assert out["sideSpan"] > 0 and out["upSpan"] > 0, out
+ # Individual phase: one flock beating in unison reads as one object —
+ # and the phase is also the per-bird seed the plumage hashes off.
+ assert out["phaseSpan"] > 5.0, out
+
+
+def test_the_flock_advertises_the_volume_it_flies_through():
+ """`position` is all zeros, so the bounds three would compute are a
+ point at the origin — framing, culling and the zone census would all
+ place a sky-wide flock at the world origin."""
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const g = makeFlock({ count: 40, extent: 50, height: 30 })
+ .children[0].geometry;
+const b = g.boundingBox;
+console.log(JSON.stringify({
+ min: [b.min.x, b.min.y, b.min.z].map((v) => +v.toFixed(1)),
+ max: [b.max.x, b.max.y, b.max.z].map((v) => +v.toFixed(1)),
+ radius: +g.boundingSphere.radius.toFixed(1),
+}));
+""", _LIBS)
+ assert out["max"][0] > 45 and out["min"][0] < -45, out
+ # Altitude: the whole box sits well above the ground it flies over.
+ assert out["min"][1] > 10, out
+ assert out["radius"] > 45, out
+
+
+def test_the_default_plumage_is_an_albedo_a_camera_could_see():
+ """`color` is multiplied by an irradiance now, so it has to be a
+ REFLECTANCE. 0x23262c is 1.5% — darker than any bird, and it rendered
+ as a hole in the sky. The band asserted here is the library's own:
+ non-emissive albedos live in 0.02..0.8 linear."""
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const u = (o) => makeFlock(o).children[0].material.uniforms;
+const bird = u({ count: 4 }).uColor.value;
+const fish = u({ count: 4, kind: 'fish' }).uColor.value;
+console.log(JSON.stringify({
+ bird: [bird.r, bird.g, bird.b], fish: [fish.r, fish.g, fish.b],
+}));
+""", _LIBS)
+ for name in ("bird", "fish"):
+ for c in out[name]:
+ assert 0.02 <= c <= 0.8, (name, out[name])
+
+
+def test_the_light_colours_are_the_caller_s_and_the_sun_is_a_direction():
+ """Nothing bright on a bird is a literal: the sheen, the sunlit side
+ and the backlit primaries all arrive in `sunColor`, and the shaded side
+ in `skyColor`. A scene that hands over its rig gets a flock lit by the
+ same two lights as everything else in the frame."""
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const u = makeFlock({
+ count: 8, sunDir: [0, -0.6, -0.8], sunColor: 0x804000, skyColor: 0x004080,
+}).children[0].material.uniforms;
+const d = u.uSun.value;
+console.log(JSON.stringify({
+ sun: [u.uSunCol.value.r, u.uSunCol.value.g, u.uSunCol.value.b],
+ sky: [u.uSky.value.r, u.uSky.value.g, u.uSky.value.b],
+ len: Math.hypot(d.x, d.y, d.z), below: d.y < 0,
+}));
+""", _LIBS)
+ # Warm light, cool ambient, arriving as the caller set them.
+ assert out["sun"][0] > out["sun"][2], out
+ assert out["sky"][2] > out["sky"][0], out
+ # A direction, normalized, and still under the horizon: that is what
+ # switches the sun term off for a night flock.
+ assert abs(out["len"] - 1.0) < 1e-6, out
+ assert out["below"], out
+
+
+def test_the_shading_reaches_the_fragment_in_the_bird_s_own_frame():
+ """The two wings roll opposite ways through the stroke, so the fragment
+ needs the sun against BOTH the bird's up axis and its wing axis — a
+ single scalar can only make every bird flash at once. That is the
+ varying, and the fragment must be reading it rather than a literal
+ white."""
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const m = makeFlock({ count: 8 }).children[0].material;
+const fs = m.fragmentShader, vs = m.vertexShader;
+console.log(JSON.stringify({
+ varying: /varying\\s+vec4\\s+vLit/.test(vs) && /varying\\s+vec4\\s+vLit/.test(fs),
+ writesBoth: /vLit\\s*=\\s*vec4\\(\\s*dot\\(ud, uSun\\), dot\\(sd, uSun\\)/.test(vs),
+ readsBoth: /vLit\\.x/.test(fs) && /vLit\\.y/.test(fs),
+ mirrored: /q\\.x < 0\\.0 \\? -1\\.0 : 1\\.0/.test(fs),
+ litBySun: /uSunCol/.test(fs) && /uSky/.test(fs),
+ noWhiteMix: !/mix\\(uColor, vec3\\(1\\.0\\)/.test(fs),
+}));
+""", _LIBS)
+ assert out["varying"] and out["writesBoth"] and out["readsBoth"], out
+ assert out["mirrored"], out
+ assert out["litBySun"] and out["noWhiteMix"], out
+
+
+def test_the_flock_stays_out_of_the_depth_and_shadow_passes():
+ """A cloud of alpha-cut billboards drawn into a depth or AO buffer is a
+ stack of solid floors, and a flock does not cast a shadow on the field
+ it crosses."""
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const g = makeFlock({ count: 20 });
+const bad = [];
+g.traverse((o) => {
+ if (!o.isMesh) return;
+ if (o.castShadow) bad.push(o.name + ':castShadow');
+ if (o.material.depthWrite) bad.push(o.name + ':depthWrite');
+ if (!o.material.transparent) bad.push(o.name + ':opaque');
+ if (!o.userData.astraNoOverride) bad.push(o.name + ':override');
+});
+console.log(JSON.stringify({ bad }));
+""", _LIBS)
+ assert out["bad"] == [], out
+
+
+def test_tick_advances_the_shader_clock():
+ out = measure("""
+import { makeFlock } from './lib/flock.js';
+const g = makeFlock({ count: 40 });
+g.userData.tick(2.5);
+const times = [];
+g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.uniforms && m.uniforms.uTime) times.push(m.uniforms.uTime.value);
+ }
+});
+console.log(JSON.stringify({ times }));
+""", _LIBS)
+ assert out["times"] and all(v == 2.5 for v in out["times"])
diff --git a/harness/tests/scene_runtime/lib/test_flowers.py b/harness/tests/scene_runtime/lib/test_flowers.py
new file mode 100644
index 00000000..7d19221b
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_flowers.py
@@ -0,0 +1,745 @@
+"""flowers.js — a patch of flowering plants, and what comes down through the air.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_flowers_lib.py). The reference's properties are kept: the plants
+sit on the CALLER's ground, no two of them are alike, the three kinds are three
+silhouettes out of ONE compiled program, one wind moves the meadow and the
+flowers together, a falling leaf does not come down in a straight line, and
+both fields stay inside the box they advertise.
+
+Their ``scene_check`` compile case is restored at the end of this file, through
+``_probe.compile_scene`` (19 programs, 8 custom materials). What is asserted
+before it is the STRUCTURE of the GLSL, read back off ``onBeforeCompile``; the
+frames are at fx/out/flowers/.
+
+The last three tests are new, and each pins a change the port made:
+the depth pass now cuts the shadow to the petal's own profile (three's depth
+shader has no ``<color_fragment>``, so ``patchStandard`` drops a fragment body
+there silently and the flowers cast the shadow of their RECTANGLES); the petal
+albedo is clamped into a physical range last in the chain (base * rim * tone
+plus the transmitted lift reached 1.36 on the daisy, which is a petal with no
+shading left on it); and the per-plant hue jitter is now small on a saturated
+kind, because ``astraHueShift`` rotates in RGB and drives a near-primary's
+small channels negative — measured on the render, 0.25 rad split the poppy
+field into an amber lobe and a magenta one with nothing in between.
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "noise.js", "grass.js", "foliage_shade.js",
+ "finish.js", "flowers.js")
+
+# Perpendicular deviation of a horizontal path from its own chord: the one
+# number that separates a leaf from a falling stone.
+_DEVIATE = """
+const deviate = (pts) => {
+ const a = pts[0], b = pts[pts.length - 1];
+ const dx = b[0] - a[0], dz = b[1] - a[1];
+ const len = Math.hypot(dx, dz);
+ if (len < 1e-9) {
+ let m = 0;
+ for (const p of pts) m = Math.max(m, Math.hypot(p[0] - a[0], p[1] - a[1]));
+ return m;
+ }
+ let m = 0;
+ for (const p of pts) {
+ m = Math.max(m, Math.abs((p[0] - a[0]) * dz - (p[1] - a[1]) * dx) / len);
+ }
+ return m;
+};
+const jumped = (pts, lim) => {
+ for (let i = 1; i < pts.length; i++) {
+ if (Math.hypot(pts[i][0] - pts[i - 1][0],
+ pts[i][1] - pts[i - 1][1]) > lim) return true;
+ }
+ return false;
+};
+"""
+
+# Run a material's patch chain the way three does, and hand back the GLSL.
+_COMPILE = """
+const compile = (mat, vs, fs) => {
+ const shader = { uniforms: {}, vertexShader: vs, fragmentShader: fs };
+ mat.onBeforeCompile(shader, {});
+ return shader;
+};
+const STD_V = '#include <begin_vertex>\\n';
+const STD_F = 'void main() {\\n#include <color_fragment>\\n}\\n';
+const DEPTH_F = 'void main() {\\n#include <alphatest_fragment>\\n}\\n';
+"""
+
+
+def test_each_field_is_one_draw_call_with_position_at_the_origin():
+ """The bet both factories make: instances are free, meshes are not, so a
+ whole plant — stem, petals and boss — is ONE instance of one geometry. And
+ GTAO redraws with an override material that ignores custom vertex shaders,
+ so a petal left in `position` would stack every copy at the world origin."""
+ out = measure("""
+import { makeFlowers, makeFalling } from './lib/flowers.js';
+const shape = (g) => {
+ const drawn = [];
+ g.traverse((o) => { if (o.isMesh || o.isPoints) drawn.push(o); });
+ const m = drawn[0], geo = m.geometry;
+ return {
+ meshes: drawn.length,
+ instanced: !!geo.isInstancedBufferGeometry,
+ groups: geo.groups.length,
+ materials: [].concat(m.material).length,
+ instances: geo.instanceCount,
+ verts: geo.attributes.position.count,
+ posAllZero: Array.from(geo.attributes.position.array)
+ .every((v) => v === 0),
+ hasCorner: !!geo.attributes.aCorner,
+ hasNormal: !!geo.attributes.normal,
+ guarded: !!m.userData.astraNoOverride,
+ casts: m.castShadow === true,
+ depthShared: !!m.customDepthMaterial
+ && m.customDepthMaterial.userData.uniforms
+ === m.material.userData.uniforms,
+ };
+};
+console.log(JSON.stringify({
+ small: shape(makeFlowers({ extent: 2, density: 9, seed: 2,
+ shadows: true })),
+ big: shape(makeFlowers({ extent: 20, density: 9, seed: 2,
+ shadows: true })),
+ poppy: shape(makeFlowers({ kind: 'poppy', extent: 4, density: 9,
+ shadows: true })),
+ unshadowed: shape(makeFlowers({ extent: 8, density: 9, seed: 2 })),
+ petals: shape(makeFalling({ count: 300 })),
+ leaves: shape(makeFalling({ kind: 'leaf', count: 900 })),
+}));
+""", _LIBS)
+ # A meadow of flower heads in the shadow map stamps a hard block on the
+ # ground under each one, so casting is opt-in as it is for grass.
+ assert out["unshadowed"]["casts"] is False, out["unshadowed"]
+ assert out["unshadowed"]["guarded"], out["unshadowed"]
+ for k in ("small", "big", "poppy", "petals", "leaves"):
+ f = out[k]
+ assert f["meshes"] == 1, (k, out)
+ assert f["instanced"] and f["materials"] == 1, (k, out)
+ # Geometry groups are per-material sub-draws: one draw call means none.
+ assert f["groups"] == 0, (k, out)
+ assert f["posAllZero"] and f["hasCorner"], (k, out)
+ # A zero normal NaNs through the shadow-bias path of every lit
+ # material, and instancedQuad ships none.
+ assert f["hasNormal"], (k, out)
+ assert f["guarded"], (k, out)
+ for k in ("small", "big", "poppy"):
+ assert out[k]["casts"] and out[k]["depthShared"], (k, out)
+ for k in ("petals", "leaves"):
+ assert not out[k]["casts"], (k, out)
+ assert out["small"]["verts"] == out["big"]["verts"], out
+ assert out["big"]["instances"] > 10 * out["small"]["instances"], out
+ assert out["petals"]["instances"] == 300, out
+ assert out["leaves"]["instances"] == 900, out
+
+
+def test_the_stated_sphere_covers_every_flower_at_full_bend():
+ """`position` is all zeros, so the bounds three would derive are a point at
+ the origin — and three CULLS on the sphere. The box also has to hold at
+ every t: the stem is laid over on an arc by a gust the CPU never sees, so
+ the reach is computed from the LARGEST bend that gust term can reach."""
+ out = measure("""
+import { makeFlowers } from './lib/flowers.js';
+const check = (kind) => {
+ const g = makeFlowers({ kind, extent: 5, density: 12, seed: 4,
+ heightAt: (x, z) => 0.1 * x, wind: 1.4 });
+ const m = g.children[0], geo = m.geometry;
+ const u = m.material.userData.uniforms;
+ const P = geo.attributes.iPos.array, S = geo.attributes.iShape.array;
+ const B = geo.attributes.iBend.array;
+ const len = u.uFlowSize.value.x, wid = u.uFlowSize.value.y;
+ const curl = Math.abs(u.uFlowCurl.value);
+ const cup = Math.abs(u.uFlowCup.value);
+ const disc = u.uFlowDisc.value, bulge = u.uFlowBulge.value;
+ const b = geo.boundingBox, s = geo.boundingSphere;
+ let worstBox = -1e9, worstSphere = -1e9, need = 0, top = -1e9;
+ for (let i = 0; i < geo.instanceCount; i++) {
+ const h = S[i * 4], hs = S[i * 4 + 2];
+ const k = Math.min(u.uFlowBend.value, B[i * 4 + 2] + B[i * 4] * 1.19);
+ const fs = hs * 1.25;
+ const outR = disc * hs + len * fs + 0.5 * wid * fs;
+ const upR = curl * len * fs + 0.25 * cup * wid * fs + bulge * hs;
+ const reach = h * (1 - Math.cos(k)) / k + outR;
+ const high = P[i * 3 + 1] + h * Math.sin(k) / k + upR;
+ need = Math.max(need, reach);
+ top = Math.max(top, high);
+ for (const [x, y, z] of [[P[i * 3] + reach, high, P[i * 3 + 2] + reach],
+ [P[i * 3] - reach, P[i * 3 + 1],
+ P[i * 3 + 2] - reach]]) {
+ worstBox = Math.max(worstBox, b.min.x - x, x - b.max.x,
+ b.min.y - y, y - b.max.y,
+ b.min.z - z, z - b.max.z);
+ worstSphere = Math.max(worstSphere,
+ Math.hypot(x - s.center.x, y - s.center.y, z - s.center.z)
+ - s.radius);
+ }
+ }
+ return { worstBox, worstSphere, radius: s.radius, need,
+ box: [b.min.toArray(), b.max.toArray()], top,
+ n: geo.instanceCount };
+};
+console.log(JSON.stringify({
+ daisy: check('daisy'), poppy: check('poppy'), lavender: check('lavender'),
+}));
+""", _LIBS)
+ for kind in ("daisy", "poppy", "lavender"):
+ f = out[kind]
+ assert f["n"] > 100, (kind, out)
+ assert f["worstBox"] <= 1e-6, (kind, out)
+ assert f["worstSphere"] <= 1e-6, (kind, out)
+ # And not a made-up huge number: instancedQuad's 1e4 default would
+ # "cover" anything and cull nothing.
+ true_half = 2.5 + f["need"]
+ assert f["box"][1][0] <= true_half * 1.2, (kind, out)
+ assert f["radius"] <= true_half * 1.7, (kind, out)
+ assert f["box"][0][1] < -0.2, (kind, out)
+ assert f["box"][1][1] < 1.2, (kind, out)
+
+
+def test_the_flowers_are_rooted_on_the_callers_ground():
+ """A flower that ignores `heightAt` hovers over a slope or sinks into it,
+ and no amount of shader work rescues that."""
+ out = measure("""
+import { makeFlowers } from './lib/flowers.js';
+const bed = (x, z) => 0.22 * x - 0.13 * z;
+const g = makeFlowers({ extent: 8, density: 10, seed: 8, heightAt: bed });
+const geo = g.children[0].geometry;
+const P = geo.attributes.iPos.array;
+let err = 0, span = 0, lo = 1e9, hi = -1e9;
+for (let i = 0; i < geo.instanceCount; i++) {
+ const x = P[i * 3], y = P[i * 3 + 1], z = P[i * 3 + 2];
+ err = Math.max(err, Math.abs(y - bed(x, z)));
+ lo = Math.min(lo, y);
+ hi = Math.max(hi, y);
+ span = Math.max(span, Math.abs(x), Math.abs(z));
+}
+const flat = makeFlowers({ extent: 4, density: 10 }).children[0].geometry;
+const F = flat.attributes.iPos.array;
+let flatMax = 0;
+for (let i = 1; i < F.length; i += 3) flatMax = Math.max(flatMax, F[i]);
+console.log(JSON.stringify({ err, lo, hi, span, flatMax,
+ n: geo.instanceCount }));
+""", _LIBS)
+ assert out["err"] < 1e-6, out
+ assert out["hi"] - out["lo"] > 1.0, out
+ assert out["span"] <= 4.0 + 1e-9, out
+ assert out["flatMax"] == 0, out
+
+
+def test_no_two_plants_in_a_patch_are_alike():
+ """A field of identical flowers is a texture. Six things differ per plant,
+ and how far it has OPENED is the one that matters most, because a patch
+ where every bloom is at full spread reads as plastic."""
+ out = measure("""
+import { makeFlowers } from './lib/flowers.js';
+const geo = makeFlowers({ extent: 6, density: 12, seed: 5 })
+ .children[0].geometry;
+const S = geo.attributes.iShape.array, B = geo.attributes.iBend.array;
+const V = geo.attributes.iVar.array;
+const stat = (get) => {
+ const v = [];
+ for (let i = 0; i < geo.instanceCount; i++) v.push(get(i));
+ const mean = v.reduce((a, b) => a + b, 0) / v.length;
+ const sd = Math.sqrt(v.reduce((a, b) => a + (b - mean) ** 2, 0) / v.length);
+ return { spread: (Math.max(...v) - Math.min(...v)) / Math.abs(mean),
+ rel: sd / Math.abs(mean), uniq: new Set(v).size };
+};
+console.log(JSON.stringify({
+ height: stat((i) => S[i * 4]),
+ width: stat((i) => S[i * 4 + 1]),
+ head: stat((i) => S[i * 4 + 2]),
+ open: stat((i) => S[i * 4 + 3]),
+ lean: stat((i) => B[i * 4 + 2]),
+ hue: stat((i) => V[i * 4] + 2),
+ value: stat((i) => V[i * 4 + 3]),
+ n: geo.instanceCount,
+}));
+""", _LIBS)
+ for key, spread in (("height", 0.4), ("width", 0.4), ("head", 0.4),
+ ("open", 0.4), ("lean", 0.4), ("value", 0.25)):
+ f = out[key]
+ # Near-continuous, not three sizes: a per-plant draw, not a lookup
+ # into a table of variants.
+ assert f["uniq"] > 0.9 * out["n"], (key, out)
+ assert f["rel"] > 0.08, (key, out)
+ assert f["spread"] > spread, (key, out)
+ assert out["hue"]["uniq"] > 0.9 * out["n"], out
+
+
+def test_the_three_kinds_are_three_silhouettes():
+ """A disc of petals, a cup and a spike. They share ONE compiled program —
+ the cache key is the patch chain, and the first material to compile a key
+ decides the GLSL for every material that shares it — so the silhouette can
+ only live in uniforms and in the petal layout."""
+ out = measure("""
+import { makeFlowers } from './lib/flowers.js';
+const probe = (kind) => {
+ const m = makeFlowers({ kind, extent: 2, density: 6 }).children[0];
+ const u = m.material.userData.uniforms;
+ const a = m.geometry.attributes.aPart.array;
+ let petals = 0;
+ for (let i = 0; i < a.length; i += 3) petals = Math.max(petals, a[i + 1]);
+ return {
+ key: m.material.customProgramCacheKey(),
+ elev: u.uFlowElev.value, curl: u.uFlowCurl.value,
+ cup: u.uFlowCup.value, spike: u.uFlowSpike.value,
+ step: u.uFlowStep.value, disc: u.uFlowDisc.value,
+ prof: u.uFlowProf.value.toArray(), blotch: u.uFlowBlotch.value,
+ len: u.uFlowSize.value.x, wid: u.uFlowSize.value.y,
+ petals: petals + 1,
+ };
+};
+console.log(JSON.stringify({
+ daisy: probe('daisy'), poppy: probe('poppy'), lavender: probe('lavender'),
+}));
+""", _LIBS)
+ d, p, lv = out["daisy"], out["poppy"], out["lavender"]
+ assert d["key"] == p["key"] == lv["key"], out
+ # A daisy is a FLAT disc of many narrow rays round a boss.
+ assert d["elev"] < 0.3 and d["petals"] >= 10, out
+ assert d["disc"] > 0 and d["wid"] < 0.5 * d["len"], out
+ # A poppy is a CUP: few broad petals, lifted and curled inward, with a
+ # dark blotch at the throat.
+ assert p["elev"] > 2 * d["elev"] and p["petals"] <= 6, out
+ assert p["cup"] > d["cup"] and p["curl"] > 0, out
+ assert p["wid"] > 0.7 * p["len"] and p["blotch"] > 0.5, out
+ # A spike spreads its florets DOWN the stem; the other two gather them.
+ assert lv["spike"] > 0.2 and d["spike"] == 0 and p["spike"] == 0, out
+ assert lv["petals"] > 2 * d["petals"], out
+ assert lv["len"] < 0.6 * d["len"], out
+ assert len({round(d["step"], 4), round(p["step"], 4),
+ round(lv["step"], 4)}) == 3, out
+
+
+def test_one_wind_moves_the_grass_and_the_flowers_together():
+ """`windOf` is IMPORTED from grass.js, not re-read here: a meadow whose
+ flowers lean the other way is worse than a still one."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+import { makeFlowers, makeFalling } from './lib/flowers.js';
+const wind = { dir: [0.3, -0.9], strength: 1.6, speed: 1.7 };
+const grass = makeGrass({ extent: 4, density: 20, wind, sward: false })
+ .children[0].material.userData.uniforms;
+const flow = makeFlowers({ extent: 4, density: 6, wind })
+ .children[0].material.userData.uniforms;
+const bendOf = (w) => {
+ const geo = makeFlowers({ extent: 4, density: 6, seed: 2, wind: w })
+ .children[0].geometry;
+ const B = geo.attributes.iBend.array;
+ let s = 0;
+ for (let i = 0; i < geo.instanceCount; i++) s += B[i * 4];
+ return s / geo.instanceCount;
+};
+const drift = (w) => makeFalling({ wind: w })
+ .children[0].material.userData.uniforms.uFallDrift.value;
+console.log(JSON.stringify({
+ grassDir: grass.uGrassWind.value.toArray(),
+ flowDir: flow.uFlowWind.value.toArray(),
+ grassSpeed: grass.uGrassSpeed.value,
+ flowSpeed: flow.uFlowSpeed.value,
+ bendWeak: bendOf(0.5), bendStrong: bendOf(2),
+ driftWeak: drift(0.5).length(), driftStrong: drift(2).length(),
+ driftDir: drift(wind).clone().normalize().toArray(),
+ defaultDir: makeFlowers({ extent: 1, density: 4 })
+ .children[0].material.userData.uniforms.uFlowWind.value.toArray(),
+}));
+""", _LIBS)
+ assert out["flowDir"] == out["grassDir"], out
+ assert out["flowSpeed"] == out["grassSpeed"] == 1.7, out
+ # grass.js's default is a light breeze toward +X, and a flower that
+ # invented its own default would lean across the meadow.
+ assert abs(out["defaultDir"][0] - 0.9113) < 1e-3, out
+ assert abs(out["defaultDir"][1] - 0.4101) < 1e-3, out
+ assert abs(out["bendStrong"] / out["bendWeak"] - 4) < 1e-6, out
+ assert abs(out["driftStrong"] / out["driftWeak"] - 4) < 1e-6, out
+ assert abs(out["driftDir"][0] - 0.3162) < 1e-3, out
+ assert abs(out["driftDir"][1] + 0.9487) < 1e-3, out
+
+
+def test_a_falling_leaf_does_not_come_down_in_a_straight_line():
+ """The whole difference between a leaf and a dropped stone. `sample(i, t)`
+ is the CPU mirror of the vertex shader, so the path measured is drawn."""
+ out = measure(_DEVIATE + """
+import { makeFalling } from './lib/flowers.js';
+const probe = (kind) => {
+ const g = makeFalling({ kind, count: 300, extent: 12, height: 6,
+ seed: 7, wind: { dir: [1, 0], strength: 1 } });
+ const geo = g.children[0].geometry;
+ const F = geo.attributes.aFall.array, A = geo.attributes.aAxis.array;
+ const dev = [], drop = [];
+ for (let i = 0; i < geo.instanceCount; i++) {
+ const pts = [];
+ for (let k = 0; k <= 24; k++) {
+ const p = g.userData.sample(i, k * 0.25);
+ pts.push([p.x, p.z]);
+ }
+ if (!jumped(pts, 3)) dev.push(deviate(pts));
+ drop.push(g.userData.sample(i, 0).y - g.userData.sample(i, 0.5).y);
+ }
+ dev.sort((a, b) => a - b);
+ const rate = [], spin = [], axes = new Set();
+ for (let i = 0; i < geo.instanceCount; i++) {
+ rate.push(F[i * 4]);
+ spin.push(F[i * 4 + 2]);
+ axes.add([A[i * 3], A[i * 3 + 1], A[i * 3 + 2]].join(','));
+ }
+ let unit = 0;
+ for (let i = 0; i < geo.instanceCount; i++) {
+ unit = Math.max(unit, Math.abs(
+ Math.hypot(A[i * 3], A[i * 3 + 1], A[i * 3 + 2]) - 1));
+ }
+ return {
+ paths: dev.length, minDev: dev[0], medDev: dev[dev.length >> 1],
+ rateSpread: Math.max(...rate) / Math.min(...rate),
+ minSpin: Math.min(...spin.map(Math.abs)),
+ bothWays: spin.some((v) => v > 0) && spin.some((v) => v < 0),
+ spins: new Set(spin).size, axes: axes.size, unit,
+ fell: drop.filter((d) => d > 0).length,
+ rose: drop.filter((d) => d <= 0 && d > -3).length,
+ fall: g.children[0].material.userData.uniforms.uFallRate.value,
+ spinRate: g.children[0].material.userData.uniforms.uFallSpin.value,
+ };
+};
+console.log(JSON.stringify({ petal: probe('petal'), leaf: probe('leaf') }));
+""", _LIBS)
+ for kind in ("petal", "leaf"):
+ f = out[kind]
+ assert f["paths"] >= 100, (kind, out)
+ assert f["minDev"] > 0.002, (kind, out)
+ assert f["medDev"] > 0.02, (kind, out)
+ # Its own rate: the slowest and the fastest differ by half again,
+ # or the field descends as one sheet.
+ assert f["rateSpread"] > 1.5, (kind, out)
+ assert f["minSpin"] > 0 and f["spinRate"] > 0, (kind, out)
+ assert f["bothWays"] and f["spins"] > 250, (kind, out)
+ assert f["axes"] > 250 and f["unit"] < 1e-6, (kind, out)
+ # DOWN, for every one of them: the rest wrapped from the floor back
+ # to the ceiling inside the window.
+ assert f["fell"] > 250 and f["rose"] == 0, (kind, out)
+ # A petal hangs where a leaf drops: slower, and sliding further.
+ assert out["petal"]["fall"] < 0.6 * out["leaf"]["fall"], out
+ assert out["petal"]["medDev"] > out["leaf"]["medDev"], out
+
+
+def test_the_falling_field_stays_inside_the_volume_it_states():
+ """Every position is computed in the shader from `uTime`, so the box is a
+ PROMISE the CPU keeps, at every t and for every piece."""
+ out = measure("""
+import { makeFalling } from './lib/flowers.js';
+const check = (kind, extent, height) => {
+ const g = makeFalling({ kind, count: 200, extent, height, seed: 9,
+ wind: { dir: [1, 0.6], strength: 2 } });
+ const m = g.children[0], geo = m.geometry;
+ const u = m.material.userData.uniforms;
+ const F = geo.attributes.aFall.array;
+ const b = geo.boundingBox, s = geo.boundingSphere;
+ const w = u.uFallSize.value.x, l = u.uFallSize.value.y;
+ const curl = u.uFallCurl.value;
+ let worstBox = -1e9, worstSphere = -1e9;
+ for (let i = 0; i < geo.instanceCount; i++) {
+ const span = 0.5 * Math.hypot(w, l) * F[i * 4 + 1]
+ + 0.25 * curl * w * F[i * 4 + 1];
+ for (let k = 0; k <= 40; k++) {
+ const p = g.userData.sample(i, k * 0.37);
+ worstBox = Math.max(worstBox,
+ b.min.x - (p.x - span), (p.x + span) - b.max.x,
+ b.min.y - (p.y - span), (p.y + span) - b.max.y,
+ b.min.z - (p.z - span), (p.z + span) - b.max.z);
+ worstSphere = Math.max(worstSphere,
+ Math.hypot(p.x - s.center.x, p.y - s.center.y, p.z - s.center.z)
+ + span - s.radius);
+ }
+ }
+ return { worstBox, worstSphere, radius: s.radius,
+ box: [b.min.toArray(), b.max.toArray()] };
+};
+console.log(JSON.stringify({
+ petal: check('petal', 9, 5), leaf: check('leaf', 14, 8),
+}));
+""", _LIBS)
+ for kind, extent, height in (("petal", 9, 5), ("leaf", 14, 8)):
+ f = out[kind]
+ assert f["worstBox"] <= 0, (kind, out)
+ assert f["worstSphere"] <= 0, (kind, out)
+ assert f["box"] == [[-extent / 2, 0, -extent / 2],
+ [extent / 2, height, extent / 2]], (kind, out)
+ want = 0.5 * (2 * (extent ** 2) + height ** 2) ** 0.5
+ assert abs(f["radius"] - want) < 1e-6, (kind, out)
+
+
+def test_the_same_seed_builds_the_same_field():
+ """Determinism is the contract for every shipped factory: a re-run that
+ reshuffles the patch is a re-run nobody can compare against."""
+ out = measure("""
+import { makeFlowers, makeFalling } from './lib/flowers.js';
+const plants = (s) => JSON.stringify(['iPos', 'iShape', 'iBend', 'iVar']
+ .map((k) => Array.from(makeFlowers({ extent: 4, density: 9, seed: s,
+ heightAt: (x, z) => 0.1 * x }).children[0].geometry.attributes[k]
+ .array)));
+const fall = (s) => JSON.stringify(['aPos', 'aFall', 'aAxis', 'aWob']
+ .map((k) => Array.from(makeFalling({ kind: 'leaf', count: 60, seed: s })
+ .children[0].geometry.attributes[k].array)));
+console.log(JSON.stringify({
+ plantsSame: plants(4) === plants(4), plantsDiffer: plants(4) !== plants(9),
+ fallSame: fall(4) === fall(4), fallDiffer: fall(4) !== fall(9),
+ n: JSON.parse(plants(4))[0].length,
+}));
+""", _LIBS)
+ assert out["plantsSame"] and out["plantsDiffer"], out
+ assert out["fallSame"] and out["fallDiffer"], out
+ assert out["n"] > 300, out
+
+
+def test_tick_advances_every_material():
+ """Every moving part lives in the vertex shader, so an un-advanced uTime is
+ a meadow frozen mid-gust with its petals hanging in the air."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeFlowers, makeFalling } from './lib/flowers.js';
+const g = new THREE.Group();
+for (const kind of ['daisy', 'poppy', 'lavender']) {
+ g.add(makeFlowers({ kind, extent: 2, density: 5 }));
+}
+g.add(makeFalling({ kind: 'petal', count: 20 }));
+g.add(makeFalling({ kind: 'leaf', count: 20 }));
+const times = () => {
+ const out = [];
+ g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (!m) continue;
+ const u = (m.uniforms && m.uniforms.uTime) ? m.uniforms
+ : (m.userData && m.userData.uniforms);
+ if (u && u.uTime) out.push(u.uTime.value);
+ }
+ });
+ return out;
+};
+const before = times();
+for (const c of g.children) c.userData.tick(2.5);
+console.log(JSON.stringify({ before, after: times() }));
+""", _LIBS)
+ assert out["before"] == [0] * 5, out
+ assert out["after"] == [2.5] * 5, out
+
+
+def test_the_shadow_is_cut_to_the_petal_and_not_to_its_card():
+ """PORT FIX. A petal is a rectangle the FRAGMENT stage carves a petal out
+ of, and three's depth shader never sees that carving — worse,
+ `patchStandard` writes a fragment body through `<color_fragment>`, which
+ the depth shader does not contain, so the hook is dropped in silence.
+ Measured on the showcase render before this: every shadowed daisy stamped
+ a fused slate slab on the ground and the patch read as litter dropped
+ round the plants. The cut is spliced above three's own alpha test, which
+ is the one place a depth pass may discard, and it reads the SURFACE's
+ profile uniform so the shadow is cut by the curve that is drawn."""
+ out = measure(_COMPILE + """
+import { makeFlowers } from './lib/flowers.js';
+const m = makeFlowers({ kind: 'daisy', extent: 2, density: 4,
+ shadows: true }).children[0];
+const dep = m.customDepthMaterial;
+const d = compile(dep, STD_V, DEPTH_F);
+const surf = compile(m.material, STD_V, STD_F);
+console.log(JSON.stringify({
+ cuts: /discard/.test(d.fragmentShader),
+ byProfile: d.fragmentShader.indexOf('flowProfile(vFlow.y, uFlowProf)') >= 0,
+ aboveAlphaTest: d.fragmentShader.indexOf('discard')
+ < d.fragmentShader.indexOf('#include <alphatest_fragment>'),
+ // The one thing that makes the cut the SAME cut: the depth material is
+ // handed the surface's own uniform map, profile and all.
+ sameProfileObject: dep.userData.uniforms.uFlowProf
+ === m.material.userData.uniforms.uFlowProf,
+ uploaded: !!d.uniforms.uFlowProf,
+ varying: /varying vec4 vFlow;/.test(d.fragmentShader),
+ writesVarying: /vFlow = vec4/.test(d.vertexShader),
+ // and the surface still discards by the same profile.
+ surfaceProfile: surf.fragmentShader.indexOf('flowProfile(') >= 0,
+ // one helper, not two: the vertex head carries it as well and a second
+ // copy in one stage is a GLSL redefinition.
+ vertexCopies: (d.vertexShader.match(/float flowProfile\\(/g) || []).length,
+ fragCopies: (d.fragmentShader.match(/float flowProfile\\(/g) || []).length,
+}));
+""", _LIBS)
+ assert out["cuts"] and out["byProfile"], out
+ assert out["aboveAlphaTest"], out
+ assert out["sameProfileObject"] and out["uploaded"], out
+ assert out["varying"] and out["writesVarying"], out
+ assert out["surfaceProfile"], out
+ assert out["fragCopies"] == 1, out
+ assert out["vertexCopies"] == 0, out
+
+
+def test_a_petal_albedo_stays_inside_the_range_a_petal_can_have():
+ """PORT FIX. Three multipliers ride on the petal's colour — the rim goes
+ paler, the plant has its own tone, and `patchLeafSSS` adds the light that
+ came THROUGH — and on the daisy they reached 1.36. An albedo over 1 is
+ not a brighter petal: it is a petal with no shading left, because the tone
+ map pins every pixel of it to the same white, and the whole silhouette
+ goes to a paper cut-out. The clamp is last in the chain, after the
+ transmitted lift, or it clamps a number that then grows again."""
+ out = measure(_COMPILE + """
+import { makeFlowers, makeFalling } from './lib/flowers.js';
+const m = makeFlowers({ extent: 2, density: 4 }).children[0];
+const fs = compile(m.material, STD_V, STD_F).fragmentShader;
+const fall = makeFalling({ count: 8 }).children[0];
+console.log(JSON.stringify({
+ chain: m.material.customProgramCacheKey(),
+ clampAfterLift: fs.indexOf('clamp(diffuseColor.rgb')
+ > fs.indexOf('uLeafTint * lT'),
+ ceiling: /clamp\\(diffuseColor\\.rgb, vec3\\(0\\.015\\), vec3\\(0\\.86\\)\\)/
+ .test(fs),
+ fallCeiling: /min\\(flCol, vec3\\(0\\.86\\)\\)/.test(
+ compile(fall.material, STD_V, STD_F).fragmentShader),
+}));
+""", _LIBS)
+ # The lift is applied by name, so the order is the chain's order.
+ assert out["chain"].endswith("flowers:albedoRange"), out
+ assert out["clampAfterLift"], out
+ assert out["ceiling"] and out["fallCeiling"], out
+
+
+def test_one_patch_is_one_species_and_still_no_two_flowers_alike():
+ """PORT FIX. `astraHueShift` rotates in RGB about the grey axis, so on a
+ near-primary albedo it drives the small channels NEGATIVE and the clamp
+ turns one swing into two: measured on the render, 0.25 rad of jitter split
+ the poppies into an amber lobe (20-40 deg) and a magenta one (330-355) with
+ nothing in between — 0.72 pink pixels per red one. A saturated kind now
+ rotates barely at all and takes its variety from a stated SIBLING albedo
+ instead, which is an offset in HSL and so follows `opts.color` too. After:
+ 0.12 pink pixels per red one, and the spread is still there."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeFlowers, makeFalling } from './lib/flowers.js';
+const hsl = (c) => { const o = {}; c.getHSL(o); return o; };
+// astraHueShift, spelled in JS: a Rodrigues rotation about the grey axis.
+// Its result is only a hue rotation while it stays inside the cube.
+const K = 0.5773502691896258;
+const rot = (col, a) => {
+ const c = [col.r, col.g, col.b];
+ const ca = Math.cos(a), sa = Math.sin(a);
+ const cr = [K * (c[2] - c[1]), K * (c[0] - c[2]), K * (c[1] - c[0])];
+ const d = K * (c[0] + c[1] + c[2]);
+ return c.map((v, i) => v * ca + cr[i] * sa + K * d * (1 - ca));
+};
+const gamut = (col, swing) => Math.min(
+ ...rot(col, swing / 2), ...rot(col, -swing / 2));
+const probe = (kind) => {
+ const geo = makeFlowers({ kind, extent: 4, density: 9, seed: 5 })
+ .children[0];
+ const u = geo.material.userData.uniforms;
+ const V = geo.geometry.attributes.iVar.array;
+ let lo = 1e9, hi = -1e9;
+ const seen = new Set();
+ for (let i = 0; i < geo.geometry.instanceCount; i++) {
+ lo = Math.min(lo, V[i * 4]);
+ hi = Math.max(hi, V[i * 4]);
+ seen.add(V[i * 4]);
+ }
+ const a = hsl(u.uFlowPetal.value), b = hsl(u.uFlowPetalB.value);
+ let dh = Math.abs(a.h - b.h);
+ dh = Math.min(dh, 1 - dh);
+ return { swing: hi - lo, uniq: seen.size, n: geo.geometry.instanceCount,
+ sat: a.s, satB: b.s, dh, dl: Math.abs(a.l - b.l),
+ gamut: gamut(u.uFlowPetal.value, hi - lo),
+ siblingDiffers: u.uFlowPetal.value.getHex()
+ !== u.uFlowPetalB.value.getHex() };
+};
+const custom = makeFlowers({ kind: 'poppy', color: 0x2f6ad0, extent: 2,
+ density: 4 }).children[0].material.userData
+ .uniforms;
+const fall = (kind) => {
+ const u = makeFalling({ kind, count: 8 }).children[0].material.userData
+ .uniforms;
+ const a = hsl(u.uFallColor.value), b = hsl(u.uFallColorB.value);
+ let dh = Math.abs(a.h - b.h);
+ return { dh: Math.min(dh, 1 - dh), sat: a.s,
+ differs: u.uFallColor.value.getHex()
+ !== u.uFallColorB.value.getHex() };
+};
+console.log(JSON.stringify({
+ daisy: probe('daisy'), poppy: probe('poppy'), lavender: probe('lavender'),
+ customA: custom.uFlowPetal.value.getHexString(),
+ customB: custom.uFlowPetalB.value.getHexString(),
+ petal: fall('petal'), leaf: fall('leaf'),
+}));
+""", _LIBS)
+ for kind in ("daisy", "poppy", "lavender"):
+ f = out[kind]
+ # Still a per-plant draw, never a table of three variants.
+ assert f["uniq"] > 0.9 * f["n"], (kind, out)
+ assert f["siblingDiffers"], (kind, out)
+ # THE rule, stated as the mechanism rather than as a number: the
+ # jitter a kind allows must keep the rotation inside the cube. Once
+ # a channel goes negative the clamp — not the angle — decides the
+ # colour, and the swing stops being a hue and becomes a fork. A
+ # near-primary can afford almost none of it, a violet (no small
+ # channel) a fair amount, a white as much as it likes.
+ # (measured: the poppy reaches -0.0033 at its 0.07, and reached
+ # -0.042 at the 0.5 every kind used to share.)
+ assert f["swing"] > 0.02, (kind, out)
+ assert f["gamut"] > -0.008, (kind, out)
+ # The sibling carries the variety instead: a real second colour, and
+ # still inside the species — either under a fifth of the wheel away,
+ # or so weakly coloured that half a wheel is warm cream to cool
+ # paper rather than a second flower. Both ends have to be pale for
+ # that, which is why the daisy's cool end drops saturation as it
+ # turns: a white that keeps its saturation across the wheel is blue.
+ assert f["dh"] <= 0.2 or max(f["sat"], f["satB"]) < 0.16, (kind, out)
+ assert f["dh"] > 0.005 or f["dl"] > 0.02, (kind, out)
+ # The poppy is the one that forked, and it is the tightest.
+ assert out["poppy"]["swing"] < out["lavender"]["swing"], out
+ assert out["lavender"]["swing"] < out["daisy"]["swing"], out
+ # A caller's own colour gets its own sibling, not the table's.
+ assert out["customA"] != out["customB"], out
+ assert out["customA"].startswith("2f6a"), out
+ for kind in ("petal", "leaf"):
+ assert out[kind]["differs"] and out[kind]["dh"] <= 0.2, (kind, out)
+
+# A FOGGED, shadow-casting scene: `USE_FOG` and the shadow branches only exist
+# in a program built from one, and a patch that drops a chunk compiles fine in
+# an unfogged fixture and renders as a sticker in a real scene.
+_COMPILE_SCENE = """
+import * as THREE from 'three';
+import { tickShaders } from './lib/shader.js';
+import { makeFlowers, makeFalling } from './lib/flowers.js';
+
+export const BOUNDS = { min: [-30, 0, -30], max: [30, 20, 30] };
+export function heightAt(x, z) { return Math.sin(x * 0.1) * 0.3; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.004);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 1.0));
+ const sun = new THREE.DirectionalLight(0xffffff, 3);
+ sun.position.set(10, 20, 10); sun.castShadow = true; scene.add(sun);
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(80, 80),
+ new THREE.MeshStandardMaterial({ color: 0x6d6a52 }));
+ ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground);
+ scene.add(makeFlowers({ extent: 8, heightAt }));
+ scene.add(makeFalling({ extent: 8, height: 5 }));
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [12, 5, 14], lookAt: [0, 2, 0], fov: 45 }],
+ update(t) { tickShaders(scene, t); },
+ };
+}
+"""
+
+
+def test_every_program_compiles_on_the_gpu():
+ """Two separate instanced programs — a rooted field that bends from its base
+ and a falling one that integrates its own drift — each with a vertex stage
+ three never wrote.
+
+ The reference had this case and the port dropped it: `_probe.shader_check`
+ staged only `src/fixture.js` while `check_shaders.mjs` boots the workspace's
+ `src/scene.js`, so it could never run. `_probe.compile_scene` stages the
+ scene, so the case is back (consolidation, 2026-09-01)."""
+ code, out = compile_scene(_COMPILE_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out
diff --git a/harness/tests/scene_runtime/lib/test_foliage_shade.py b/harness/tests/scene_runtime/lib/test_foliage_shade.py
new file mode 100644
index 00000000..c3274c2c
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_foliage_shade.py
@@ -0,0 +1,506 @@
+"""foliage_shade.js: the three cues that make a plant read as alive.
+
+Ported from the reference suite (tests/test_foliage_shade_lib.py) 2026-09-01.
+Every one of these effects is a ``patchStandard`` injection, so nothing here
+can be checked by calling a function: the value of the patch IS the GLSL it
+writes, and a wrong sign or a dropped clamp is a frame that looks lit rather
+than an exception. So these tests read the injected source and assert the
+chain that carries the intent — a front-lit leaf that gets nothing added, a
+base that cannot move, a band measured from the plant's own origin — and then
+hand the whole thing to the GPU.
+
+Two changes from the reference. The last test hands ``_probe.compile_scene``
+a one-line ``src/scene.js`` wrapper around the fixture — the USE_INSTANCING
+branch is preprocessor-guarded and a real InstancedMesh program is the only
+thing that ever compiles it. And the port's own pigment break-up (the
+flat-green fix, measured on fx/out/foliage_shade) is pinned by the two tests
+at the end.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure
+
+_LIBS = ("shader.js", "foliage_shade.js")
+
+_LIB_SRC = (LIB_DIR / "foliage_shade.js").read_text(encoding="utf-8")
+
+# The patch only exists inside onBeforeCompile, so every probe hands it the
+# two chunks patchStandard replaces and reads back what it wrote.
+_PRELUDE = """
+import * as THREE from 'three';
+import { patchLeafSSS, patchWind, patchRootContact }
+ from './lib/foliage_shade.js';
+
+const std = () => new THREE.MeshStandardMaterial({ color: 0x557733 });
+
+function compile(mat) {
+ const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+ };
+ mat.onBeforeCompile(shader);
+ return shader;
+}
+"""
+
+# ONE leaf material on an InstancedMesh AND a plain Mesh: the instanced
+# program is the only place the USE_INSTANCING branch of the world-space
+# helpers is ever compiled.
+_FIXTURE = """
+import * as THREE from 'three';
+import { patchLeafSSS, patchWind, patchRootContact }
+ from './lib/foliage_shade.js';
+
+export function build() {
+ const g = new THREE.Group();
+
+ const leaf = new THREE.MeshStandardMaterial({
+ color: 0x4e7a35, flatShading: true, side: THREE.DoubleSide,
+ });
+ patchLeafSSS(leaf, { sunDir: new THREE.Vector3(0.3, 0.62, -0.72) });
+ patchWind(leaf, { strength: 0.3, height: 5 });
+
+ const crown = new THREE.InstancedMesh(
+ new THREE.IcosahedronGeometry(1.1, 1), leaf, 12);
+ const m = new THREE.Matrix4();
+ for (let i = 0; i < 12; i++) {
+ m.compose(
+ new THREE.Vector3((i % 4) * 3 - 4.5, 4 + (i % 3) * 0.7,
+ Math.floor(i / 4) * 3 - 3),
+ new THREE.Quaternion().setFromEuler(new THREE.Euler(0, i * 0.7, 0)),
+ new THREE.Vector3(1.2, 0.9, 1.1));
+ crown.setMatrixAt(i, m);
+ }
+ crown.instanceMatrix.needsUpdate = true;
+ crown.frustumCulled = false;
+ g.add(crown);
+
+ const card = new THREE.Mesh(new THREE.PlaneGeometry(1.6, 1.6), leaf);
+ card.position.set(2.6, 3.2, 2.4);
+ g.add(card);
+
+ // Base at y = 0 — the contract patchRootContact measures height from.
+ const bark = new THREE.MeshStandardMaterial({ color: 0x6b5540 });
+ patchWind(bark, {
+ strength: 0.06, height: 5, dir: new THREE.Vector2(1, 0),
+ });
+ patchRootContact(bark, { band: 0.6, darken: 0.5 });
+ const stem = new THREE.CylinderGeometry(0.28, 0.5, 5, 12);
+ stem.translate(0, 2.5, 0);
+ const trunk = new THREE.Mesh(stem, bark);
+ trunk.castShadow = true;
+ g.add(trunk);
+ return g;
+}
+"""
+
+# The wrapper check_shaders.mjs boots: our host asks for createScene(), the
+# reference's tool did not.
+_SCENE = """
+import * as THREE from 'three';
+import { build } from './fixture.js';
+
+export const BOUNDS = { min: [-10, 0, -10], max: [10, 10, 10] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.add(new THREE.DirectionalLight(0xffffff, 2));
+ scene.add(build());
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [8, 4, 8], lookAt: [0, 3, 0] }],
+ update() {},
+ };
+}
+"""
+
+
+def _probe(body: str) -> dict:
+ return measure(_PRELUDE + body, _LIBS)
+
+
+def _find(pattern: str, src: str) -> re.Match:
+ m = re.search(pattern, src)
+ assert m, f"{pattern} not in\n{src}"
+ return m
+
+
+def test_the_leaf_glow_fires_only_with_the_sun_behind_the_leaf():
+ """The whole point of the patch: light from BEHIND the surface. The term
+ is a dot against the NEGATED sun so it peaks when the eye looks into the
+ sun through the leaf, clamped at zero so a front-lit leaf is left exactly
+ as it was, and every later line may only SCALE it — one addition anywhere
+ in that chain and the crown glows at noon with the sun at the camera's
+ back."""
+ out = _probe("""
+const m = std();
+patchLeafSSS(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ back = _find(r"float (\w+) = max\(dot\((\w+), -uLeafSun\), 0\.0\);", fs)
+ # The view vector really is surface -> eye, in world space.
+ _find(rf"vec3 {back.group(2)} = normalize\(cameraPosition"
+ r" - vAstraFol\);", fs)
+ term = _find(rf"float (\w+) = uLeafAmt \* pow\({back.group(1)},"
+ r" uLeafPow\);", fs)
+ lt = term.group(1)
+ uses = [ln.strip() for ln in fs.splitlines()
+ if re.search(rf"\b{lt}\b", ln) and f"float {lt} =" not in ln]
+ assert uses, "the transmission term is computed and never used"
+ for line in uses:
+ assert (line.startswith(f"{lt} *=") or line.startswith("+")
+ or line.startswith(f"diffuseColor.rgb += uLeafTint * {lt};")
+ ), line
+ # A crown is not a lamp: what reaches the eye is dappled from the WORLD
+ # position, which also decorrelates neighbouring trees.
+ assert re.search(rf"{lt} \*= [^;]*astraFbm2\(vAstraFol\.xz", fs)
+
+
+def test_leaf_options_arrive_as_uniforms_and_the_sun_is_normalised():
+ """A patch whose knobs are uniforms is one program for every tree in the
+ scene; an un-normalised sunDir would scale the exponent's base and quietly
+ change the lobe, so it is normalised on a COPY — the caller's light
+ direction is not the patch's to mutate."""
+ out = _probe("""
+const a = std();
+patchLeafSSS(a);
+const sun = new THREE.Vector3(0, 4, 0);
+const b = std();
+patchLeafSSS(b, { strength: 0.2, power: 6, sunDir: sun,
+ tint: new THREE.Color(0x112233) });
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ amt: u(a).uLeafAmt.value, pow: u(a).uLeafPow.value,
+ sunLen: u(a).uLeafSun.value.length(), sunY: u(a).uLeafSun.value.y,
+ tint: u(a).uLeafTint.value.getHex(),
+ bAmt: u(b).uLeafAmt.value, bPow: u(b).uLeafPow.value,
+ bSunY: u(b).uLeafSun.value.y, callerSunY: sun.y,
+ bTint: u(b).uLeafTint.value.getHex(),
+}));
+""")
+ assert out["amt"] == 0.55 and out["pow"] == 3
+ assert abs(out["sunLen"] - 1) < 1e-6 and out["sunY"] > 0.5
+ assert out["tint"] == 0xccd966, "a warm yellow-green, not white"
+ assert out["bAmt"] == 0.2 and out["bPow"] == 6
+ assert abs(out["bSunY"] - 1) < 1e-6 and out["callerSunY"] == 4
+ assert out["bTint"] == 0x112233
+
+
+def test_the_transmitted_colour_takes_the_key_lights_own_colour():
+ """New here. A leaf transmits the light that reached it: under a golden
+ rig, or a moon, a hardcoded noon yellow-green is the wrong colour on the
+ one surface in the shot the eye reads as light. `light` multiplies the
+ pigment tint, on a COPY of the caller's colour, and defaults to no
+ change at all."""
+ out = _probe("""
+const a = std();
+patchLeafSSS(a);
+const moon = new THREE.Color(0.5, 0.6, 1.0);
+const b = std();
+patchLeafSSS(b, { light: moon });
+const t = (m) => m.userData.uniforms.uLeafTint.value;
+console.log(JSON.stringify({
+ plain: [t(a).r, t(a).g, t(a).b], lit: [t(b).r, t(b).g, t(b).b],
+ callerB: moon.b,
+}));
+""")
+ p, li = out["plain"], out["lit"]
+ assert li[0] == p[0] * 0.5 and li[2] == p[2]
+ assert li[2] / max(li[0], 1e-9) > p[2] / p[0], "moonlight must go cooler"
+ assert out["callerB"] == 1.0, "the caller's colour is not ours to scale"
+
+
+def test_wind_pins_the_base_and_puts_the_travel_in_the_tip():
+ """A plant that slides sideways as a whole has come loose from the ground.
+ The bend is the plant's own height fraction SQUARED, so it is exactly zero
+ at the base and carries the full `strength` only at the tip; normalising
+ by the asset's own height (not by a world y) is what lets a scaled
+ instance and a tree on a hill sway alike."""
+ out = _probe("""
+const m = std();
+patchWind(m, { strength: 0.4, speed: 2, height: 6 });
+const u = m.userData.uniforms;
+console.log(JSON.stringify({
+ vs: compile(m).vertexShader,
+ amp: u.uWindAmp.value, speed: u.uWindSpeed.value, h: u.uWindH.value,
+ dirLen: u.uWindDir.value.length(),
+}));
+""")
+ vs = out["vs"]
+ bend = _find(r"float (\w+) = clamp\(transformed\.y"
+ r" / max\(uWindH, 1e-3\), 0\.0, 1\.0\);", vs)
+ b = bend.group(1)
+ _find(rf"transformed \+= (\w+) \* \(uWindAmp \* {b} \* {b} \* (\w+)\);",
+ vs)
+ assert out["amp"] == 0.4 and out["speed"] == 2 and out["h"] == 6
+ # An un-normalised dir would multiply the metres the caller asked for.
+ assert abs(out["dirLen"] - 1) < 1e-6
+
+
+def test_wind_takes_its_phase_from_each_plants_world_origin():
+ """Two rules at once. The phase comes from the plant's ORIGIN, never from
+ the vertex — a per-vertex phase shears one plant apart — and it is offset
+ by astraStagger, whose several-turn spread is what stops a scattered row
+ from nodding in step. No PRNG anywhere: the world position is the seed,
+ so a re-render places the same sway."""
+ out = _probe("""
+const m = std();
+patchWind(m);
+console.log(JSON.stringify({ vs: compile(m).vertexShader }));
+""")
+ vs = out["vs"]
+ origin = _find(r"vec3 (\w+) = astraFolWorld\(vec3\(0\.0\)\);", vs)
+ phase = _find(r"float (\w+) = uTime \* uWindSpeed"
+ r" \+ astraStagger\(([^)]*)\);", vs)
+ seed = phase.group(2)
+ assert origin.group(1) in seed, seed
+ assert "transformed" not in seed, "per-vertex phase tears the plant"
+ _find(rf"sin\({phase.group(1)}\)", vs)
+ assert "Math.random" not in _LIB_SRC
+
+
+def test_wind_reaches_an_instanced_mesh_and_a_plain_mesh_alike():
+ """`instanceMatrix` is applied in <project_vertex>, AFTER the body patched
+ in at <begin_vertex>, so world space here is hand-built behind a
+ USE_INSTANCING guard — and three declares that attribute itself, so a
+ second declaration would fail every instanced plant. The wind direction
+ is carried into the plant's own frame too: scatter.js yaws every instance,
+ and an object-space wind would blow a different way for each one."""
+ out = _probe("""
+const m = std();
+patchWind(m);
+console.log(JSON.stringify({ vs: compile(m).vertexShader }));
+""")
+ vs = out["vs"]
+ world = vs[vs.index("vec3 astraFolWorld("):]
+ world = world[:world.index("\n}")]
+ assert "#ifdef USE_INSTANCING" in world
+ assert "modelMatrix * instanceMatrix * vec4(p, 1.0)" in world
+ assert "#else" in world and "modelMatrix * vec4(p, 1.0)" in world
+ assert "attribute mat4 instanceMatrix" not in vs
+ _find(r"vec3 (\w+) = astraFolLocalDir\(vec3\(uWindDir\.x, 0\.0,"
+ r" uWindDir\.y\)\);", vs)
+ # fwidth is fragment-only and the util block ships in both stages:
+ # astraStroke may be DEFINED in the vertex shader (behind its guard),
+ # never called from a vertex body.
+ assert vs.count("astraStroke(") == 1
+ assert "#define ASTRA_FRAG" not in vs
+
+
+def test_wind_declares_the_time_uniform_its_body_reads():
+ """patchStandard's withTime pass runs over the head and the original
+ source BEFORE the body is injected, so a vertexBody that reads uTime gets
+ no declaration from it — the patch declares its own, exactly once, or
+ every plant fails to compile on an undeclared identifier."""
+ out = _probe("""
+const m = std();
+patchWind(m);
+const s = compile(m);
+console.log(JSON.stringify({
+ vsDecls: (s.vertexShader.match(/uniform float uTime;/g) || []).length,
+ reads: s.vertexShader.includes('uTime * uWindSpeed'),
+ driven: !!m.userData.uniforms.uTime,
+}));
+""")
+ assert out["reads"] and out["vsDecls"] == 1
+ # tickShaders() finds it through userData, so one call in tick() advances
+ # the sway.
+ assert out["driven"]
+
+
+def test_the_root_band_is_measured_from_the_plants_own_base():
+ """`band` is metres above the CONTACT, so the height it shades is the
+ vertex's world y minus the object origin's world y. Measuring from world
+ zero instead would put the litter ring underground on any tree standing on
+ a hill, which is where trees stand."""
+ out = _probe("""
+const m = std();
+patchRootContact(m, { band: 0.6, darken: 0.3 });
+const s = compile(m);
+const u = m.userData.uniforms;
+console.log(JSON.stringify({
+ vs: s.vertexShader, fs: s.fragmentShader,
+ band: u.uRootBand.value, dark: u.uRootDark.value,
+ litter: u.uRootLitter.value.getHex(),
+}));
+""")
+ _find(r"vAstraRootH = astraFolWorld\(transformed\)\.y"
+ r" - astraFolWorld\(vec3\(0\.0\)\)\.y;", out["vs"])
+ fs = out["fs"]
+ band = _find(r"float (\w+) = astraContact\((\w+), uRootBand\);", fs)
+ k = band.group(1)
+ # Darkening scales the albedo down and the litter is a tint toward the
+ # fallen-leaf colour; both fade out with the same band.
+ _find(rf"diffuseColor\.rgb \*= 1\.0 - uRootDark \* {k};", fs)
+ _find(rf"diffuseColor\.rgb = mix\(diffuseColor\.rgb, \w+,"
+ rf" {k} \* {k} [^;]*\);", fs)
+ assert out["band"] == 0.6 and out["dark"] == 0.3
+ assert out["litter"] == 0x4a3a26
+
+
+def test_the_litter_edge_is_broken_across_the_band_not_along_it():
+ """Structure runs ACROSS the flow. The band's flow is vertical, so its
+ break-up has to be horizontal: the noise moves the HEIGHT the litter
+ reaches and is sampled from world XZ, which makes the edge ragged around
+ the trunk. Noise ranked up the band instead would stripe the trunk in
+ horizontal bands. The port raised its frequency: a trunk is about half a
+ metre across, and the reference's 3-per-metre field crosses it in one and
+ a half cycles — a tilted line, not a ragged one (fx/crop_fol_root_*.png).
+ And the litter itself is hue-broken, because fallen leaves are never one
+ brown."""
+ out = _probe("""
+const m = std();
+patchRootContact(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ height = _find(r"float (\w+) = vAstraRootH - uRootBand \* [^;]+;", fs)
+ scale = _find(r"astraFbm2\(vAstraFol\.xz \* ([0-9.]+),", height.group(0))
+ assert float(scale.group(1)) >= 6, "one cycle across a trunk is a line"
+ _find(rf"astraContact\({height.group(1)}, uRootBand\)", fs)
+ assert "astraFbm2(vAstraFol.y" not in fs
+ litter = _find(r"vec3 (\w+) = astraHueBreak\(uRootLitter, vAstraFol\.xz,"
+ r" [^;]+\);", fs)
+ _find(rf"mix\(diffuseColor\.rgb, {litter.group(1)},", fs)
+
+
+def test_the_pigment_is_broken_up_before_the_glow_goes_on():
+ """The port's own fix, and the one that decides whether a crown reads as
+ a plant or as green plastic: one material over a whole tree paints one
+ flat green, and the transmission then washes that single tone paler. The
+ break runs FIRST, at two coarse world scales (a third, finer octave was
+ tried and cut — smooth noise under a metre reads as camouflage), with the
+ value swing riding the COARSER field so warm clumps are also the light
+ ones. Measured on fx/out/foliage_shade: crown hue spread 27 -> 35 deg
+ close in, 35 -> 45 deg at 20 m, one-value-bin share 0.49 -> 0.30."""
+ out = _probe("""
+const m = std();
+patchLeafSSS(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ body = fs[fs.index("void main"):]
+ breaks = re.findall(r"astraHueBreak\(diffuseColor\.rgb, (\w+),\s*"
+ r"([0-9.]+) \* uLeafVarS", body)
+ assert len(breaks) == 2, body
+ assert breaks[0][0] == breaks[1][0], "both scales sample one field"
+ coarse, fine = float(breaks[0][1]), float(breaks[1][1])
+ assert coarse < fine, "the clump break is the coarser of the two"
+ # The field folds height in: an xz-only sample paints one tone down a
+ # whole column of leaves.
+ _find(rf"vec2 {breaks[0][0]} = vAstraFol\.xz \+ vAstraFol\.y", body)
+ # Value rides the coarse field, so warm reads as sunlit, not as olive.
+ val = _find(rf"float (\w+) = clamp\(\(astraFbm2\({breaks[0][0]} \*"
+ rf" {coarse} \* uLeafVarS, 2\)\s*- [0-9.]+\) \*"
+ r" [0-9.]+, -1\.0, 1\.0\);", body)
+ _find(rf"diffuseColor\.rgb \*= 1\.0 \+ uLeafVar \* [0-9.]+ \*"
+ rf" {val.group(1)};", body)
+ # Every line of it scales by uLeafVar, so variance: 0 is exactly the
+ # unbroken albedo — an agent that wants a flat colour still gets one.
+ assert body.index("astraHueBreak") < body.index("uLeafTint")
+
+
+def test_the_pigment_break_is_a_uniform_and_retunes_in_place():
+ """Scale and swing are uniforms, so a meadow of grass and a canopy read
+ from 40 m share one program, and a second call retunes rather than
+ injecting a second copy of the break."""
+ out = _probe("""
+const a = std();
+patchLeafSSS(a);
+const b = std();
+patchLeafSSS(b, { variance: 0, varyScale: 4 });
+patchLeafSSS(b, { variance: 0.9, varyScale: 3 });
+const u = (m) => m.userData.uniforms;
+const fs = compile(b).fragmentShader;
+console.log(JSON.stringify({
+ var0: u(a).uLeafVar.value, scale0: u(a).uLeafVarS.value,
+ varB: u(b).uLeafVar.value, scaleB: u(b).uLeafVarS.value,
+ breaks: (fs.match(/astraHueBreak\\(diffuseColor/g) || []).length,
+}));
+""")
+ assert out["var0"] == 0.6 and out["scale0"] == 1
+ assert out["varB"] == 0.9 and out["scaleB"] == 3
+ assert out["breaks"] == 2, "a re-applied patch must not stack its code"
+
+
+def test_the_three_patches_stack_on_one_material_exactly_once():
+ """Leaves that both glow and sway are two calls on one leaf material, so
+ stacking is the ordinary case. patchStandard chains them, but it repeats
+ whatever it is handed: the shared world-space helpers must be emitted ONCE
+ (a second function body is a compile error), and a re-applied patch has to
+ retune its uniforms rather than inject its declarations a second time."""
+ out = _probe("""
+const all = std();
+patchLeafSSS(all);
+patchWind(all, { strength: 0.2 });
+patchRootContact(all);
+patchWind(all, { strength: 0.9 });
+const s = compile(all);
+const windOnly = std();
+patchWind(windOnly);
+const count = (src, needle) => src.split(needle).length - 1;
+console.log(JSON.stringify({
+ key: all.customProgramCacheKey(),
+ windKey: windOnly.customProgramCacheKey(),
+ leaf: s.fragmentShader.includes('uLeafTint * lT'),
+ wind: s.vertexShader.includes('uWindAmp * wB * wB'),
+ root: s.fragmentShader.includes('uRootDark'),
+ amp: all.userData.uniforms.uWindAmp.value,
+ worldFn: count(s.vertexShader, 'vec3 astraFolWorld(vec3 p) {'),
+ bend: count(s.vertexShader, 'float wB ='),
+ varyVs: count(s.vertexShader, 'varying vec3 vAstraFol;'),
+ varyFs: count(s.fragmentShader, 'varying vec3 vAstraFol;'),
+}));
+""")
+ assert out["leaf"] and out["wind"] and out["root"]
+ assert out["worldFn"] == 1 and out["varyVs"] == 1 and out["varyFs"] == 1
+ # Every option is a uniform, so re-applying a patch retunes it in place
+ # instead of stacking a second copy of its code.
+ assert out["bend"] == 1 and out["amp"] == 0.9
+ for part in ("leaf", "wind", "root"):
+ assert part in out["key"], out["key"]
+ # three caches programs by key: a material carrying more patches must not
+ # collide with one carrying fewer.
+ assert out["key"] != out["windKey"]
+
+
+def test_no_vertex_body_leans_on_another_patchs_varying():
+ """patchStandard injects each body straight after <begin_vertex>, and the
+ bodies are joined in call order, so a vertex body that read a varying
+ another patch writes would depend on which order the caller happened to
+ patch in. Every body here stands alone; the shared world position is
+ written for the FRAGMENT stage only."""
+ out = _probe("""
+const m = std();
+patchLeafSSS(m);
+patchWind(m);
+patchRootContact(m);
+console.log(JSON.stringify({ vs: compile(m).vertexShader }));
+""")
+ body = out["vs"][out["vs"].index("void main"):]
+ reads = [ln.strip() for ln in body.splitlines()
+ if "vAstraFol" in ln and "vAstraRootH" not in ln]
+ assert reads == ["vAstraFol = astraFolWorld(transformed);"], reads
+
+
+def test_all_three_patches_compile_on_the_gpu():
+ """The only witness that the USE_INSTANCING branch exists at all: it is
+ preprocessor-guarded, so nothing but a real InstancedMesh program ever
+ compiles it. The fixture puts one leaf material on both an InstancedMesh
+ and a plain Mesh, and flat shading on it — the patch must not lean on
+ vNormal, which three omits when FLAT_SHADED, and the fragment hook runs
+ before <normal_fragment_begin> in any case."""
+ code, out = compile_scene(_SCENE, _LIBS, extra={"fixture.js": _FIXTURE})
+ assert code == 0, out
+ report = json.loads(out.strip().splitlines()[-1])
+ assert report["ok"] and report["errors"] == [], out
+ # Two patched built-ins, and MORE programs than materials: the leaf
+ # material compiled twice, once per instancing state.
+ assert report["compile"]["programs"] >= 3, report["compile"]
diff --git a/harness/tests/scene_runtime/lib/test_godrays.py b/harness/tests/scene_runtime/lib/test_godrays.py
new file mode 100644
index 00000000..5fcd2c4f
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_godrays.py
@@ -0,0 +1,572 @@
+"""godrays.js: shafts of light, their floor pools and the dust in them.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_godrays_lib.py). Their geometric laws are kept as they stood —
+a shaft reads as LIGHT only when it is volumeless and chord-weighted (so it
+can never draw its own silhouette), when it slants along the sun instead of
+standing up as a prism, and when it opens as it falls — and their two
+clipping laws with them: added light cannot see what it adds to, so a bright
+frame gets a scattering veil rather than an added one, and added light
+STACKS, so a heavy rig is damped by its own beam load. Their GPU compile
+runs through `_probe.compile_scene`, which stages the fixture as a workspace
+`src/scene.js` — the shape `check_shaders.mjs` boots.
+
+THE PORT'S OWN LAWS — each one a frame rendered on our host at
+fx/out/godrays/, looked at, and measured against a control render of the
+same scene with the group removed:
+
+1. A SHAFT OF LIGHT MAY NOT DARKEN WHAT IT CROSSES. The scattering branch
+ wrote its veil at colour 1.0, which ACES + sRGB land at 0.915 — under the
+ 0.94 this host's sky sits at. Measured over the effect's own pixels,
+ 2.6% of them came out DARKER than the control: the beams read as grey
+ smoke where they passed the sky. The veil is lifted into the ACES
+ shoulder (1.9 -> 0.96) instead, and 100.0% of the effect's pixels now
+ lift the frame. The additive branch is untouched: there the alpha
+ already is the brightness, and the gain was measured against clipping.
+
+2. THE POOLS AND THE DUST ARE ADDED LIGHT TOO. Only the shafts were ever
+ taught what a bright frame costs. On the eight 2.2 m outdoor rig the
+ shafts had already been fixed for, the dust arrived as white bokeh balls
+ hanging in the SKY and the pools as blown discs on sunlit dirt: 2.17% of
+ the effect's pixels past 0.97 (0.52% of the whole frame), peak lift
+ +0.33. Riding the same two corrections takes that to 0.04% (0.01% of
+ the frame) and +0.12 while keeping 14.7% coverage — the effect is still
+ there, it just stopped clipping.
+
+3. DUST IS SMALL. A mote was sized at a tenth of the beam's width, which
+ at close range is a 25 px white disc — falling snow, or a dirty lens,
+ never air. A third of that, with a sharper core, is a glint.
+
+4. THE AIR IS NOT THE LAMP. Every part of the effect now carries two
+ tints, the source hue in the core and an AIR hue at the far end and the
+ rim, and the air one is DERIVED from the caller's own colour rather than
+ stated — a hardcoded blue haze under a red sun is a beam whose far end
+ disagrees with its own scene.
+"""
+
+from __future__ import annotations
+
+from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "godrays.js")
+
+# Per-shaft end rings, recovered from the merged geometry: uv.y is 0 at the
+# gap the light comes through and 1 where it lands, and aShaft tags which
+# shaft a vertex belongs to.
+_RINGS = """
+function rings(mesh) {
+ const p = mesh.geometry.attributes.position.array;
+ const uv = mesh.geometry.attributes.uv.array;
+ const tag = mesh.geometry.attributes.aShaft.array;
+ const acc = new Map();
+ for (let i = 0; i < tag.length; i++) {
+ const v = uv[i * 2 + 1];
+ const end = v < 1e-6 ? 'top' : (v > 1 - 1e-6 ? 'bot' : null);
+ if (!end) continue;
+ const k = tag[i].toFixed(4);
+ if (!acc.has(k)) acc.set(k, { top: [], bot: [] });
+ acc.get(k)[end].push([p[i * 3], p[i * 3 + 1], p[i * 3 + 2]]);
+ }
+ const mean = (pts) => pts.reduce(
+ (a, q) => [a[0] + q[0] / pts.length, a[1] + q[1] / pts.length,
+ a[2] + q[2] / pts.length], [0, 0, 0]);
+ const radius = (pts, c) => pts.reduce(
+ (a, q) => a + Math.hypot(q[0] - c[0], q[1] - c[1], q[2] - c[2])
+ / pts.length, 0);
+ return [...acc.values()].map((r) => {
+ const t = mean(r.top), b = mean(r.bot);
+ const d = [b[0] - t[0], b[1] - t[1], b[2] - t[2]];
+ const L = Math.hypot(d[0], d[1], d[2]);
+ return {
+ axis: [d[0] / L, d[1] / L, d[2] / L],
+ run: Math.hypot(d[0], d[2]),
+ rTop: radius(r.top, t), rBot: radius(r.bot, b),
+ };
+ });
+}
+"""
+
+# The scene our check_shaders.mjs boots: fog, so USE_FOG is defined and the
+# fog branches in three custom shaders actually compile, and a camera,
+# because a scene with none is reported as not booted and never reaches the
+# compile stage at all.
+_SCENE = """
+import * as THREE from 'three';
+import { makeGodRays } from './lib/godrays.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 20, 20] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xc9d6e0, 0.02);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ // Both branches, because they are two different materials.
+ const day = makeGodRays({ count: 6, height: 5, seed: 4 });
+ const room = makeGodRays({ count: 3, height: 5, ambient: 0.05, seed: 9 });
+ room.position.set(9, 0, 0);
+ scene.add(day);
+ scene.add(room);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [8, 4, 10], lookAt: [0, 2, 0],
+ fov: 45 }],
+ update(t) { day.userData.tick(t); room.userData.tick(t); },
+ };
+}
+"""
+
+
+def test_the_shafts_slant_along_the_sun_and_open_as_they_fall():
+ """Parallel rays converge on the sun through perspective alone, so every
+ shaft must carry the SAME direction — a fanned set converges nowhere. A
+ vertical shaft of constant width is the shape that reads as a pipe, so
+ it must also slant and widen."""
+ out = measure(_RINGS + """
+import { makeGodRays } from './lib/godrays.js';
+const sun = [-0.42, -1.0, 0.24];
+const n = Math.hypot(...sun);
+const hat = sun.map((v) => v / n);
+const g = makeGodRays({ count: 6, height: 5, sunDir: sun, seed: 4 });
+const rs = rings(g.getObjectByName('Shafts'));
+const box = new (await import('three')).Box3().setFromObject(g);
+console.log(JSON.stringify({
+ shafts: rs.length,
+ // 1 means the shaft points exactly where the light travels.
+ alignMin: Math.min(...rs.map(
+ (r) => r.axis[0] * hat[0] + r.axis[1] * hat[1] + r.axis[2] * hat[2])),
+ // 1 would be straight down: a vertical prism.
+ uprightMax: Math.max(...rs.map((r) => -r.axis[1])),
+ runMin: Math.min(...rs.map((r) => r.run)),
+ flareMin: Math.min(...rs.map((r) => r.rBot / r.rTop)),
+ minY: +box.min.y.toFixed(3),
+ names: g.children.map((c) => c.name).sort(),
+ hasTick: typeof g.userData.tick === 'function',
+}));
+""", _LIBS)
+ assert out["shafts"] == 6, out
+ assert out["alignMin"] > 0.999, out
+ # Slanted: at least ~14 degrees off vertical, and the foot of the shaft
+ # is metres downstream of its head.
+ assert out["uprightMax"] < 0.97, out
+ assert out["runMin"] > 5 * 0.25, out
+ # Opens toward the floor instead of holding one cross-section.
+ assert out["flareMin"] > 1.2, out
+ assert abs(out["minY"]) <= 0.02, out
+ assert out["names"] == ["Motes", "Pools", "Shafts"]
+ assert out["hasTick"]
+
+
+def test_the_shafts_are_additive_light_and_fade_at_their_own_edge():
+ """The failure mode is a solid glowing cylinder, and it has one cause:
+ an unweighted double-sided shell stacks its front and back faces at the
+ silhouette into a bright outline. Additive blending with no depth write
+ makes the shaft brighten what is behind it instead of hiding it; the
+ astraFacing weight is what deletes the outline, because |n.v| is the
+ chord the eye cuts through the beam and it goes to zero at the rim."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeGodRays } from './lib/godrays.js';
+// The additive build, which is what an UNLIT interior asks for by name —
+// the default scatters.
+const g = makeGodRays({ count: 4, ambient: 0.0 });
+const mats = [];
+g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (m) mats.push({ name: o.name, m });
+ }
+});
+const shaft = mats.find((e) => e.name === 'Shafts').m;
+console.log(JSON.stringify({
+ additive: mats.every((e) => e.m.blending === THREE.AdditiveBlending),
+ noDepthWrite: mats.every((e) => e.m.depthWrite === false),
+ transparent: mats.every((e) => e.m.transparent === true),
+ bothSides: shaft.side === THREE.DoubleSide,
+ // GLSL_UTIL DEFINES both helpers in every shader, so only a second
+ // occurrence is a call.
+ facing: (shaft.fragmentShader.match(/astraFacing\\(/g) || []).length,
+ fresnel: (shaft.fragmentShader.match(/astraFresnel\\(/g) || []).length,
+}));
+""", _LIBS)
+ assert out["additive"] and out["noDepthWrite"] and out["transparent"]
+ assert out["bothSides"] and out["facing"] >= 2, out
+ # A fresnel rim is the exact opposite weighting: it BRIGHTENS the
+ # silhouette, which is how a beam turns into a tube.
+ assert out["fresnel"] == 1, out
+
+
+def test_the_motes_keep_position_at_the_origin():
+ """GTAOPass redraws with an override material that ignores custom vertex
+ shaders, so a billboard that keeps its quad in `position` burns a black
+ rectangle at the world origin."""
+ out = measure("""
+import { makeGodRays } from './lib/godrays.js';
+const g = makeGodRays({ count: 5 });
+const motes = g.getObjectByName('Motes');
+const pos = Array.from(motes.geometry.attributes.position.array);
+console.log(JSON.stringify({
+ posAllZero: pos.every((v) => v === 0),
+ hasCorner: !!motes.geometry.attributes.aCorner,
+ motes: motes.geometry.instanceCount,
+ seeded: motes.geometry.attributes.aSeed.count,
+ poolsPerShaft: g.getObjectByName('Pools').geometry.instanceCount,
+}));
+""", _LIBS)
+ assert out["posAllZero"] and out["hasCorner"]
+ assert out["motes"] > 0 and out["seeded"] == out["motes"]
+ assert out["poolsPerShaft"] == 5
+
+
+def test_the_instanced_fields_state_a_real_bounding_sphere():
+ """`position` is zero on both instanced lattices, so three's own sphere
+ would be a point at the origin and culling would drop the whole field
+ the moment the origin left frame. The stated radius was
+ `run + side * 2` on two Vector3s, which JavaScript evaluates to the
+ STRING "[object Object]NaN": both fields shipped a bounding sphere of
+ NaN radius, inert only because both also set frustumCulled = false."""
+ out = measure("""
+import { makeGodRays } from './lib/godrays.js';
+const g = makeGodRays({ count: 5, height: 8, width: 0.9, seed: 2 });
+const r = (n) => g.getObjectByName(n).geometry.boundingSphere.radius;
+console.log(JSON.stringify({
+ pools: r('Pools'), motes: r('Motes'),
+ finite: Number.isFinite(r('Pools')) && Number.isFinite(r('Motes')),
+}));
+""", _LIBS)
+ assert out["finite"], out
+ # It has to actually cover the field: the drop alone is 8 m.
+ assert out["pools"] > 8 and out["motes"] > 8, out
+ # ...and not the 10 km default, which frames a kilometre of empty air.
+ assert out["pools"] < 200 and out["motes"] < 200, out
+
+
+def test_two_fields_with_one_seed_are_identical():
+ """Determinism is the contract for every shipped factory: a re-run that
+ reshuffles the dust is a re-run nobody can compare against."""
+ out = measure("""
+import { makeGodRays } from './lib/godrays.js';
+const dump = (s) => {
+ const g = makeGodRays({ seed: s, count: 5 });
+ const parts = [];
+ g.traverse((o) => {
+ if (!o.isMesh) return;
+ for (const k of Object.keys(o.geometry.attributes).sort()) {
+ parts.push(o.name, k,
+ Array.from(o.geometry.attributes[k].array).join(','));
+ }
+ });
+ return parts.join('|');
+};
+const a = dump(6), b = dump(6), c = dump(19);
+console.log(JSON.stringify({
+ same: a === b, differs: a !== c, bytes: a.length,
+}));
+""", _LIBS)
+ assert out["same"] and out["differs"] and out["bytes"] > 1000
+
+
+def test_tick_advances_every_material_in_the_group():
+ out = measure("""
+import { makeGodRays } from './lib/godrays.js';
+const g = makeGodRays({ count: 4 });
+g.userData.tick(2.5);
+const times = [];
+g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.uniforms && m.uniforms.uTime) times.push(m.uniforms.uTime.value);
+ }
+});
+console.log(JSON.stringify({ times }));
+""", _LIBS)
+ assert len(out["times"]) == 3
+ assert all(v == 2.5 for v in out["times"])
+
+
+def test_the_whole_field_compiles_on_the_real_renderer():
+ """The retreat to a flat material starts here: a custom shader without
+ the depth chunks is discarded with no error at all, and the dust rides a
+ raw vertex shader that hand-carries them. Only the GPU can say whether
+ that was done right — and it has to say it for BOTH branches, since the
+ scattering and the adding build are two different programs."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert '"custom_materials":6' in out.replace(" ", ""), out
+ # The billboard route must not trip the fog or GTAO warnings either.
+ assert "WARN" not in out, out
+
+
+def test_bright_surroundings_switch_the_shafts_from_adding_to_scattering():
+ """Added light cannot see what it adds to. Measured on the asset the
+ composer actually asked for — six shafts 4 m wide and 35 m tall — the
+ additive build blew 12.8% of a pale frame past 0.97, and cutting the
+ gain 3.6x only reached 11.3%, because 0.94 plus anything visible still
+ clips. From ambient 0.35 up the shafts scatter instead: normal
+ blending, paler, lower alpha, which lowers the contrast behind them the
+ way a daylight shaft does."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeGodRays } from './lib/godrays.js';
+const shaftMat = (g) => g.getObjectByName('Shafts').material;
+const dark = shaftMat(makeGodRays({ ambient: 0.0, seed: 3 }));
+const open = shaftMat(makeGodRays({ ambient: 1.0, seed: 3 }));
+console.log(JSON.stringify({
+ darkAdds: dark.blending === THREE.AdditiveBlending,
+ openScatters: open.blending === THREE.NormalBlending,
+ paler: open.uniforms.uColor.value.b > dark.uniforms.uColor.value.b,
+ // A room has no haze in front of the beam; the open air does.
+ roomAir: dark.uniforms.uAirMix.value,
+ openAir: open.uniforms.uAirMix.value,
+ bothDepthWrite: dark.depthWrite === false && open.depthWrite === false,
+}));
+""", _LIBS)
+ assert out["darkAdds"], "an unlit interior still gets added light"
+ assert out["openScatters"], "an open scene must not add to a bright frame"
+ assert out["paler"] and out["bothDepthWrite"]
+ assert out["roomAir"] == 0.0 and out["openAir"] > 0.15, out
+
+
+def test_the_scattering_veil_is_brighter_than_the_sky_it_crosses():
+ """PORT LAW 1. A normal blend REPLACES what is behind it in proportion
+ to alpha, so its colour has to carry the luminance the additive branch
+ carries in its alpha. At 1.0 the veil tone-maps (ACES, exposure 1.0,
+ sRGB out — this host has no post chain, so it happens in the fragment
+ tail) to 0.915, under the 0.94 our sky sits at: measured against a
+ control render, 2.6% of the effect's own pixels came out darker than the
+ frame beneath them and the shafts read as grey smoke. Lifted into the
+ ACES shoulder, 100.0% of them lift it. The additive branch keeps
+ exactly 1.0 — there the gain is the brightness and it was tuned against
+ clipping."""
+ out = measure("""
+import { makeGodRays } from './lib/godrays.js';
+const u = (o) => makeGodRays(o).getObjectByName('Shafts').material.uniforms;
+const open = u({ ambient: 0.9, seed: 3 });
+const room = u({ ambient: 0.05, seed: 3 });
+const aces = (x) => (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14);
+const srgb = (x) => (x <= 0.0031308 ? x * 12.92
+ : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
+const shown = (c) => srgb(aces(0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b));
+console.log(JSON.stringify({
+ openVeil: shown(open.uColor.value),
+ openAir: shown(open.uAir.value),
+ roomVeil: shown(room.uColor.value),
+ // The lift is a multiplier on the colour, never on the alpha.
+ gainOpen: open.uGain.value, gainRoom: room.uGain.value,
+}));
+""", _LIBS)
+ # Our sky renders at 0.94; the veil has to land above it, and the air
+ # tint it fades into with it.
+ assert out["openVeil"] > 0.94, out
+ assert out["openAir"] > 0.94, out
+ # ...and stop well short of white, or the shoulder is doing nothing.
+ assert out["openVeil"] < 0.99, out
+ # The additive build is untouched: the warm daylight default is
+ # 0.867 in the linear working space, which lands at 0.892 — further
+ # under the sky still, and right, because there the alpha is what
+ # carries the light.
+ assert abs(out["roomVeil"] - 0.892) < 0.01, out
+ assert abs(out["gainOpen"] - 0.34) < 1e-6, out
+
+
+def test_the_air_tint_is_derived_from_the_light_and_can_be_handed_over():
+ """PORT LAW 4. The far end of a beam, its feathered rim and the margin
+ of its pool are air, not lamp: they need a second, cooler tint. Stating
+ one would put a blue haze under a red sun, so it is the caller's own
+ colour tilted the way scattering tilts it — long wavelengths out, short
+ ones back — renormalised to the same luminance so it is a change of hue
+ and not a second, dimmer lamp."""
+ out = measure("""
+import { makeGodRays } from './lib/godrays.js';
+const u = (o) => makeGodRays(o).getObjectByName('Shafts').material.uniforms;
+const lum = (c) => 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
+const warm = u({ color: 0xffeecb, ambient: 0.0, seed: 3 });
+const red = u({ color: 0xff5522, ambient: 0.0, seed: 3 });
+const told = u({ color: 0xffeecb, hazeColor: 0x224466, ambient: 0.0,
+ seed: 3 });
+const ratio = (v) => ({
+ cooler: (v.uAir.value.b / Math.max(v.uAir.value.r, 1e-4))
+ > (v.uColor.value.b / Math.max(v.uColor.value.r, 1e-4)),
+ keptLum: lum(v.uAir.value) / lum(v.uColor.value),
+});
+console.log(JSON.stringify({
+ warm: ratio(warm), red: ratio(red),
+ // A sun stated red must not hand back a blue that ignores it.
+ redAirWarmerThanWarmAir: red.uAir.value.r / red.uAir.value.b
+ > warm.uAir.value.r / warm.uAir.value.b,
+ told: [told.uAir.value.r, told.uAir.value.g, told.uAir.value.b],
+}));
+""", _LIBS)
+ for k in ("warm", "red"):
+ assert out[k]["cooler"], (k, out)
+ assert abs(out[k]["keptLum"] - 1.0) < 0.02, (k, out)
+ assert out["redAirWarmerThanWarmAir"], out
+ # A scene with its own sky or fog colour to hand overrides all of it.
+ assert out["told"][2] > out["told"][0], out
+
+
+def test_the_pools_and_the_dust_ride_the_frame_and_the_load():
+ """PORT LAW 2. Both are additive marks laid ON a background, and only
+ the shafts were ever taught that. On the eight 2.2 m outdoor rig, the
+ dust arrived as white bokeh in the sky and the pools as blown discs on
+ sunlit dirt: 2.17% of the effect's pixels past 0.97 and a peak lift of
+ +0.33 over the control, against 0.04% and +0.12 once both ride the
+ ambient and the beam load. A dark room keeps its full strength, since
+ that frame has nothing to clip."""
+ out = measure("""
+import { makeGodRays } from './lib/godrays.js';
+const amps = (o) => {
+ const g = makeGodRays(o);
+ return {
+ pool: g.getObjectByName('Pools').material.uniforms.uAmp.value,
+ mote: g.getObjectByName('Motes').material.uniforms.uAmp.value,
+ };
+};
+console.log(JSON.stringify({
+ room: amps({ ambient: 0.05, seed: 3 }),
+ open: amps({ ambient: 0.9, seed: 3 }),
+ nave: amps({ ambient: 0.9, count: 8, width: 2.2, height: 20, seed: 3 }),
+ narrow: amps({ ambient: 0.05, count: 3, width: 0.3, seed: 3 }),
+}));
+""", _LIBS)
+ # An unlit room at the reference load is the configuration everything
+ # here was tuned on: untouched, in both fields.
+ assert out["room"]["pool"] == 1.0 and out["room"]["mote"] == 1.0, out
+ # A bright frame washes a glint out harder than it washes out a pool of
+ # sun on a shaded floor, which is what a daylight scene asks for.
+ assert 0.5 < out["open"]["pool"] < 0.8, out
+ assert out["open"]["mote"] < out["open"]["pool"], out
+ # The rig that blew the frame comes down by roughly another third.
+ assert out["nave"]["pool"] < out["open"]["pool"] * 0.45, out
+ assert out["nave"]["mote"] < out["open"]["mote"] * 0.45, out
+ # Below the reference load nothing is boosted: damping only.
+ assert out["narrow"]["pool"] == 1.0 and out["narrow"]["mote"] == 1.0, out
+
+
+def test_a_mote_is_dust_and_not_a_snowflake():
+ """PORT LAW 3. The sprite half-extent is `aSeed.y`, added straight to
+ the view-space position, so it is a radius in metres: at a tenth of a
+ 0.8 m beam that is a 25 px white disc at close range. Dust in a beam is
+ a glint — a few pixels — so the radius is capped well under a twentieth
+ of the beam, and the draw is biased small so the field is not all one
+ bead size."""
+ out = measure("""
+import { makeGodRays } from './lib/godrays.js';
+const w = 0.8;
+const s = makeGodRays({ count: 6, width: w, height: 8, seed: 4 })
+ .getObjectByName('Motes').geometry.attributes.aSeed.array;
+const r = [];
+for (let i = 0; i < s.length; i += 4) r.push(s[i + 1]);
+r.sort((a, b) => a - b);
+console.log(JSON.stringify({
+ width: w,
+ max: r[r.length - 1], median: r[Math.floor(r.length / 2)],
+ min: r[0], n: r.length,
+}));
+""", _LIBS)
+ # Never more than a twelfth of the beam it rides...
+ assert out["max"] < out["width"] / 12, out
+ # ...biased small, so most of the field is finer still...
+ assert out["median"] < out["max"] * 0.62, out
+ # ...and a real spread rather than one bead size.
+ assert out["max"] > out["min"] * 2.0, out
+
+
+def test_the_default_is_the_mode_that_cannot_wreck_a_frame():
+ """A gorge scene passed `ambient: 0.5` — the honest middle of a
+ documented "0 interior, 1 daylight" range — and got the additive build,
+ which over an open mid-morning frame is the solid white slab this
+ library was already fixed once for. Adding light is the exception a
+ caller asks for by declaring the surroundings dark."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeGodRays } from './lib/godrays.js';
+const mode = (o) => makeGodRays(o).getObjectByName('Shafts')
+ .material.blending === THREE.NormalBlending;
+console.log(JSON.stringify({
+ unspecified: mode({ seed: 1 }),
+ composerMiddle: mode({ ambient: 0.5, seed: 1 }),
+ daylight: mode({ ambient: 1.0, seed: 1 }),
+ unlitInterior: mode({ ambient: 0.0, seed: 1 }),
+ dimRoom: mode({ ambient: 0.2, seed: 1 }),
+}));
+""", _LIBS)
+ assert out["unspecified"], "a library's default must be the safe one"
+ assert out["composerMiddle"], "0.5 is the value a composer actually picks"
+ assert out["daylight"]
+ assert not out["unlitInterior"] and not out["dimRoom"], (
+ "a genuinely dark room still gets added light")
+
+
+def test_a_low_sun_cannot_stretch_a_shaft_into_a_spear():
+ """`height` is the DROP, and length is drop / slant — so at an 18 deg
+ sun a stated 32 m becomes 103 m, which is what shipped: a delivered
+ gorge drew five 100 m bars across the whole frame and the judge called
+ them "disproportionately massive" solid meshes. The drawn length is
+ capped instead; a shaft cut short fades out in the air, and only one
+ that still reaches the floor throws a pool."""
+ out = measure(_RINGS + """
+import { makeGodRays } from './lib/godrays.js';
+// 18 deg elevation: the delivered gorge's own sun.
+const el = 18 * Math.PI / 180;
+const sun = [-Math.cos(el), -Math.sin(el), 0];
+const full = (g) => {
+ const rs = rings(g.getObjectByName('Shafts'));
+ return rs.map((r) => r.run / Math.cos(el));
+};
+const low = makeGodRays({ count: 5, height: 32, width: 0.85,
+ spread: 22, sunDir: sun, seed: 4 });
+const wide = makeGodRays({ count: 5, height: 32, width: 0.85,
+ spread: 22, sunDir: sun, seed: 4,
+ maxLength: 200 });
+const steep = makeGodRays({ count: 5, height: 32, width: 0.85,
+ spread: 22, sunDir: [0, -1, -0.2], seed: 4 });
+console.log(JSON.stringify({
+ capped: Math.max(...full(low)),
+ uncapped: Math.max(...full(wide)),
+ steep: Math.max(...full(steep)),
+ cappedNames: low.children.map((c) => c.name).sort(),
+ steepNames: steep.children.map((c) => c.name).sort(),
+}));
+""", _LIBS)
+ # 32 / sin(18 deg) = 103 m if nothing caps it; the cap is 1.6x.
+ assert out["uncapped"] > 95, out
+ assert out["capped"] <= 32 * 1.6 + 1.0, out
+ # A shaft that no longer reaches the floor throws no pool...
+ assert out["cappedNames"] == ["Motes", "Shafts"], out
+ # ...while a steep sun still lands, and keeps its pool.
+ assert out["steep"] < 32 * 1.6, out
+ assert out["steepNames"] == ["Motes", "Pools", "Shafts"], out
+
+
+def test_a_wide_nave_of_shafts_does_not_add_enough_light_to_clip():
+ """Added light STACKS, and the additive gain was tuned on the default
+ seven 0.55 m shafts. A cathedral asking for eight 2.2 m ones puts about
+ five times the beam through the same air: measured in a dark interior,
+ 1.9% of the frame blew pure white and the judge called them "physical
+ beams" rather than light — at the normalised gain the same view clips
+ 0.0%. The default must be untouched: it is the configuration the gain
+ was measured on."""
+ out = measure("""
+import { makeGodRays } from './lib/godrays.js';
+const gainOf = (o) => makeGodRays(o).getObjectByName('Shafts')
+ .material.uniforms.uGain.value;
+console.log(JSON.stringify({
+ base: gainOf({ ambient: 0.18, seed: 3 }),
+ nave: gainOf({ ambient: 0.18, count: 8, width: 2.2, height: 20,
+ seed: 3 }),
+ narrow: gainOf({ ambient: 0.18, count: 3, width: 0.3, seed: 3 }),
+ scatter: gainOf({ ambient: 0.9, count: 8, width: 2.2, seed: 3 }),
+ // The reference rig itself is unchanged in either mode.
+ scatterRef: gainOf({ ambient: 0.9, count: 7, width: 0.55, seed: 3 }),
+}));
+""", _LIBS)
+ # The default configuration keeps the gain it was tuned at.
+ assert abs(out["base"] - 0.62 * (1 - 0.5 * 0.18)) < 1e-6, out
+ # Five times the beam load comes down to roughly a third.
+ assert out["nave"] < out["base"] * 0.4, out
+ # Below the default load nothing is boosted: damping only.
+ assert abs(out["narrow"] - out["base"]) < 1e-6, out
+ # Scattering was a FLAT 0.34, so no outdoor configuration was ever
+ # damped: a delivered lane asked for four 35 m shafts and got solid
+ # white wedges across the frame.
+ assert out["scatter"] < 0.34 * 0.6, out
+ assert abs(out["scatterRef"] - 0.34) < 1e-6, out
diff --git a/harness/tests/scene_runtime/lib/test_grass.py b/harness/tests/scene_runtime/lib/test_grass.py
new file mode 100644
index 00000000..d10f7768
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_grass.py
@@ -0,0 +1,504 @@
+"""grass.js — the field that has to read as a field, close up and from above.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_grass_lib.py). Its properties are kept whole: the whole field is
+ONE instanced draw call with ``position`` pinned at the origin, the clump field
+decides where grass grows and how tall, the mat under the blades carries that
+same field, both stand on the caller's ground, a seed is a promise, one
+``tick`` drives both materials, and blade shadows stay opt-in.
+
+Their compile case is restored at the end of this file — ``_probe.compile_scene``
+stages the fixture as a workspace ``src/scene.js``, the shape
+``runtime_js/check_shaders.mjs`` boots (16 programs, 4 custom materials). What is
+asserted before it is the STRUCTURE of the GLSL, read back off ``onBeforeCompile``,
+and the frames are at fx/out/grass/ (day and night).
+
+The last four tests are new, and each pins a change the port made. The first
+of them is a real bug: the blade's shading normal was built as
+``cross(grTan, grSide)``, which is the BACK face of the strip the vertex shader
+sweeps, and DOUBLE_SIDED cannot rescue that — three multiplies ``vNormal`` by
+``gl_FrontFacing``, which is decided by the same winding the normal was built
+from, so the two flip together and the product is invariant. Every blade shaded
+by its far side. Backlit that reads as soft; front-lit it is a black field, and
+on our night rig the whole meadow came back at luminance 0.009 next to a lit
+rock and lit ground. The other three pin the grading: MeshPhysicalMaterial for
+one uniform (``specularIntensity`` — a Standard dielectric's F90 is pinned at
+1.0 and a field seen edge-on from a low camera reflected the sky at full
+strength over every pixel), the backlight term that reads the scene's own key
+light rather than a hardcoded sun, and the one metre-scale colour field that
+blades and mat now share.
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "noise.js", "grass.js")
+
+# Run a material's patch chain the way three does, and hand back the GLSL.
+_COMPILE = """
+const compile = (mat) => {
+ const shader = {
+ uniforms: {},
+ vertexShader: '#include <begin_vertex>\\n',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}\\n',
+ };
+ mat.onBeforeCompile(shader, {});
+ return shader;
+};
+"""
+
+
+def test_the_whole_field_of_blades_is_one_draw_call():
+ """Thousands of blades are affordable only as ONE instanced mesh;
+ a per-tuft mesh would spend the scene's draw budget on grass."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+const g = makeGrass({ extent: 4, density: 600, seed: 3 });
+const meshes = [];
+g.traverse((o) => { if (o.isMesh) meshes.push(o); });
+const blades = g.getObjectByName('Blades');
+console.log(JSON.stringify({
+ names: g.children.map((c) => c.name),
+ meshes: meshes.length,
+ instanced: !!blades.geometry.isInstancedBufferGeometry,
+ count: blades.geometry.instanceCount,
+ perBlade: blades.geometry.index.count / 3,
+ attrs: Object.keys(blades.geometry.attributes).sort(),
+ culled: blades.frustumCulled,
+ box: [blades.geometry.boundingBox.min.toArray(),
+ blades.geometry.boundingBox.max.toArray()],
+ hasTick: typeof g.userData.tick === 'function',
+}));
+""", _LIBS)
+ assert out["names"] == ["Blades", "Sward"]
+ # One mesh for every blade plus the mat under them, and nothing else.
+ assert out["meshes"] == 2, out
+ assert out["instanced"] and out["count"] > 3000, out
+ assert out["perBlade"] == 8, out
+ assert out["attrs"] == ["aCorner", "iPos", "iShape", "iVar", "normal",
+ "position", "uv"]
+ # position is zero, so a derived bound would be a point at the
+ # origin and the field would vanish the moment it left the centre.
+ assert out["culled"] is False
+ assert out["box"][0][0] == -2 and out["box"][1][2] == 2, out
+ assert out["box"][1][1] > 0.3, out
+ assert out["hasTick"]
+
+
+def test_the_blades_keep_position_at_the_origin():
+ """Any pass that redraws with an override material ignores this vertex
+ shader, so a real blade left in `position` would stack every copy at the
+ world origin and burn a slab there."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+const b = makeGrass({ extent: 3, density: 400 }).getObjectByName('Blades');
+const g = b.geometry;
+console.log(JSON.stringify({
+ posAllZero: Array.from(g.attributes.position.array).every((v) => v === 0),
+ corners: g.attributes.aCorner.count,
+ perInstance: [g.attributes.iPos.count, g.attributes.iShape.count,
+ g.attributes.iVar.count],
+ instances: g.instanceCount,
+}));
+""", _LIBS)
+ assert out["posAllZero"], out
+ # A 1x4 strip: two corners per row, five rows.
+ assert out["corners"] == 10
+ assert out["perInstance"] == [out["instances"]] * 3
+
+
+def test_clumps_decide_where_grass_grows_and_how_tall():
+ """A field of identical blades is a carpet. Grass grows in tussocks:
+ taller and greener inside one, sparser and dryer between them.
+ `patchy` moves blades OUT of the open ground and into the clumps
+ without changing how much grass there is — that is `density`'s job,
+ and it stays true to its name at any patchiness."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+function field(patchy) {
+ const b = makeGrass({ extent: 8, density: 500, seed: 4, patchy })
+ .getObjectByName('Blades');
+ const n = b.geometry.instanceCount;
+ const shape = b.geometry.attributes.iShape.array;
+ const vary = b.geometry.attributes.iVar.array;
+ const rows = [];
+ for (let i = 0; i < n; i++) rows.push([vary[i * 4 + 2], shape[i * 4]]);
+ rows.sort((a, b2) => a[0] - b2[0]);
+ const mean = (from, to) => {
+ let s = 0;
+ for (let i = from; i < to; i++) s += rows[i][1];
+ return s / (to - from);
+ };
+ const third = Math.floor(n / 3);
+ return {
+ perM2: n / 64,
+ onBareGround: rows.filter((r) => r[0] > 0.6).length / n,
+ greenestH: mean(0, third),
+ driestH: mean(n - third, n),
+ };
+}
+const open = field(0.05), bare = field(0.85);
+console.log(JSON.stringify({ open, bare }));
+""", _LIBS)
+ open_, bare = out["open"], out["bare"]
+ # Sparser between the clumps: patchiness thins the open ground, and
+ # the blades it takes from there stand in the tussocks instead.
+ assert bare["onBareGround"] < open_["onBareGround"] * 0.6, out
+ for f in (open_, bare):
+ assert 400 < f["perM2"] < 520, out
+ # Taller in the clumps, in both fields.
+ assert f["greenestH"] > f["driestH"] * 1.3, out
+
+
+def test_the_mat_carries_the_same_clump_field_as_the_blades():
+ """From above, blades show only their tips: what makes the field
+ read as continuous rather than as a scatter of dots is the mat under
+ them, which has to be green exactly where the blades are dense."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+const g = makeGrass({ extent: 8, density: 400, seed: 4 });
+const sward = g.getObjectByName('Sward');
+const clump = sward.geometry.attributes.aClump;
+const pos = sward.geometry.attributes.position;
+const blades = g.getObjectByName('Blades');
+const iPos = blades.geometry.attributes.iPos.array;
+const iVar = blades.geometry.attributes.iVar.array;
+// Green mat under green blades: bin the mat by its own clump value and
+// ask what the blades standing in each bin look like.
+let lowSum = 0, lowN = 0, highSum = 0, highN = 0;
+for (let i = 0; i < blades.geometry.instanceCount; i++) {
+ const x = iPos[i * 3], z = iPos[i * 3 + 2];
+ let best = 0, bestD = 1e9;
+ for (let v = 0; v < pos.count; v++) {
+ const d = (pos.getX(v) - x) ** 2 + (pos.getZ(v) - z) ** 2;
+ if (d < bestD) { bestD = d; best = clump.array[v]; }
+ }
+ if (best < 0.35) { lowSum += iVar[i * 4 + 2]; lowN++; }
+ if (best > 0.65) { highSum += iVar[i * 4 + 2]; highN++; }
+}
+console.log(JSON.stringify({
+ verts: pos.count,
+ clumpMin: Math.min(...clump.array),
+ clumpMax: Math.max(...clump.array),
+ dryOnBareMat: lowSum / Math.max(lowN, 1),
+ dryOnGreenMat: highSum / Math.max(highN, 1),
+ binned: [lowN, highN],
+}));
+""", _LIBS)
+ assert out["verts"] > 200, out
+ # The field is calibrated on the patch it covers, so a patch always
+ # gets the whole range instead of one flat mid-grey wash.
+ assert out["clumpMin"] < 0.15 and out["clumpMax"] > 0.85, out
+ assert min(out["binned"]) > 20, out
+ # Blades standing on green mat are the green ones.
+ assert out["dryOnGreenMat"] < out["dryOnBareMat"] - 0.25, out
+
+
+def test_blades_and_mat_stand_on_the_callers_ground():
+ """Grass that ignores `heightAt` floats over a slope or buries
+ itself in it — the one defect a still frame shows immediately."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+const h = (x, z) => 0.8 * Math.sin(x * 0.3) * Math.cos(z * 0.21) + 0.9;
+const g = makeGrass({ extent: 10, density: 300, seed: 8, heightAt: h });
+const iPos = g.getObjectByName('Blades').geometry.attributes.iPos.array;
+let bladeErr = 0;
+for (let i = 0; i < iPos.length; i += 3) {
+ bladeErr = Math.max(bladeErr,
+ Math.abs(iPos[i + 1] - h(iPos[i], iPos[i + 2])));
+}
+const p = g.getObjectByName('Sward').geometry.attributes.position;
+let matErr = 0, lift = 0;
+for (let v = 0; v < p.count; v++) {
+ const d = p.getY(v) - h(p.getX(v), p.getZ(v));
+ matErr = Math.max(matErr, Math.abs(d - 0.012));
+ lift = Math.max(lift, d);
+}
+const flat = makeGrass({ extent: 6, density: 300, seed: 8 });
+const fPos = flat.getObjectByName('Blades').geometry.attributes.iPos.array;
+let flatMax = 0;
+for (let i = 1; i < fPos.length; i += 3) flatMax = Math.max(flatMax, fPos[i]);
+console.log(JSON.stringify({
+ bladeErr, matErr, lift, flatMax,
+ boxLow: g.getObjectByName('Blades').geometry.boundingBox.min.y,
+}));
+""", _LIBS)
+ assert out["bladeErr"] < 1e-4, out
+ assert out["matErr"] < 1e-4, out
+ # Just clear of the ground: level with it the mat z-fights, higher
+ # and the blades look planted in a tray.
+ assert 0.005 < out["lift"] < 0.05, out
+ # No heightAt: the field rests exactly on y = 0.
+ assert out["flatMax"] == 0, out
+ assert out["boxLow"] <= 0.11, out
+
+
+def test_two_fields_with_one_seed_are_identical():
+ """Determinism is the contract for every shipped factory: a re-run
+ that reshuffles the blades is a re-run nobody can compare against."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+const fieldOf = (s) => Array.from(
+ makeGrass({ extent: 5, density: 400, seed: s })
+ .getObjectByName('Blades').geometry.attributes.iShape.array);
+const a = fieldOf(6), b = fieldOf(6), c = fieldOf(7);
+console.log(JSON.stringify({
+ same: JSON.stringify(a) === JSON.stringify(b),
+ differs: JSON.stringify(a) !== JSON.stringify(c),
+ n: a.length,
+}));
+""", _LIBS)
+ assert out["same"] and out["differs"] and out["n"] > 0
+
+
+def test_tick_advances_every_material_in_the_group():
+ """The bend lives entirely in the vertex shader, so an un-advanced
+ uTime is a field frozen mid-gust, not a field at rest."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+const g = makeGrass({ extent: 4, density: 200 });
+const times = () => {
+ const out = [];
+ g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ const u = m && m.userData && m.userData.uniforms;
+ if (u && u.uTime) out.push(u.uTime.value);
+ }
+ });
+ return out;
+};
+const before = times();
+g.userData.tick(2.5);
+console.log(JSON.stringify({ before, after: times() }));
+""", _LIBS)
+ assert out["before"] == [0, 0]
+ assert out["after"] == [2.5, 2.5]
+
+
+def test_blade_shadows_are_opt_in_and_displaced_when_on():
+ """Wheat set the precedent: tens of thousands of instances in the
+ shadow map are a real SwiftShader cost, so blades cast only when
+ asked. Off, the mesh stays OUT of the map (its depth pass would draw
+ the zero-position quads); on, it casts through a depth material
+ carrying the blade displacement on the surface's own uniform map —
+ anything else is no shadow, or one frozen at t = 0."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+const pick = (g) => {
+ let m;
+ g.traverse((o) => { if (o.name === 'Blades') m = o; });
+ return m;
+};
+const off = pick(makeGrass({ extent: 6, density: 40, seed: 3 }));
+const on = pick(makeGrass({ extent: 6, density: 40, seed: 3,
+ shadows: true }));
+console.log(JSON.stringify({
+ offCasts: off.castShadow, offDepth: !!off.customDepthMaterial,
+ onCasts: on.castShadow,
+ onShared: !!on.customDepthMaterial
+ && on.customDepthMaterial.userData.uniforms
+ === on.material.userData.uniforms,
+}));
+""", _LIBS)
+ assert not out["offCasts"] and not out["offDepth"], out
+ assert out["onCasts"] and out["onShared"], out
+
+
+# --- what the port changed -------------------------------------------------
+
+def test_the_shading_normal_is_wound_the_way_the_strip_is():
+ """THE bug this port fixed. The sweep sends the plane's x to `grSide`
+ and its y to `grTan`, so the face three rasterises has the normal
+ `cross(grSide, grTan)`; the reference wrote `cross(grTan, grSide)`, the
+ other one. DOUBLE_SIDED cannot rescue it — three multiplies vNormal by
+ gl_FrontFacing, and gl_FrontFacing is decided by the same winding the
+ normal was built from, so both flip together and the product is
+ invariant. Every blade shaded by its far face: soft when backlit, and
+ a BLACK field under any key light on the camera's side (measured on our
+ night rig, the whole meadow at luminance 0.009 beside a lit rock and lit
+ ground; 0.049 once wound right, and the frame's dark fraction 0.42 ->
+ 0.19). The cup term flips with it or the channel is inside out."""
+ out = measure(_COMPILE + """
+import { makeGrass } from './lib/grass.js';
+const vs = compile(makeGrass({ extent: 4, density: 100 })
+ .getObjectByName('Blades').material).vertexShader;
+console.log(JSON.stringify({
+ right: vs.includes('cross(grSide, grTan) - grSide * aCorner.x'),
+ wrong: vs.includes('cross(grTan, grSide)'),
+ guarded: vs.includes('#ifndef FLAT_SHADED'),
+}));
+""", _LIBS)
+ assert out["right"], out
+ assert not out["wrong"], out
+ # The depth pass defines FLAT_SHADED, and a depth shader has no vNormal.
+ assert out["guarded"], out
+
+
+def test_the_blade_material_turns_down_the_sky_it_cannot_see():
+ """Measured on our renderer with the blade albedo forced to BLACK and the
+ environment off, the field still came back at luminance 0.36, saturation
+ 0.07 — a flat neutral sheen that was 70% of every pixel, which is why no
+ albedo could make this grass read as green. A Standard dielectric's F90
+ is pinned at 1.0, so a field seen nearly edge-on from a low camera
+ reflects the sky at full strength everywhere; `specularIntensity` (a
+ Physical uniform, scaling F0 AND F90) is the only knob that turns it
+ down, and a blade of grass is a waxy leaf, not polished glass. The env
+ cut alongside it is the AO this host has no pass for — a blade standing
+ in a sward sees a slot of sky, not a dome."""
+ out = measure("""
+import { makeGrass } from './lib/grass.js';
+const g = makeGrass({ extent: 4, density: 100 });
+const b = g.getObjectByName('Blades').material;
+const s = g.getObjectByName('Sward').material;
+console.log(JSON.stringify({
+ type: b.type, specular: b.specularIntensity, blade: b.envMapIntensity,
+ sward: s.envMapIntensity, doubleSided: b.side === 2,
+ rough: [b.roughness, s.roughness], metal: [b.metalness, s.metalness],
+}));
+""", _LIBS)
+ assert out["type"] == "MeshPhysicalMaterial", out
+ assert 0.1 <= out["specular"] <= 0.45, out
+ # Both cut, and the mat — the bottom of the sward — further than the
+ # blades standing in it, whose one uniform is weighted to their tips.
+ assert 0.2 <= out["sward"] < out["blade"] < 1.0, out
+ assert out["doubleSided"] and out["metal"] == [0, 0], out
+ assert min(out["rough"]) > 0.6, out
+
+
+def test_the_backlight_reads_the_scenes_own_key_light():
+ """A blade is a fraction of a millimetre of sap, and with the shading
+ normal finally facing the eye a BACKLIT blade's diffuse response is
+ nearly nothing — which is what backlit means. The glow through it is
+ therefore not a garnish, it is the light on the field, and it goes in as
+ emitted radiance because albedo cannot add light to a face the sun is
+ behind. Direction AND colour come off `directionalLights[0]` in view
+ space, so it can never disagree with the sun and a night rig's moon
+ drives it too; the two gates keep it off a front-lit field, and the
+ depth weight keeps it out of the roots (a field that glows to its roots
+ is fog)."""
+ out = measure(_COMPILE + """
+import { makeGrass } from './lib/grass.js';
+const fs = compile(makeGrass({ extent: 4, density: 100 })
+ .getObjectByName('Blades').material).fragmentShader;
+const emit = fs.split('totalEmissiveRadiance +=')[1] || '';
+console.log(JSON.stringify({
+ emits: fs.includes('totalEmissiveRadiance +='),
+ guarded: fs.includes('#if NUM_DIR_LIGHTS > 0'),
+ readsColor: emit.includes('directionalLights[0].color'),
+ readsDir: fs.includes('grL = directionalLights[0].direction'),
+ gates: emit.includes('grThru') && emit.includes('grBeam'),
+ depthWeighted: emit.includes('grDepth * grDepth'),
+ hardcoded: /vec3\\s*\\(\\s*1\\.0\\s*,\\s*0\\.9/.test(emit),
+}));
+""", _LIBS)
+ assert out["emits"] and out["guarded"], out
+ assert out["readsColor"] and out["readsDir"], out
+ assert out["gates"] and out["depthWeighted"], out
+ assert not out["hardcoded"], out
+
+
+def test_the_blades_and_the_mat_break_colour_on_one_field():
+ """A blade is a couple of pixels wide and its own hue jitter averages
+ straight back out — measured, quadrupling the per-blade swing moved the
+ frame by under two degrees. What survives is the METRE: warm where the
+ sun lands, cool where only the sky reaches, and bands of straw that have
+ nothing to do with how dense the grass is. Both shaders have to read
+ that field at the same scale, off the same world XZ, or the mat lays one
+ meadow's colour over another's — the blades sample it at their ROOT, not
+ at the bending spine, so the wind cannot slide the colour about."""
+ out = measure(_COMPILE + """
+import { makeGrass } from './lib/grass.js';
+const g = makeGrass({ extent: 4, density: 100 });
+const blade = compile(g.getObjectByName('Blades').material);
+const sward = compile(g.getObjectByName('Sward').material);
+const HUE = 'astraHueBreak(', DRY = 'astraFbm2(';
+console.log(JSON.stringify({
+ bladeHue: blade.fragmentShader.includes(
+ 'astraHueBreak(grC, vGrassW, 0.55, 0.62)'),
+ swardHue: sward.fragmentShader.includes(
+ 'astraHueBreak(swCol, vSward.xy, 0.55, 0.62)'),
+ bladeDry: blade.vertexShader.includes('astraFbm2(vGrassW * 0.35 + 5.0, 2)'),
+ swardDry: sward.fragmentShader.includes(
+ 'astraFbm2(vSward.xy * 0.35 + 5.0, 2)'),
+ rootNotSpine: blade.vertexShader.includes(
+ 'vGrassW = (modelMatrix * vec4(grBase, 1.0)).xz'),
+}));
+""", _LIBS)
+ assert out["bladeHue"] and out["swardHue"], out
+ assert out["bladeDry"] and out["swardDry"], out
+ assert out["rootNotSpine"], out
+
+
+def test_one_wind_is_read_in_either_spelling():
+ """`windOf` is exported so a scene's meadow, reeds and trees can take the
+ SAME wind; a library that re-implements this reader is a library that
+ will drift away from it. Both spellings, a Vector2 or a pair, and a
+ degenerate direction that must not produce NaN."""
+ out = measure("""
+import * as THREE from 'three';
+import { windOf } from './lib/grass.js';
+const r = (w) => { const o = windOf(w);
+ return [+o.dir.x.toFixed(4), +o.dir.y.toFixed(4), o.amp, o.speed]; };
+console.log(JSON.stringify({
+ bare: r(2),
+ none: r(undefined),
+ arr: r({ dir: [0, 3], strength: 1, speed: 2 }),
+ vec: r({ dir: new THREE.Vector2(0, 3), strength: 1, speed: 2 }),
+ zero: r({ dir: [0, 0] }),
+}));
+""", _LIBS)
+ # A bare number is a strength multiplier on the default breeze.
+ assert out["bare"] == [pytest.approx(0.9113, abs=1e-3),
+ pytest.approx(0.4101, abs=1e-3), 1.0, 1]
+ assert out["none"][2] == 0.5 and out["none"][3] == 1
+ # [x, z] and Vector2 are the same direction, normalised.
+ assert out["arr"] == out["vec"] == [0, 1, 0.5, 2]
+ # A zero direction falls back to +X instead of NaN.
+ assert out["zero"][:2] == [1, 0]
+
+# A FOGGED, shadow-casting scene: `USE_FOG` and the shadow branches only exist
+# in a program built from one, and a patch that drops a chunk compiles fine in
+# an unfogged fixture and renders as a sticker in a real scene.
+_COMPILE_SCENE = """
+import * as THREE from 'three';
+import { tickShaders } from './lib/shader.js';
+import { makeGrass } from './lib/grass.js';
+
+export const BOUNDS = { min: [-30, 0, -30], max: [30, 20, 30] };
+export function heightAt(x, z) { return Math.sin(x * 0.1) * 0.3; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.004);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 1.0));
+ const sun = new THREE.DirectionalLight(0xffffff, 3);
+ sun.position.set(10, 20, 10); sun.castShadow = true; scene.add(sun);
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(80, 80),
+ new THREE.MeshStandardMaterial({ color: 0x6d6a52 }));
+ ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground);
+ const g = makeGrass({ extent: 20, density: 120, heightAt, shadows: true });
+ scene.add(g);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [12, 5, 14], lookAt: [0, 2, 0], fov: 45 }],
+ update(t) { tickShaders(scene, t); },
+ };
+}
+"""
+
+
+def test_every_program_compiles_on_the_gpu():
+ """Two materials (blade and, behind `shadows: true`, the custom depth material
+ that makes the blades cast what they actually are) plus a vertex texture fetch
+ for the gust field. Only the GPU can say the GLSL is legal.
+
+ The reference had this case and the port dropped it: `_probe.shader_check`
+ staged only `src/fixture.js` while `check_shaders.mjs` boots the workspace's
+ `src/scene.js`, so it could never run. `_probe.compile_scene` stages the
+ scene, so the case is back (consolidation, 2026-09-01)."""
+ code, out = compile_scene(_COMPILE_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out
diff --git a/harness/tests/scene_runtime/lib/test_indoor.py b/harness/tests/scene_runtime/lib/test_indoor.py
new file mode 100644
index 00000000..36d4c1c5
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_indoor.py
@@ -0,0 +1,798 @@
+"""An interior that is LIT, the surfaces hands have been on, and a crowd.
+
+Ported from the reference suite 2026-09-01. `indoor.js` answers three
+failures. A room filled with ambient reads as a MODEL of a room: nothing
+bleeds, so a white ceiling beside a red wall stays white and the eye is
+told there is no light in here, only exposure. A pane nobody has touched
+says the same about the props. A square with nobody in it is a set.
+
+Each export loses its whole point if one property goes. The bounce must
+fall to EXACTLY zero at its reach — a wash that never ends is ambient
+again, the thing it replaces — and it must be LIGHT, because an albedo
+lift is capped at what already lands on the surface and the shaded soffit
+that needs it most would take none. The smudge must move GLOSS and not
+colour, or it is a stain. The crowd must stay one draw call, seated on
+the ground, and out of the override passes that draw a transparent card
+as a solid wall.
+
+THE PORT'S OWN LAWS, each measured on our host (fx/out/indoor/, exposure
+1.0, no post chain) against a control render of the same frame with the
+patches off:
+
+1. A PLANE'S FORM FACTOR IS THE UN-SQUARED HALF-LAMBERT. Squaring it is
+ exact for neither limit of a Lambertian half-space: a ceiling facing a
+ lit floor sees it over its whole hemisphere (factor 1, which squaring
+ also gives) and a WALL over exactly half of it (factor 0.5, where
+ squaring gives 0.25). The wall above a floor is the geometry every
+ room has, and it was getting half its bleed. Measured on the white
+ plaster of the showcase loggia, mean absolute difference against the
+ unpatched control: skirting 3.22 -> 5.74 (close) and 3.87 -> 6.91
+ (mid) of 255, red-rug bleed 4.34 -> 7.55, and the SOFFIT — the
+ parallel case, already correct — 1.86 -> 2.14, unchanged as the
+ theory says it must be.
+
+2. A WASH THAT KEEPS ITS HUE TO THE LAST CENTIMETRE IS A LAMP. Light
+ that has travelled further has bounced off more than one thing, so the
+ tint desaturates across the reach (32% at the far edge).
+
+3. BOUNCE IS THE SMOOTHEST GRADIENT IN A ROOM. On the widest flat it
+ lands on it climbs the 8-bit ladder in bands; half a code of hashed
+ dither, only where there is bleed, took the gradient strip from 136 to
+ 156 distinct colours (row-to-row noise 0.452 -> 0.566).
+
+4. GREASE IS A FILM WITH RIDGES, NOT A SET OF STRIPES. With the arcs
+ alone a touched pane is a few bright bands on clean glass and the eye
+ reads bands as paint. The film term took the smudge on the showcase's
+ polished counter from 0.91 to 3.01 mean absolute difference and from
+ 23% to 55% of the surface changed by more than 1/255.
+
+5. A BACKLIT CARD IS A SILHOUETTE WITH A LIT EDGE. A crowd with the sun
+ behind it had a hard `max(dot, 0)` terminator on a coarse bowed
+ normal, so every figure printed as one flat ambient tone. Wrapped
+ diffuse plus a rim on the sun-side edge: the darkest crowd pixels rose
+ from 15.9 to 24.7 of 255, distinct colours over the crowd from 4337 to
+ 4726. Plus per-person VALUE (a street is pale coats and dark ones,
+ not one value in two hues) and a `legColor` default off the floor —
+ an albedo under about 0.02 linear is a hole no light reopens.
+"""
+
+from __future__ import annotations
+
+import re
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure
+
+_LIBS = ("shader.js", "noise.js", "indoor.js", "surface_wear.js")
+_SRC = LIB_DIR / "indoor.js"
+
+# One material carrying BOTH patches under two more from another library —
+# the GLSL namespace collision that only shows up when three libraries share
+# one material — plus an InstancedMesh (whose world position needs
+# instanceMatrix folded in by hand) and the crowd field.
+_BODY = """
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0xd8d2c6, roughness: 0.45, metalness: 0.1 });
+ patchMicroBreakup(mat, { scale: 0.6, strength: 0.12, seed: 5 });
+ patchEdgeWear(mat, { strength: 0.4, seed: 6 });
+ patchBounceLight(mat, {
+ sources: [{ position: [-3, 1.4, 0], normal: [1, 0, 0],
+ color: 0xa8201a, reach: 3.5 },
+ { position: [0, 0, 0], normal: [0, 1, 0],
+ color: 0x3f7a2a, reach: 2.2 },
+ { position: [2, 0.8, 1], color: 0xffcc88, reach: 1.5 }],
+ up: [0, 1, 0], strength: 1.2 });
+ patchFingerprints(mat, { amount: 0.6, smear: 0.4, seed: 3 });
+ const wall = new THREE.Mesh(new THREE.BoxGeometry(6, 3, 0.3), mat);
+ wall.position.set(0, 1.5, -2);
+ HOST.add(wall);
+ const posts = new THREE.InstancedMesh(
+ new THREE.BoxGeometry(0.12, 1.1, 0.12), mat, 8);
+ const m4 = new THREE.Matrix4();
+ for (let i = 0; i < 8; i++) {
+ m4.makeTranslation(-3 + i * 0.9, 0.55, 0.6);
+ posts.setMatrixAt(i, m4);
+ }
+ posts.instanceMatrix.needsUpdate = true;
+ HOST.add(posts);
+ HOST.add(makeCrowdImposters({
+ count: 40, extent: 20, heightAt: (x, z) => 0.05 * Math.sin(x * 0.3),
+ seed: 5 }));
+"""
+
+# A SCENE, not an asset: the reference's asset mode built its own unfogged,
+# point-light-free scene, so USE_FOG was never defined and NUM_POINT_LIGHTS
+# was zero — two whole branches of this library never reached a compiler.
+# A room is exactly where both exist. Ours boots a scene either way, so the
+# two reference compile tests are one test here.
+_SCENE = """
+import * as THREE from 'three';
+import { makeCrowdImposters, patchBounceLight, patchFingerprints }
+ from './lib/indoor.js';
+import { patchEdgeWear, patchMicroBreakup } from './lib/surface_wear.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 20, 20] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xb9c6d4, 0.012);
+ scene.add(new THREE.HemisphereLight(0xc8d6e6, 0x8a8478, 1.0));
+ const sun = new THREE.DirectionalLight(0xfff1da, 2.4);
+ sun.position.set(14, 9, 5);
+ scene.add(sun);
+ const lamp = new THREE.PointLight(0xfff4e2, 30, 0, 2);
+ lamp.position.set(1.2, 2.4, 2.0);
+ scene.add(lamp);
+""" + _BODY.replace("HOST", "scene") + """
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [8, 4, 10], lookAt: [0, 1.5, 0],
+ fov: 45 }],
+ update() {},
+ };
+}
+"""
+
+# Pull a scalar GLSL helper out of the SHIPPED source and run it as JS. The
+# two dialects agree on everything here except the declarations, so the
+# numbers below are the numbers the GPU computes — not a second
+# implementation that could drift from the one that renders.
+_GLSL_AS_JS = """
+const glslFn = (src, name, args) => {
+ const re = new RegExp('float ' + name + '\\\\(([\\\\s\\\\S]*?)\\\\)\\\\s*\\\\{');
+ const m = re.exec(src);
+ if (!m) throw new Error('no ' + name + '() in the shipped source');
+ let depth = 0, end = -1;
+ for (let i = src.indexOf('{', m.index); i < src.length; i++) {
+ if (src[i] === '{') depth++;
+ else if (src[i] === '}' && --depth === 0) { end = i; break; }
+ }
+ const body = src.slice(src.indexOf('{', m.index) + 1, end)
+ .replace(/\\bfloat\\b/g, 'let');
+ const fn = new Function(...args, 'clamp', 'max', 'min', 'fract',
+ 'step', 'mix', 'pow', 'exp', 'sin', 'floor',
+ body);
+ return (...v) => fn(...v,
+ (x, a, b) => Math.min(Math.max(x, a), b), Math.max, Math.min,
+ (x) => x - Math.floor(x),
+ (e, x) => (x < e ? 0 : 1),
+ (a, b, t) => a + (b - a) * t,
+ Math.pow, Math.exp, Math.sin, Math.floor);
+};
+"""
+
+# The same trick for the ONE helper here that takes vectors: astraFresnel is
+# shader.js's, shared by every grazing-angle effect in the library, so the
+# smudge's angle response is read out of the shipped GLSL_UTIL.
+_FRESNEL_AS_JS = """
+const fresnelOf = (src) => {
+ const i = src.indexOf('float astraFresnel(');
+ if (i < 0) throw new Error('no astraFresnel() in GLSL_UTIL');
+ const open = src.indexOf('{', i);
+ let depth = 0, end = -1;
+ for (let k = open; k < src.length; k++) {
+ if (src[k] === '{') depth++;
+ else if (src[k] === '}' && --depth === 0) { end = k; break; }
+ }
+ const fn = new Function('n', 'v', 'power', 'pow', 'clamp', 'dot',
+ 'normalize', src.slice(open + 1, end));
+ const dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+ const norm3 = (a) => {
+ const l = Math.hypot(a[0], a[1], a[2]);
+ return [a[0] / l, a[1] / l, a[2] / l];
+ };
+ return (n, v, p) => fn(n, v, p, Math.pow,
+ (x, a, b) => Math.min(Math.max(x, a), b), dot3, norm3);
+};
+"""
+
+
+def test_all_three_compile_in_a_room_with_fog_and_a_point_light():
+ """Both patches chained under two from another library, on one
+ material, plus an InstancedMesh and the crowd field — in a FOGGED
+ scene with a point light, because the smudge sums point lights and
+ every custom shader here has a fog branch. `patchStandard` THROWS on
+ two patches defining one function name, which only the GPU, or this,
+ can settle."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ # A WARN here is the fog trap or the GTAO trap, either of which ships
+ # an effect that looks wrong rather than one that errors.
+ assert "WARN" not in out, out
+ assert "no fog chunks" not in out, out
+
+
+def test_the_bounce_falls_off_and_is_zero_beyond_its_reach():
+ """Read straight out of the GLSL the patch ships. A bare inverse
+ square never reaches zero, so every surface in the scene would keep a
+ wash of every bouncer in it — ambient light again, the one thing
+ colour bleed exists to replace. A plane must also lose its light more
+ slowly than a point, or a wall bleeds like a bulb."""
+ out = measure(_GLSL_AS_JS + """
+import * as THREE from 'three';
+import { patchBounceLight } from './lib/indoor.js';
+
+const m = new THREE.MeshStandardMaterial({ color: 0x888888 });
+patchBounceLight(m, { sources: [[0, 0, 0]], strength: 1 });
+const patch = m.userData.astraPatches.find(
+ (p) => p.name === 'indoor:bounce');
+const fall = glslFn(patch.fragmentHead, 'astraBncFall',
+ ['d', 'r', 'plane']);
+const curve = (plane) => {
+ const out = [];
+ for (let i = 0; i <= 40; i++) out.push(fall(i * 0.1, 3, plane));
+ return out;
+};
+console.log(JSON.stringify({
+ point: curve(0), plane: curve(1),
+ at0: [fall(0, 3, 0), fall(0, 3, 1)],
+ atR: [fall(3, 3, 0), fall(3, 3, 1)],
+ beyond: [fall(3.5, 3, 0), fall(9, 3, 1), fall(400, 3, 0)],
+ half: [fall(1.5, 3, 0), fall(1.5, 3, 1)],
+}));
+""", _LIBS)
+ assert out["at0"] == [1, 1], out["at0"]
+ for name in ("point", "plane"):
+ curve = out[name]
+ for a, b in zip(curve, curve[1:], strict=False):
+ assert b <= a, f"{name} bounce rises with distance: {a} -> {b}"
+ inside = [c for c in curve[:30] if c > 0]
+ assert len(inside) > 25 and inside[0] > 8 * inside[-1], inside
+ # EXACTLY zero at the reach and past it, both shapes.
+ assert out["atR"] == [0, 0], out["atR"]
+ assert out["beyond"] == [0, 0, 0], out["beyond"]
+ # A wall is a broad source and a rug is not: at half the reach the
+ # plane must still be carrying several times what the point is.
+ assert out["half"][1] > 2.0 * out["half"][0], out["half"]
+
+
+def test_a_plane_bounces_with_the_form_factor_and_a_point_does_not():
+ """THE PORT'S FIRST LAW. The half-lambert un-squared is the EXACT
+ cosine-weighted form factor at both limits of a Lambertian
+ half-space — 1.0 for a ceiling facing a lit floor, 0.5 for a wall
+ standing on one — and squaring it lands the wall at 0.25. That is
+ half the bleed on the one geometry every room has, and on our host it
+ was the difference between 3.9 and 6.9 of 255 on the plaster. A
+ POINT keeps the square: a rug really is directional."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchBounceLight } from './lib/indoor.js';
+
+const m = new THREE.MeshStandardMaterial();
+patchBounceLight(m, { sources: [{ position: [0, 0, 0], normal: [0, 1, 0],
+ reach: 4 }] });
+const body = m.userData.astraPatches.find(
+ (p) => p.name === 'indoor:bounce').fragmentBody;
+// the wrap the shipped body applies, run at the three geometries that
+// matter: facing the source, perpendicular to it, turned away.
+const wrap = (lam, plane) => {
+ const sq = lam * lam;
+ return plane * lam + (1 - plane) * sq;
+};
+console.log(JSON.stringify({
+ body,
+ plane: [wrap(1, 1), wrap(0.5, 1), wrap(0, 1)],
+ point: [wrap(1, 0), wrap(0.5, 0), wrap(0, 0)],
+}));
+""", _LIBS)
+ body = out["body"]
+ assert "float bncWrap = mix(bncLam * bncLam, bncLam, bncPl);" in body, body
+ assert "bncSum += bncTint * (bncFront * bncWrap" in body, body
+ # ceiling over a floor 1.0, wall on a floor 0.5, facing away 0.
+ assert out["plane"] == [1, 0.5, 0], out["plane"]
+ # and the point is still the tighter, squared response.
+ assert out["point"] == [1, 0.25, 0], out["point"]
+
+
+def test_the_wash_loses_the_bouncer_hue_as_it_spreads_and_is_dithered():
+ """A red bleed as red at its far edge as it is under the wall reads as
+ a coloured LAMP: light that has come further has bounced off more than
+ one thing. And bounce is the smoothest gradient a room has, on the
+ widest flat in it — without a dither it climbs the 8-bit ladder in
+ bands (136 -> 156 distinct colours over the showcase's gradient
+ strip)."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchBounceLight } from './lib/indoor.js';
+
+const m = new THREE.MeshStandardMaterial();
+patchBounceLight(m, { sources: [{ position: [0, 0, 0], normal: [0, 1, 0],
+ color: 0xc23a2c, reach: 3 }] });
+const body = m.userData.astraPatches.find(
+ (p) => p.name === 'indoor:bounce').fragmentBody;
+const amp = /\\)\\s*\\*\\s*(0\\.\\d+)\\s*\\*\\s*step\\(/.exec(body);
+console.log(JSON.stringify({
+ body,
+ desatAt: /0\\.32\\s*\\*\\s*bncX/.test(body),
+ ditherAmp: amp ? parseFloat(amp[1]) : null,
+}));
+""", _LIBS)
+ body = out["body"]
+ # the tint is mixed toward its own LUMA (a grey of the same
+ # brightness), so the wash goes pale, never dark, as it spreads.
+ assert "vec3 bncTint = mix(uBncCol[i]," in body, body
+ assert "vec3(0.2126, 0.7152, 0.0722))" in body, body
+ assert out["desatAt"], body
+ # gated on bncX, which is 0 at the source: the skirting under a red
+ # wall keeps the full hue.
+ assert "float bncX = clamp(bncDist / max(uBncSpan[i].x, 1e-4)" in body
+ # Half a code of hash, and only where there is bleed to band.
+ assert "astraHash11(gl_FragCoord.x" in body, body
+ assert "step(1e-4, bncLvl)" in body, body
+ assert 0.002 <= out["ditherAmp"] <= 0.012, out["ditherAmp"]
+
+
+def test_the_bounce_is_light_and_never_repaints_the_albedo():
+ """A bounce lifted into ALBEDO is capped at the light already landing
+ on the surface, so the shaded soffit under an eave — the one place
+ colour bleed is the whole cue — would take none of it. It has to ADD,
+ tinted by the receiver's own colour because arriving light is
+ reflected, and it must never assign over diffuseColor, which would
+ delete every patch that ran before it."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchBounceLight } from './lib/indoor.js';
+
+const m = new THREE.MeshStandardMaterial({ color: 0x445566 });
+patchBounceLight(m, {
+ sources: [{ position: [0, 2, 0], normal: [0, 1, 0], color: 0x40ff40,
+ reach: 4 },
+ { position: [3, 0, 0], color: 0xff4040, reach: 2 }],
+ strength: 1.5 });
+const p = m.userData.astraPatches.find((q) => q.name === 'indoor:bounce');
+const base = m.userData.astraPatches.find((q) => q.name === 'indoor:base');
+const u = m.userData.uniforms;
+console.log(JSON.stringify({
+ body: p.fragmentBody,
+ vert: base.vertexBody,
+ names: m.userData.astraPatches.map((q) => q.name),
+ count: u.uBncCount.value,
+ gain: u.uBncGain.value,
+ spans: u.uBncSpan.value.map((v) => [v.x, v.y]),
+ colors: u.uBncCol.value.map((c) => c.getHex()),
+ normals: u.uBncNrm.value.map((v) => v.toArray()),
+ emissive: m.emissive !== undefined,
+}));
+""", _LIBS)
+ body = out["body"]
+ assert "totalEmissiveRadiance +=" in body, body
+ # Reads the albedo as a reflectance, never writes it.
+ assert "diffuseColor.rgb" in body, body
+ assert not re.search(r"diffuseColor(\.rgb)?\s*=[^=]", body), body
+ assert "astraBncFall(" in body, body
+ # An instanced post needs instanceMatrix folded in by hand, or every
+ # copy is lit as though it stood at the mesh origin.
+ assert "USE_INSTANCING" in out["vert"], out["vert"]
+ assert out["count"] == 2 and out["gain"] == 1.5, out
+ # Stating a normal makes a source a PLANE (span.y 1) and leaving it
+ # out makes it a POINT (0) — the whole geometry of the falloff.
+ assert out["spans"][0] == [4, 1], out["spans"]
+ assert out["spans"][1] == [2, 0], out["spans"]
+ # An unused slot is black, so a shorter list cannot leak light.
+ assert out["colors"][2:] == [0] * 4, out["colors"]
+ # A point with no normal of its own throws along `up`.
+ assert out["normals"][1] == [0, 1, 0], out["normals"]
+
+
+def test_a_bouncer_only_lights_the_side_it_faces():
+ """A lawn does not light the cellar under it and a wall throws nothing
+ through itself: without the front gate, colour bleed leaks to the far
+ side of every surface that casts it — which is the one way this reads
+ as a coloured fog rather than as light."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchBounceLight } from './lib/indoor.js';
+
+const m = new THREE.MeshStandardMaterial();
+patchBounceLight(m, { sources: [{ position: [0, 0, 0],
+ normal: [0, 1, 0], reach: 3 }] });
+const p = m.userData.astraPatches.find((q) => q.name === 'indoor:bounce');
+console.log(JSON.stringify({ body: p.fragmentBody,
+ head: p.fragmentHead }));
+""", _LIBS)
+ body = out["body"]
+ assert "float bncSide = dot(bncD, uBncNrm[i]);" in body, body
+ assert "step(1e-4, bncSide)" in body, body
+ # A plane is measured PERPENDICULAR to itself and a point radially:
+ # that is what makes a long wall bleed along a whole band of ceiling
+ # while a rug stays under the table.
+ assert "mix(bncR, bncSide, bncPl)" in body, body
+ assert "mix(-bncD / max(bncR, 1e-4), -uBncNrm[i], bncPl)" in body, body
+ # Half lambert: a hard terminator would cut the ceiling off in a line
+ # above a wall that in truth lights all of it.
+ assert "dot(bncN, bncL) * 0.5 + 0.5" in body, body
+
+
+def test_fingerprints_move_gloss_and_never_colour():
+ """A smudge that changes the COLOUR of glass is a stain, and the pane
+ reads as dirty rather than used. Gloss is per MATERIAL here
+ (`<color_fragment>` runs before `<roughnessmap_fragment>`), so the
+ reachable half is a roughness factor composed through
+ `composeRoughness` — and it must compose, not re-base, or two
+ libraries on one material fight over the same number."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchFingerprints } from './lib/indoor.js';
+
+const rough = (amount, smear) => {
+ const m = new THREE.MeshStandardMaterial({ color: 0x224466,
+ roughness: 0.10 });
+ patchFingerprints(m, { amount, smear, seed: 2 });
+ return { r: m.roughness, color: m.color.getHex() };
+};
+const m = new THREE.MeshStandardMaterial({ color: 0x224466,
+ roughness: 0.10 });
+patchFingerprints(m, { amount: 0.8, smear: 0.4, seed: 2 });
+const once = m.roughness;
+patchFingerprints(m, { amount: 0.8, smear: 0.4, seed: 2 });
+const p = m.userData.astraPatches.find(
+ (q) => q.name === 'indoor:fingerprints');
+console.log(JSON.stringify({
+ clean: rough(0, 0), light: rough(0.3, 0.4), heavy: rough(1, 1),
+ once, twice: m.roughness,
+ keys: Object.keys(m.userData.astraRoughness.factors),
+ base: m.userData.astraRoughness.base,
+ body: p.fragmentBody,
+}));
+""", _LIBS)
+ clean, light, heavy = out["clean"], out["light"], out["heavy"]
+ # Grease scatters: gloss goes DOWN (roughness up) with the amount.
+ assert clean["r"] == 0.10, clean
+ assert light["r"] > clean["r"], (clean, light)
+ assert heavy["r"] > light["r"], (light, heavy)
+ # And the albedo is untouched at every setting.
+ assert clean["color"] == light["color"] == heavy["color"] == 0x224466
+ # Re-applying retunes, never re-bases (composeRoughness).
+ assert out["twice"] == out["once"], out
+ assert out["keys"] == ["indoor:fingerprints"], out["keys"]
+ assert out["base"] == 0.10, out["base"]
+ body = out["body"]
+ assert "totalEmissiveRadiance +=" in body, body
+ assert "diffuseColor" not in body, body
+
+
+def test_the_smudge_is_hidden_head_on_and_comes_up_at_grazing():
+ """The whole cue: grease is invisible until the surface starts
+ reflecting, then it takes the pane over. The weight is the
+ dielectric's own — a few percent head-on, everything at grazing — read
+ out of shader.js's `astraFresnel`, the same helper every grazing-angle
+ effect in this library shares."""
+ out = measure(_FRESNEL_AS_JS + """
+import * as THREE from 'three';
+import { GLSL_UTIL } from './lib/shader.js';
+import { patchFingerprints } from './lib/indoor.js';
+
+const m = new THREE.MeshStandardMaterial({ roughness: 0.08 });
+patchFingerprints(m, { amount: 0.6, smear: 0.4, seed: 3 });
+const p = m.userData.astraPatches.find(
+ (q) => q.name === 'indoor:fingerprints');
+const fres = fresnelOf(GLSL_UTIL);
+// A pane facing +Z, seen from `deg` off its normal — the weight the
+// shipped body applies to the whole smudge.
+const weight = (deg) => {
+ const a = deg * Math.PI / 180;
+ const v = [Math.sin(a), 0, Math.cos(a)];
+ return 0.06 + 0.94 * fres([0, 0, 1], v, 4.0);
+};
+console.log(JSON.stringify({
+ ladder: [0, 30, 60, 75, 82, 88].map((d) => +weight(d).toFixed(4)),
+ body: p.fragmentBody, head: p.fragmentHead,
+}));
+""", _LIBS)
+ ladder = out["ladder"]
+ # The numbers only mean anything if the shipped body applies them.
+ assert "float fprGrz = astraFresnel(fprN, fprV, 4.0);" in out["body"]
+ assert "float fprW = mix(0.06, 1.0, fprGrz);" in out["body"]
+ assert "fprW" in out["body"].split("totalEmissiveRadiance")[1]
+ for a, b in zip(ladder, ladder[1:], strict=False):
+ assert b > a, f"the smudge does not rise with the angle: {ladder}"
+ assert ladder[0] < 0.07, ladder
+ assert ladder[4] > 8 * ladder[0], ladder
+ # The scratches are the grazing-only layer, gated a second time.
+ assert "fprScr * fprGrz" in out["body"], out["body"]
+ # And there is a light to catch, or a smudge has nothing to show:
+ # both direct kinds plus the sky, which is what a shopfront reflects.
+ for token in ("directionalLights[i].color", "pointLights[i].color",
+ "hemisphereLights[i].skyColor"):
+ assert token in out["body"], token
+
+
+def test_the_grease_is_a_film_and_not_a_set_of_stripes():
+ """THE PORT'S FOURTH LAW. Arcs alone are a few bright bands on clean
+ glass, and the eye reads bands as paint. The film rides the same
+ blotch that decides WHERE hands have been — so a wiped pane stays
+ wiped — at about half the arcs' weight, with its own slow variation
+ so it is cloud and not a wash."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchFingerprints } from './lib/indoor.js';
+
+const m = new THREE.MeshStandardMaterial();
+patchFingerprints(m, { amount: 0.6, smear: 0.4, seed: 3 });
+const body = m.userData.astraPatches.find(
+ (q) => q.name === 'indoor:fingerprints').fragmentBody;
+const w = /fprFilm\\s*\\*\\s*(0\\.\\d+)/.exec(body);
+console.log(JSON.stringify({ body, filmWeight: w ? parseFloat(w[1]) : null }));
+""", _LIBS)
+ body = out["body"]
+ # It is gated on fprWhere — the same blotch as the arcs — so amount
+ # still means "how much of the surface hands have reached".
+ assert "float fprFilm = fprWhere * (" in body, body
+ assert "astraNoise2(fprQ" in body.split("fprFilm")[1], body
+ assert "+ fprFilm * " in body, body
+ assert 0.3 <= out["filmWeight"] <= 0.75, out["filmWeight"]
+ # and it is inside the mask, so the fresnel weight still hides it
+ # head-on: a film that ignored the angle would be a frosted pane.
+ mask = body.split("float fprMask")[1].split("\n")[0:3]
+ assert any("fprFilm" in ln for ln in mask), mask
+
+
+def test_the_crowd_is_one_draw_call_seated_on_the_ground():
+ """A crowd is only affordable as one draw call, and it is only a crowd
+ if its people stand ON the ground with their own heights. The stated
+ bounding SPHERE is the other half: `position` is all zeros (the GTAO
+ reason `instancedQuad` documents), so without a real radius three
+ culls the whole square the moment the origin leaves frame — and with
+ the 10 km default it frames 10 km of empty air."""
+ out = measure("""
+import { makeCrowdImposters } from './lib/indoor.js';
+
+const heightAt = (x, z) => 1.4 + 0.25 * Math.sin(x * 0.21)
+ + 0.18 * Math.cos(z * 0.17);
+const g = makeCrowdImposters({ count: 64, extent: 30, height: 1.72,
+ heightAt, seed: 4 });
+const meshes = [];
+g.traverse((o) => { if (o.isMesh) meshes.push(o); });
+const geo = meshes[0].geometry;
+const pos = geo.attributes.aPos.array;
+const card = geo.attributes.aCrowd.array;
+let offGround = 0, outside = 0;
+const scales = [], tones = [];
+for (let i = 0; i < 64; i++) {
+ const x = pos[i * 3], y = pos[i * 3 + 1], z = pos[i * 3 + 2];
+ if (Math.abs(y - heightAt(x, z)) > 1e-6) offGround++;
+ if (Math.abs(x) > 15 || Math.abs(z) > 15) outside++;
+ scales.push(card[i * 4 + 1]);
+ tones.push(card[i * 4]);
+}
+console.log(JSON.stringify({
+ meshes: meshes.length,
+ vertex: meshes[0].material.vertexShader,
+ instanced: !!geo.isInstancedBufferGeometry,
+ count: geo.instanceCount,
+ zeroPos: geo.attributes.position.array.every((v) => v === 0),
+ radius: geo.boundingSphere.radius,
+ lowY: geo.boundingBox.min.y, highY: geo.boundingBox.max.y,
+ offGround, outside,
+ scaleRange: [Math.min(...scales), Math.max(...scales)],
+ toneRange: [Math.min(...tones), Math.max(...tones)],
+ name: g.name, tick: typeof g.userData.tick,
+ ticked: g.userData.tick(3.5),
+}));
+""", _LIBS)
+ assert out["meshes"] == 1, out["meshes"]
+ assert out["instanced"] and out["count"] == 64, out
+ # The GTAO trap: a real quad left in `position` is drawn at the world
+ # origin by the override pass and burns a hole there.
+ assert out["zeroPos"], "the cards keep a real quad in position"
+ assert out["offGround"] == 0, f"{out['offGround']} people float"
+ assert out["outside"] == 0, out["outside"]
+ # A REAL radius, not the 10 km default and not a sphere so small three
+ # culls the square as soon as its centre leaves frame.
+ assert 15 < out["radius"] < 40, out["radius"]
+ assert out["lowY"] < 1.2 and out["highY"] > 2.9, out
+ # Varied heights and clothing, or a crowd is wallpaper: one in seven
+ # is a child, so the range has to reach well under an adult.
+ lo, hi = out["scaleRange"]
+ assert lo < 0.8 and hi > 1.0, out["scaleRange"]
+ assert out["toneRange"][1] - out["toneRange"][0] > 0.8, out
+ assert out["name"] == "Crowd" and out["tick"] == "function", out
+ assert out["ticked"] == 1, out["ticked"]
+ # Facing the camera, in YAW only: a card that also pitches lifts the
+ # whole crowd off the ground together as the camera looks down.
+ vs = out["vertex"]
+ assert "modelViewMatrix[0][0], modelViewMatrix[1][0]" in vs, vs
+ assert "camR - up * dot(camR, up)" in vs, vs
+ assert "vec3 up = vec3(0.0, 1.0, 0.0);" in vs, vs
+
+
+def test_a_backlit_card_is_a_silhouette_with_a_lit_edge():
+ """THE PORT'S FIFTH LAW. With the sun behind it, a hard `max(dot, 0)`
+ on this card's coarse bowed normal prints the whole crowd as one flat
+ ambient tone — the frame our host rendered before this, where 90
+ people were 90 identical blue-grey stumps. Three things fix it and
+ all three are in the shipped shader: a WRAP so the terminator is not a
+ cliff, a RIM in the light's own colour on the sun-side edge of the
+ silhouette (gated on the sun being BEHIND, or a front-lit crowd grows
+ a halo), and per-person VALUE, because a street is pale coats and dark
+ ones and hue alone is not a crowd."""
+ out = measure("""
+import { makeCrowdImposters } from './lib/indoor.js';
+
+const g = makeCrowdImposters({ count: 8, extent: 10, seed: 3 });
+const mat = g.children[0].material;
+console.log(JSON.stringify({
+ vs: mat.vertexShader, fs: mat.fragmentShader,
+ leg: mat.uniforms.uCrwLeg.value.toArray().map((v) => +v.toFixed(4)),
+}));
+""", _LIBS)
+ vs, fs = out["vs"], out["fs"]
+ # The card has no depth for a normal to find the rim in, so the
+ # vertex stage hands the fragment which way the light lies ACROSS it
+ # and how far behind.
+ assert "vCrwRim = vec2(dot(right, uCrwSun), clamp(-dot(fwd, uCrwSun)" in vs
+ assert "uniform vec3 uCrwSun;" in vs, vs
+ # Wrapped, not clamped.
+ assert "float iNdL = clamp((dot(normalize(vCrwN), uCrwSun) + 0.30)" in fs
+ assert "max(dot(normalize(vCrwN), uCrwSun), 0.0)" not in fs, fs
+ # The rim rides the real silhouette (cW is the body half-width), is
+ # gated on the sun side and on backlight, and is the LIGHT's colour.
+ rim = fs.split("float iRim")[1].split(";")[0]
+ assert "abs(iq.x) / max(cW, 0.02)" in rim, rim
+ assert "vCrwRim.x * sign(iq.x)" in rim and "vCrwRim.y" in rim, rim
+ assert "uCrwSunColor * (iRim *" in fs, fs
+ # Value per person, on the clothing ramp.
+ assert "iAlb *= 0.72 + 0.62 * fract(cPh * 0.29);" in fs, fs
+ # Trousers, hair and shoes stay above the albedo floor: linear 0.02 is
+ # about where a surface stops being a colour and becomes a hole.
+ r, gr, b = out["leg"]
+ assert min(r, gr, b) > 0.02, out["leg"]
+ assert max(r, gr, b) < 0.10, out["leg"]
+
+
+def test_the_crowd_is_kept_out_of_the_override_passes():
+ """GTAOPass redraws the scene with an OPAQUE override material, in
+ which a transparent card is a solid wall — measured elsewhere at
+ 50/255 of false darkening on ground the effect never touched. The
+ same guard stops the mesh casting a shadow, which is right: a card
+ that always faces the camera would cast a shadow that turns with
+ it."""
+ out = measure("""
+import { makeCrowdImposters } from './lib/indoor.js';
+
+const rows = [];
+makeCrowdImposters({ count: 12, extent: 10, seed: 4 }).traverse((o) => {
+ if (!o.isMesh) return;
+ rows.push({ name: o.name,
+ guarded: o.userData.astraNoOverride === true,
+ shadow: !!o.castShadow,
+ transparent: !!o.material.transparent,
+ depthWrite: !!o.material.depthWrite });
+});
+console.log(JSON.stringify({ rows }));
+""", _LIBS)
+ rows = out["rows"]
+ assert len(rows) == 1, rows
+ for r in rows:
+ assert r["transparent"], r
+ assert r["guarded"], f"{r['name']} would be a solid wall to GTAO"
+ assert not r["shadow"], f"{r['name']} casts a shadow"
+ # Still writes depth: a card that does not punches a
+ # sky-coloured hole through the one behind it.
+ assert r["depthWrite"], r
+
+
+def test_every_option_is_a_uniform_and_not_baked_into_the_glsl():
+ """The first material to compile a cache key decides the GLSL every
+ material with that key gets. So two rooms tuned differently must
+ differ only in UNIFORM values — otherwise the second room silently
+ renders with the first one's sources, and nothing in the frame says
+ so."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchBounceLight, patchFingerprints } from './lib/indoor.js';
+
+const make = (opts, fpr) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchBounceLight(m, opts);
+ patchFingerprints(m, fpr);
+ const b = m.userData.astraPatches.find((p) => p.name === 'indoor:bounce');
+ const f = m.userData.astraPatches.find(
+ (p) => p.name === 'indoor:fingerprints');
+ return {
+ key: m.customProgramCacheKey(),
+ glsl: [b.fragmentHead, b.fragmentBody, b.vertexHead,
+ f.fragmentHead, f.fragmentBody].join('|'),
+ bounce: [m.userData.uniforms.uBncGain.value,
+ m.userData.uniforms.uBncCount.value,
+ m.userData.uniforms.uBncNrm.value[0].toArray()],
+ smudge: [m.userData.uniforms.uFprAmt.value,
+ m.userData.uniforms.uFprSmear.value,
+ m.userData.uniforms.uFprSeed.value.toArray()],
+ };
+};
+const a = make({ sources: [[0, 0, 0]], strength: 1 },
+ { amount: 0.3, smear: 0.2, seed: 1 });
+const b = make({ sources: [[4, 1, 0], [0, 2, 0]], strength: 2.5,
+ up: [0, 0, 1] },
+ { amount: 0.9, smear: 0.8, seed: 7 });
+console.log(JSON.stringify({ a, b, same: a.glsl === b.glsl }));
+""", _LIBS)
+ a, b = out["a"], out["b"]
+ assert out["same"], "an option was baked into the GLSL"
+ assert a["key"] == b["key"], (a["key"], b["key"])
+ assert "indoor:base" in a["key"] and "indoor:bounce" in a["key"]
+ assert "indoor:fingerprints" in a["key"], a["key"]
+ assert a["bounce"] != b["bounce"], a["bounce"]
+ assert b["bounce"][2] == [0, 0, 1], b["bounce"]
+ assert a["smudge"] != b["smudge"], a["smudge"]
+
+
+def test_the_same_seed_builds_the_same_crowd_twice():
+ """No Math.random anywhere: two runs of one brief must be the same
+ frame, and a different seed must actually move the crowd rather than
+ renaming it."""
+ assert "Math.random" not in _SRC.read_text(encoding="utf-8")
+ out = measure("""
+import * as THREE from 'three';
+import { makeCrowdImposters, patchFingerprints } from './lib/indoor.js';
+
+const field = (seed) => {
+ const g = makeCrowdImposters({ count: 30, extent: 20, seed,
+ heightAt: (x, z) => 0 });
+ const a = g.children[0].geometry.attributes;
+ return { pos: Array.from(a.aPos.array),
+ card: Array.from(a.aCrowd.array) };
+};
+const seedOf = (s) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchFingerprints(m, { seed: s });
+ return m.userData.uniforms.uFprSeed.value.toArray();
+};
+const a = field(4), b = field(4), c = field(5);
+console.log(JSON.stringify({
+ same: a.pos.every((v, i) => v === b.pos[i])
+ && a.card.every((v, i) => v === b.card[i]),
+ moved: a.pos.some((v, i) => v !== c.pos[i]),
+ smudge: [seedOf(1), seedOf(1), seedOf(2)],
+}));
+""", _LIBS)
+ assert out["same"], "the same seed built two different crowds"
+ assert out["moved"], "a new seed built the same crowd"
+ s = out["smudge"]
+ assert s[0] == s[1] and s[0] != s[2], s
+
+
+def test_both_patches_chain_with_another_library_on_one_material():
+ """GLSL has one global namespace and `patchStandard` THROWS when two
+ patches define one function name with different bodies — a room's wall
+ wears wear, bounce and grease at once, so the prefixes are not
+ decoration. The chain must also run in CALL order and share one
+ uniform map."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchBounceLight, patchFingerprints } from './lib/indoor.js';
+import { patchEdgeWear, patchMicroBreakup } from './lib/surface_wear.js';
+
+const m = new THREE.MeshStandardMaterial({ roughness: 0.3 });
+patchMicroBreakup(m, { scale: 0.6, strength: 0.12, seed: 5 });
+patchBounceLight(m, { sources: [[0, 1, 0]] });
+patchEdgeWear(m, { strength: 0.4, seed: 6 });
+patchFingerprints(m, { amount: 0.5, seed: 3 });
+const heads = m.userData.astraPatches
+ .map((p) => p.fragmentHead || '').join('\\n');
+const fns = [...heads.matchAll(/^\\s*(?:float|vec2|vec3)\\s+(\\w+)\\s*\\(/gm)]
+ .map((x) => x[1]);
+console.log(JSON.stringify({
+ names: m.userData.astraPatches.map((p) => p.name),
+ key: m.customProgramCacheKey(),
+ fns, dupes: fns.filter((f, i) => fns.indexOf(f) !== i),
+ uniforms: Object.keys(m.userData.uniforms).sort(),
+ roughness: m.roughness,
+ factors: Object.keys(m.userData.astraRoughness.factors).sort(),
+}));
+""", _LIBS)
+ assert out["names"] == [
+ "wear:base", "wear:micro", "indoor:base", "indoor:bounce",
+ "wear:edge", "indoor:fingerprints"], out["names"]
+ assert out["dupes"] == [], out["dupes"]
+ # Every helper this library adds is prefixed to its own patch.
+ for fn in ("astraBncFall", "astraFprField", "astraFprArc",
+ "astraFprPlane", "astraFprLobe"):
+ assert fn in out["fns"], out["fns"]
+ for u in ("uBncCol", "uBncCount", "uBncGain", "uBncNrm", "uBncPos",
+ "uBncSpan", "uFprAmt", "uFprSeed", "uFprSmear"):
+ assert u in out["uniforms"], out["uniforms"]
+ # Three libraries, three roughness factors, one composed number.
+ assert out["factors"] == ["edge", "indoor:fingerprints", "micro"], out
+ assert 0.04 <= out["roughness"] <= 1, out["roughness"]
diff --git a/harness/tests/scene_runtime/lib/test_instancing.py b/harness/tests/scene_runtime/lib/test_instancing.py
new file mode 100644
index 00000000..bb0c489e
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_instancing.py
@@ -0,0 +1,432 @@
+"""instancing.js — one asset, hundreds of copies, one draw call per material.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_instancing_lib.py). The reference's five tests are grep assertions
+over the source text; what they are ABOUT is kept and measured instead — the
+prototype is built once, sub-meshes keep their offsets, the root transform is
+not one of them, the scatter is seeded and can leave gaps, and no two copies
+are the same shape.
+
+The rest pin what the port changed, each one a defect the showcase render
+(fx/out/instancing/*) showed:
+
+* a multi-material mesh kept only ``material[0]``, so the cottage's timber
+ front face rendered as plaster and the BEFORE frame was pixel-identical to
+ one built with a single material;
+* ``mergeGeometries`` returns null on an attribute mismatch and that bucket
+ was dropped — an asset rendering with a part missing, silently;
+* every copy carried the prototype's exact albedo, which is the "high
+ repetition of identical towers" read the module's own docs are written
+ against. ``scatterGrid`` now emits a per-copy LINEAR tint;
+* ``yaw`` could only be free or off, and a built fabric wants to face its
+ street; jitter plus scaleVar routinely put two roofs in the same cubic
+ metre (measured on the showcase hamlet: one pair of ten, centres 4.10 m
+ apart under roofs 5.0 m across, z-fighting as one striped surface), which
+ ``clearance`` ends.
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("instancing.js",)
+
+# A cottage: walls (a MULTI-material box, timber on +Z), a roof of a second
+# material, and a chimney that shares the wall material 2.75 m up — the
+# sub-part offset that a bare geometry.clone() would lose.
+_ASSET = """
+import * as THREE from 'three';
+let builds = 0;
+const plaster = new THREE.MeshStandardMaterial({ color: 0xb9a891 });
+const tile = new THREE.MeshStandardMaterial({ color: 0x8a4b36 });
+const timber = new THREE.MeshStandardMaterial({ color: 0x6d5540 });
+function cottage(opts = {}) {
+ builds++;
+ const g = new THREE.Group();
+ const walls = new THREE.Mesh(new THREE.BoxGeometry(2.6, 1.9, 2.6),
+ opts.plain ? plaster : [plaster, plaster, plaster, plaster, timber, plaster]);
+ walls.position.y = 0.95;
+ g.add(walls);
+ const roof = new THREE.Mesh(new THREE.ConeGeometry(2, 1.15, 4), tile);
+ roof.position.y = 2.5;
+ g.add(roof);
+ const chimney = new THREE.Mesh(new THREE.BoxGeometry(0.38, 1.1, 0.38), plaster);
+ chimney.position.set(0.62, 2.75, 0.55);
+ g.add(chimney);
+ if (opts.rootAt) g.position.set(...opts.rootAt);
+ return g;
+}
+const prng = (seed) => { let s = seed >>> 0;
+ return () => (s = (s * 1664525 + 1013904223) >>> 0) / 4294967296; };
+const tris = (geo) => (geo.index ? geo.index.count : geo.attributes.position.count) / 3;
+const stat = (v) => {
+ const mean = v.reduce((a, b) => a + b, 0) / v.length;
+ const sd = Math.sqrt(v.reduce((a, b) => a + (b - mean) ** 2, 0) / v.length);
+ return { mean, sd, min: Math.min(...v), max: Math.max(...v), uniq: new Set(v).size };
+};
+"""
+
+
+def test_the_prototype_is_built_once_and_becomes_one_draw_per_material():
+ """The whole bet: 200 copies cost the asset's triangles ONCE and one draw
+ call per material, not 200 builds and 600 meshes."""
+ out = measure(_ASSET + """
+import { instanceAsset } from './lib/instancing.js';
+const placements = [];
+for (let i = 0; i < 200; i++) placements.push({ position: [i * 3, 0, 0] });
+const before = builds;
+const g = instanceAsset(cottage, placements, { name: 'Hamlet' });
+const kids = g.children.map((m) => ({
+ instanced: !!m.isInstancedMesh, count: m.count, tris: tris(m.geometry),
+ mat: m.material.color.getHexString(), culled: m.frustumCulled,
+ casts: m.castShadow, receives: m.receiveShadow,
+}));
+const pos = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3();
+const m4 = new THREE.Matrix4();
+g.children[0].getMatrixAt(7, m4);
+m4.decompose(pos, q, s);
+console.log(JSON.stringify({
+ builds: builds - before, name: g.name, kids,
+ totalTris: kids.reduce((a, k) => a + k.tris, 0),
+ seventh: pos.toArray().map((v) => +v.toFixed(4)),
+ empty: instanceAsset(cottage, []).children.length,
+}));
+""", _LIBS)
+ assert out["builds"] == 1, out
+ assert out["name"] == "Hamlet"
+ assert out["empty"] == 0, out
+ # Three materials on the prototype -> three draws, whatever the copy count.
+ assert len(out["kids"]) == 3, out
+ assert {k["mat"] for k in out["kids"]} == {"b9a891", "8a4b36", "6d5540"}, out
+ for k in out["kids"]:
+ assert k["instanced"] and k["count"] == 200, out
+ assert k["casts"] and k["receives"], out
+ # One bounding sphere cannot cover a spread this wide, so culling is
+ # off: with it on, three culls the whole field on the first copy.
+ assert k["culled"] is False, out
+ # The box (12) + the cone (8) + the chimney (12) once, not 200 times.
+ assert out["totalTris"] == 32, out
+ assert out["seventh"] == [21.0, 0.0, 0.0], out
+
+
+def test_a_sub_part_keeps_its_offset_and_the_root_does_not():
+ """The chimney sits 2.75 m up and 0.62 across; baking that transform is the
+ whole reason a naive clone() is not enough. The prototype ROOT's own
+ transform is the one thing that must NOT come along — the placements own
+ world space, so a builder that happens to return its group parked
+ somewhere still stamps copies where they were asked for."""
+ out = measure(_ASSET + """
+import { instanceAsset } from './lib/instancing.js';
+const box = (opts) => {
+ const g = instanceAsset(cottage, [{ position: [4, 0, -2] }], { buildOpts: opts });
+ const wall = g.children.find((m) => m.material.color.getHexString() === 'b9a891');
+ wall.geometry.computeBoundingBox();
+ const b = wall.geometry.boundingBox;
+ const pos = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3();
+ const m4 = new THREE.Matrix4();
+ wall.getMatrixAt(0, m4);
+ m4.decompose(pos, q, s);
+ return { min: b.min.toArray().map((v) => +v.toFixed(3)),
+ max: b.max.toArray().map((v) => +v.toFixed(3)),
+ at: pos.toArray().map((v) => +v.toFixed(3)) };
+};
+console.log(JSON.stringify({ home: box({}), parked: box({ rootAt: [40, 9, -7] }) }));
+""", _LIBS)
+ # Walls span y 0..1.9 and the chimney reaches 3.30 — one merged geometry
+ # holding both, in the prototype's own frame.
+ for key in ("home", "parked"):
+ f = out[key]
+ assert f["min"][1] == 0.0 and f["max"][1] == 3.3, (key, out)
+ assert f["max"][0] == pytest.approx(1.3), (key, out)
+ assert f["at"] == [4.0, 0.0, -2.0], (key, out)
+ assert out["home"] == out["parked"], out
+
+
+def test_a_multi_material_mesh_keeps_its_second_material():
+ """PORT FIX. `material[0]` for the whole geometry painted the timber front
+ face with the wall's plaster — and the showcase BEFORE frame came out
+ pixel-identical to a cottage built with one material, which is how a
+ silent bug looks. Each geometry group becomes its own draw, and the
+ triangles are neither lost nor duplicated."""
+ out = measure(_ASSET + """
+import { instanceAsset } from './lib/instancing.js';
+const split = instanceAsset(cottage, [{ position: [0, 0, 0] }]);
+const plain = instanceAsset(cottage, [{ position: [0, 0, 0] }],
+ { buildOpts: { plain: true } });
+const rows = (g) => g.children.map((m) => ({
+ mat: m.material.color.getHexString(), tris: tris(m.geometry) }))
+ .sort((a, b) => a.mat.localeCompare(b.mat));
+const front = split.children.find((m) => m.material.color.getHexString() === '6d5540');
+front.geometry.computeBoundingBox();
+console.log(JSON.stringify({
+ split: rows(split), plain: rows(plain),
+ // the +Z face, and only that face
+ frontZ: +front.geometry.boundingBox.min.z.toFixed(3),
+ backZ: +front.geometry.boundingBox.max.z.toFixed(3),
+}));
+""", _LIBS)
+ assert out["split"] == [
+ {"mat": "6d5540", "tris": 2}, # the one face
+ {"mat": "8a4b36", "tris": 8}, # the roof cone
+ {"mat": "b9a891", "tris": 22}, # five box faces + the chimney
+ ], out
+ # Same triangles either way — the split adds draws, not geometry.
+ assert sum(r["tris"] for r in out["split"]) == 32, out
+ assert out["plain"] == [{"mat": "8a4b36", "tris": 8},
+ {"mat": "b9a891", "tris": 24}], out
+ assert out["frontZ"] == out["backZ"] == 1.3, out
+
+
+def test_a_bucket_that_cannot_merge_falls_back_to_draws_not_to_a_hole():
+ """PORT FIX. `mergeGeometries` returns null — no throw, no warning — when
+ its inputs disagree on their attribute set, and that bucket used to be
+ dropped: the asset rendered with a part MISSING. A vertex-coloured piece
+ beside a plain one is the ordinary way in, because `mergeStatic()` hands
+ back geometry carrying `color`."""
+ out = measure(_ASSET + """
+import { instanceAsset } from './lib/instancing.js';
+const mixed = () => {
+ const g = new THREE.Group();
+ const mat = new THREE.MeshStandardMaterial({ color: 0x777777, vertexColors: true });
+ const a = new THREE.BoxGeometry(1, 1, 1);
+ const n = a.attributes.position.count;
+ a.setAttribute('color', new THREE.BufferAttribute(new Float32Array(n * 3).fill(0.4), 3));
+ const b = new THREE.BoxGeometry(1, 1, 1); // no color attribute
+ const m1 = new THREE.Mesh(a, mat); m1.position.y = 0.5;
+ const m2 = new THREE.Mesh(b, mat); m2.position.y = 2.0;
+ g.add(m1, m2);
+ return g;
+};
+const g = instanceAsset(mixed, [{ position: [0, 0, 0] }, { position: [5, 0, 0] }]);
+const geo = g.children[0].geometry;
+geo.computeBoundingBox();
+const c = geo.attributes.color;
+let lo = 9, hi = -9;
+for (let i = 0; i < c.count; i++) { lo = Math.min(lo, c.getX(i)); hi = Math.max(hi, c.getX(i)); }
+console.log(JSON.stringify({
+ draws: g.children.length, tris: g.children.reduce((a, m) => a + tris(m.geometry), 0),
+ top: +geo.boundingBox.max.y.toFixed(3), hasColor: !!c, lo, hi,
+}));
+""", _LIBS)
+ assert out["draws"] == 1, out # harmonised, so still ONE draw
+ assert out["tris"] == 24, out # and both boxes are there
+ assert out["top"] == 2.5, out # including the one 2 m up
+ # The geometry that had no colour is filled with white, not with black:
+ # a vertexColors material reads a missing attribute as zero and the part
+ # renders black.
+ assert out["lo"] == pytest.approx(0.4), out
+ assert out["hi"] == pytest.approx(1.0), out
+
+
+def test_the_scatter_is_seeded_leaves_gaps_and_varies_every_copys_shape():
+ """The reference's two placement tests, measured: same PRNG, same field;
+ `skip` empties a street; and every copy is its own shape, because a city
+ that instanced 4.8x more geometry scored the same coverage_density when
+ the judge saw identical towers."""
+ out = measure(_ASSET + """
+import { scatterGrid } from './lib/instancing.js';
+const area = { x: 0, z: 0, w: 60, d: 40 };
+const field = (seed, opts) => scatterGrid(area, 5, prng(seed), opts || {});
+const key = (f) => JSON.stringify(f.map((p) => [p.position, p.rotationY, p.scale]));
+const full = field(3, { heightVar: 0.5, widthVar: 0.2 });
+const street = field(3, { heightVar: 0.5, widthVar: 0.2,
+ skip: (x, z) => Math.abs(z) < 6 });
+const ground = field(3, { height: (x, z) => 0.1 * x - 0.05 * z });
+console.log(JSON.stringify({
+ same: key(field(3)) === key(field(3)),
+ differ: key(field(3)) !== key(field(9)),
+ n: full.length, streetN: street.length,
+ inStreet: street.filter((p) => Math.abs(p.position[2]) < 6).length,
+ onGround: full.every((p) => p.position[1] === 0)
+ && ground.every((p) => Math.abs(p.position[1] - (0.1 * p.position[0]
+ - 0.05 * p.position[2])) < 1e-12),
+ inside: full.every((p) => Math.abs(p.position[0]) <= 30 + 2.5
+ && Math.abs(p.position[2]) <= 20 + 2.5),
+ height: stat(full.map((p) => p.scale[1])),
+ width: stat(full.map((p) => p.scale[0])),
+ squareLocked: full.every((p) => p.scale[0] === p.scale[2]),
+ uniform: stat(field(3, {}).map((p) => p.scale)),
+}));
+""", _LIBS)
+ assert out["same"] and out["differ"], out
+ assert out["n"] == 12 * 8, out
+ assert out["inStreet"] == 0 and out["streetN"] < out["n"], out
+ assert out["onGround"] and out["inside"], out
+ # Height and width vary INDEPENDENTLY — one scalar per copy is a model
+ # repeated at N sizes, which reads as the same model.
+ assert out["height"]["uniq"] > 0.95 * out["n"], out
+ assert out["width"]["uniq"] > 0.95 * out["n"], out
+ assert out["height"]["max"] - out["height"]["min"] > 0.9, out
+ assert out["width"]["max"] - out["width"]["min"] < 0.7, out
+ # X and Z stretch independently too, so the footprint is not a square
+ # scaled N ways either.
+ assert out["squareLocked"] is False, out
+ # scaleVar alone still yields one number per copy.
+ assert out["uniform"]["sd"] > 0.03 and out["uniform"]["max"] < 1.15, out
+
+
+def test_clearance_keeps_two_copies_out_of_the_same_cubic_metre():
+ """PORT FIX. Jitter and scaleVar are independent of spacing, so a jittered
+ grid puts copies inside each other — measured on the showcase hamlet,
+ two roofs of fifteen z-fought as one striped surface. `clearance` is the
+ minimum centre distance a kept copy is given."""
+ out = measure(_ASSET + """
+import { scatterGrid } from './lib/instancing.js';
+const closest = (f) => {
+ let m = 1e9;
+ for (let i = 0; i < f.length; i++) {
+ for (let j = i + 1; j < f.length; j++) {
+ const a = f[i].position, b = f[j].position;
+ m = Math.min(m, Math.hypot(a[0] - b[0], a[2] - b[2]));
+ }
+ }
+ return m;
+};
+const opts = { jitter: 0.9 };
+const loose = scatterGrid({ x: 0, z: 0, w: 60, d: 40 }, 5, prng(4), opts);
+const spaced = scatterGrid({ x: 0, z: 0, w: 60, d: 40 }, 5, prng(4),
+ { ...opts, clearance: 4.2 });
+console.log(JSON.stringify({
+ loose: { n: loose.length, min: +closest(loose).toFixed(4) },
+ spaced: { n: spaced.length, min: +closest(spaced).toFixed(4) },
+}));
+""", _LIBS)
+ assert out["loose"]["min"] < 4.2, out
+ assert out["spaced"]["min"] >= 4.2, out
+ # It thins the field rather than moving copies: a moved copy is no longer
+ # on the grid the caller asked for.
+ assert out["spaced"]["n"] < out["loose"]["n"], out
+ assert out["spaced"]["n"] > 0.5 * out["loose"]["n"], out
+
+
+def test_yaw_can_face_a_street_instead_of_spinning_freely():
+ """PORT FIX. A hamlet of buildings at uniformly random yaw reads as
+ debris; `yaw: Math.PI / 2` snaps every copy to a quarter turn, with a
+ little slop so the row is hand-laid and not CAD."""
+ out = measure(_ASSET + """
+import { scatterGrid } from './lib/instancing.js';
+const yaws = (opt, extra) => scatterGrid({ x: 0, z: 0, w: 60, d: 40 }, 5,
+ prng(6), { yaw: opt, ...(extra || {}) }).map((p) => p.rotationY);
+const snap = yaws(Math.PI / 2);
+const off = snap.map((y) => {
+ const k = Math.round(y / (Math.PI / 2));
+ return Math.abs(y - k * (Math.PI / 2));
+});
+console.log(JSON.stringify({
+ free: stat(yaws(true)), zero: yaws(false).every((y) => y === 0),
+ slots: new Set(snap.map((y) => Math.round(y / (Math.PI / 2)))).size,
+ worstOff: Math.max(...off), anyOff: off.filter((v) => v > 1e-9).length,
+ rigid: Math.max(...yaws(Math.PI / 2, { yawJitter: 0 }).map((y) => {
+ const k = Math.round(y / (Math.PI / 2));
+ return Math.abs(y - k * (Math.PI / 2));
+ })),
+ n: snap.length,
+}));
+""", _LIBS)
+ assert out["zero"], out
+ assert out["free"]["max"] > 6.0 and out["free"]["uniq"] > 0.95 * out["n"], out
+ assert out["slots"] == 4, out
+ # Slop, not sloppiness: 2 degrees, and every copy gets some.
+ assert out["worstOff"] <= 0.035 + 1e-12, out
+ assert out["anyOff"] == out["n"], out
+ assert out["rigid"] < 1e-12, out
+
+
+def test_every_copy_gets_its_own_albedo_and_the_field_keeps_its_own():
+ """PORT FIX, and the aesthetic one. One prototype means one colour, and a
+ field of thirty identical roof reds reads flat however much the
+ silhouettes vary. The tint is a LINEAR multiplier: its mean leaves the
+ authored albedo where the author put it (0.96 of it — a copy that has
+ stood in weather is darker more often than brighter) and what it adds is
+ SPREAD."""
+ out = measure(_ASSET + """
+import { scatterGrid } from './lib/instancing.js';
+const field = (tint) => scatterGrid({ x: 0, z: 0, w: 200, d: 200 }, 5,
+ prng(5), tint === undefined ? {} : { tint });
+const cols = field().map((p) => p.color);
+const chan = [0, 1, 2].map((i) => stat(cols.map((c) => c[i])));
+const lum = stat(cols.map((c) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]));
+// A saturated red must stay red: a hue ROTATION drives the small channels
+// negative and the clamp forks one swing into two lobes.
+const red = new THREE.Color(0xb4231a);
+const stillRed = cols.every((c) => red.r * c[0] > red.g * c[1] * 1.5
+ && red.r * c[0] > red.b * c[2] * 1.5);
+const spread = (hex) => {
+ const base = new THREE.Color(hex);
+ const hues = cols.map((c) => {
+ const o = {};
+ new THREE.Color(base.r * c[0], base.g * c[1], base.b * c[2])
+ .getHSL(o, THREE.SRGBColorSpace);
+ return o.h * 360;
+ }).sort((a, b) => a - b);
+ return +(hues[Math.floor(0.95 * hues.length)]
+ - hues[Math.floor(0.05 * hues.length)]).toFixed(2);
+};
+console.log(JSON.stringify({
+ n: cols.length, chan, lum, stillRed,
+ hueRed: spread(0xb4231a), hueLeaf: spread(0x4e6b2f),
+ hueStone: spread(0xb9a891),
+ isArray: Array.isArray(cols[0]),
+ off: field(false).filter((p) => p.color !== undefined).length,
+ half: stat(field(0.5).map((c) => c.color[0])),
+ custom: stat(field({ chroma: 0, value: 0.3 }).map((c) => c.color[0] - c.color[2])),
+}));
+""", _LIBS)
+ assert out["n"] > 1500, out
+ assert out["isArray"], out # linear triple, not a hex
+ assert out["off"] == 0, out
+ for c in out["chan"]:
+ assert c["mean"] == pytest.approx(0.96, abs=0.02), out
+ assert c["min"] >= 0.5 and c["max"] <= 1.35, out
+ assert c["sd"] > 0.05, out
+ assert out["lum"]["mean"] == pytest.approx(0.96, abs=0.02), out
+ # The swing runs along warm-cool, so how far a base MOVES in hue depends
+ # on where it already sits: a near-primary red is on that axis already and
+ # spends the swing on saturation instead (2.3 deg), a leaf green crosses
+ # it (13.8), a near-neutral stone moves furthest for the least perceived
+ # change (28.6). The canopy work's benchmark is 9.4 deg across one crown,
+ # against 25-45 in a photograph.
+ assert out["stillRed"], out
+ assert 1.0 < out["hueRed"] < 8, out
+ assert 8 < out["hueLeaf"] < 22, out
+ assert 18 < out["hueStone"] < 45, out
+ # A scalar scales the whole thing; chroma 0 leaves a pure value swing.
+ assert out["half"]["sd"] < 0.6 * out["chan"][0]["sd"], out
+ assert abs(out["custom"]["max"]) < 1e-12, out
+ assert out["custom"]["uniq"] == 1, out
+
+
+def test_the_tint_reaches_the_instances_in_the_space_it_was_written_in():
+ """`setColorAt` writes the working (linear) space, and three multiplies the
+ albedo by it off `USE_INSTANCING_COLOR` alone — no `vertexColors` needed.
+ A hex goes through the sRGB transfer on the way in, which is why the
+ scatter emits an array: `0x808080` as a "half" tint is a quarter."""
+ out = measure(_ASSET + """
+import { instanceAsset, scatterGrid } from './lib/instancing.js';
+const read = (mesh, i) => { const c = new THREE.Color(); mesh.getColorAt(i, c);
+ return [c.r, c.g, c.b].map((v) => +v.toFixed(6)); };
+const placed = scatterGrid({ x: 0, z: 0, w: 30, d: 30 }, 6, prng(2));
+const g = instanceAsset(cottage, placed);
+const hexed = instanceAsset(cottage, [{ position: [0, 0, 0], color: 0x808080 },
+ { position: [3, 0, 0] }]);
+const plain = instanceAsset(cottage, [{ position: [0, 0, 0] }]);
+console.log(JSON.stringify({
+ everyPart: g.children.every((m) => !!m.instanceColor),
+ needsNoVertexColors: g.children.every((m) => m.material.vertexColors !== true),
+ asWritten: [0, 1, 2].map((i) => [read(g.children[0], i), placed[i].color
+ .map((v) => +v.toFixed(6))]),
+ hex: read(hexed.children[0], 0),
+ untinted: read(hexed.children[0], 1),
+ none: plain.children[0].instanceColor,
+}));
+""", _LIBS)
+ assert out["everyPart"] and out["needsNoVertexColors"], out
+ for got, want in out["asWritten"]:
+ assert got == want, out
+ # 0x808080 is 0.2158 linear, not 0.5: the trap the docstring names.
+ assert out["hex"][0] == pytest.approx(0.2158605, abs=1e-5), out
+ # An untinted copy in a tinted batch stays at 1, not at 0 (black).
+ assert out["untinted"] == [1.0, 1.0, 1.0], out
+ assert out["none"] is None, out
diff --git a/harness/tests/scene_runtime/lib/test_lights.py b/harness/tests/scene_runtime/lib/test_lights.py
new file mode 100644
index 00000000..a7abf799
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_lights.py
@@ -0,0 +1,347 @@
+"""lights.js: panel lights ship init-fused, pre-aimed, and un-settleable.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_lights_lib.py). The reference's claims are kept — RectAreaLight
+renders BLACK without one-time LTC init, emits along local -Z, and needs a
+glow mesh — and three things this port had to add are pinned with them,
+because each one was a defect measured on OUR host, not a style preference:
+
+1. COLOUR SPACE. The Tanner Helland fit is an 8-bit *sRGB* triple and the
+ reference handed it to `new THREE.Color(r, g, b)`, which writes its
+ arguments into three's srgb-linear working space RAW. Every class came out
+ washed toward white: rendered through our pipeline the tungsten window read
+ (158,152,145) — a grey card — and the fluorescent shop, the LED sign and the
+ tungsten window were three copies of the same panel, which is precisely the
+ "class SPLIT" the module exists to sell. A hex colour already takes the
+ sRGB decode inside three, so the fit had to as well; measured after,
+ tungsten reads (239,205,148), saturation 0.176 -> 0.380.
+
+2. SETTLE. This host seats floating assets on the ground before the first
+ frame (runtime_js/lib/host_placement.mjs). A `PanelLight` is a group of
+ meshes that floats by definition, so a window panel authored at y=4.4 on a
+ wall was moved to y=0.60 — its own half-height — and rendered lying at the
+ kerb. `userData.placement = 'free'` is the documented opt-out and a
+ luminaire is exactly what it is for.
+
+3. NO POST CHAIN. There is no bloom pass here, so the panel has to carry its
+ own glow: an emissiveMap that keeps the rim off zero (a rim at zero uncovers
+ the dark base colour and draws a black bezel round every lamp) and an
+ additive spill quad *behind* the panel, where the depth test leaves only the
+ halo outside its edge.
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("lights.js",)
+
+
+def _measure(script: str) -> dict:
+ return measure(script, _LIBS)
+
+
+_PROBE = """
+import * as THREE from 'three';
+import { makePanelLight, initRectAreaLights } from './lib/lights.js';
+
+// LTC must be absent until the FIRST makePanelLight auto-inits it.
+const before = !!(THREE.UniformsLib.LTC_FLOAT_1);
+const g = makePanelLight(4, 2);
+const after = !!(THREE.UniformsLib.LTC_FLOAT_1);
+const ref1 = THREE.UniformsLib.LTC_FLOAT_1;
+initRectAreaLights();
+initRectAreaLights();
+const stable = THREE.UniformsLib.LTC_FLOAT_1 === ref1;
+
+const light = g.userData.light;
+const panel = g.userData.panel;
+const halo = g.userData.halo;
+
+// Aiming contract: group.lookAt(target) must point the EMISSION
+// (the raw light's local -Z) at the target.
+const scene = new THREE.Scene();
+scene.add(g);
+g.position.set(0, 0, 0);
+g.lookAt(new THREE.Vector3(0, 0, 7));
+scene.updateMatrixWorld(true);
+const m = light.matrixWorld.elements;
+const emission = new THREE.Vector3(-m[8], -m[9], -m[10]).normalize();
+const aimDot = emission.dot(new THREE.Vector3(0, 0, 1));
+
+const custom = makePanelLight(3, 1, 0xffdca8, 11, { glow: 4 });
+const bare = makePanelLight(2, 2, 0xffffff, 6, { panel: false });
+const plain = makePanelLight(2, 1, 'sodium', 8, { halo: false });
+
+// the emissive map is the diffuser profile: flat core, rim held off zero
+const tex = panel.material.emissiveMap;
+const N = tex.image.width;
+const at = (u, v) => tex.image.data[((v * N + u) * 4)] / 255;
+
+console.log(JSON.stringify({
+ before, after, stable,
+ isRect: light.isRectAreaLight === true,
+ w: light.width, h: light.height,
+ color: light.color.getHex(),
+ intensity: light.intensity,
+ aimDot,
+ free: g.userData.placement,
+ panelThere: !!panel,
+ panelBehind: panel.position.z < 0 && panel.position.z > -0.05,
+ glowHex: panel.material.emissive.getHex(),
+ glowI: panel.material.emissiveIntensity,
+ panelW: panel.geometry.parameters.width,
+ panelH: panel.geometry.parameters.height,
+ baseLin: panel.material.color.r,
+ roughness: panel.material.roughness,
+ texShared: makePanelLight(1, 1).userData.panel.material.emissiveMap === tex,
+ texLinear: tex.colorSpace === THREE.NoColorSpace,
+ texCore: at(N >> 1, N >> 1),
+ texRim: at(0, N >> 1),
+ texMid: at(Math.round(N * 0.88), N >> 1),
+ // dither: an undithered smoothstep row is MONOTONE, so count the
+ // sign changes along it — jitter is the only thing that makes any.
+ texFlips: (() => {
+ let f = 0, prev = 0;
+ for (let u = 1; u < N; u++) {
+ const d = at(u, N >> 1) - at(u - 1, N >> 1);
+ if (d === 0) continue;
+ if (prev !== 0 && Math.sign(d) !== prev) f++;
+ prev = Math.sign(d);
+ }
+ return f;
+ })(),
+ haloThere: !!halo,
+ haloBehindPanel: halo.position.z < panel.position.z,
+ haloAdditive: halo.material.blending === THREE.AdditiveBlending,
+ haloDepthWrite: halo.material.depthWrite,
+ haloFog: halo.material.fog,
+ haloOpacity: halo.material.opacity,
+ haloHex: halo.material.color.getHex(),
+ haloW: halo.geometry.parameters.width,
+ haloH: halo.geometry.parameters.height,
+ customColor: custom.userData.light.color.getHex(),
+ customI: custom.userData.light.intensity,
+ customGlowHex: custom.userData.panel.material.emissive.getHex(),
+ customGlowI: custom.userData.panel.material.emissiveIntensity,
+ bareNoPanel: bare.userData.panel === null,
+ bareNoHalo: bare.userData.halo === null,
+ plainNoHalo: plain.userData.halo === null,
+ plainHasPanel: !!plain.userData.panel,
+ name: g.name,
+}));
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch of _PROBE, shared by every test that reads it."""
+ return _measure(_PROBE)
+
+
+def test_ltc_init_is_automatic_and_runs_exactly_once(probe):
+ """Without RectAreaLightUniformsLib.init() the light renders black
+ with no error; the wrapper installs it on first use and must never
+ rebuild the LTC tables on later calls."""
+ m = probe
+ assert not m["before"], "probe invalid: LTC preexisted"
+ assert m["after"], "makePanelLight did not init LTC"
+ assert m["stable"], "second init rebuilt the LTC tables"
+
+
+def test_group_lookat_aims_the_emission_at_the_target(probe):
+ """RectAreaLight emits along local -Z while lookAt aims +Z; the
+ wrapper pre-rotates so group.lookAt(target) points the EMISSION at
+ the target — lose the flip and windows light the wrong wall."""
+ m = probe
+ assert m["aimDot"] > 0.999, f"emission misaimed: dot={m['aimDot']}"
+
+
+def test_light_and_glow_panel_agree_and_options_are_alive(probe):
+ """Fused contract: the panel carries the light's colour, sits just
+ behind the emitting plane at its exact size, and every documented
+ option reaches the objects — else glow and cast light disagree."""
+ m = probe
+ assert m["isRect"] and (m["w"], m["h"]) == (4, 2), m
+ assert m["color"] == 0xffffff and m["intensity"] == 6, \
+ f"measured defaults drifted: {m['color']:x}/{m['intensity']}"
+ assert m["panelThere"] and m["panelBehind"], m
+ assert (m["panelW"], m["panelH"]) == (4, 2), "panel != light size"
+ assert m["glowHex"] == 0xffffff and m["glowI"] == 2.2, m
+ assert m["customColor"] == 0xffdca8 and m["customI"] == 11, m
+ assert m["customGlowHex"] == 0xffdca8 and m["customGlowI"] == 4, m
+ assert m["bareNoPanel"], "panel:false still built a panel"
+ assert m["bareNoHalo"], "panel:false left an orphan halo"
+ assert m["name"] == "PanelLight"
+
+
+def test_the_panel_is_exempt_from_the_host_settle_pass(probe):
+ """A luminaire hangs where the author hung it. This host seats
+ floating assets before the first frame, and a PanelLight floats by
+ definition: unmarked, a 1.5x1.2 window authored at y=4.4 came back
+ at y=0.60 (its own half-height) and rendered lying at the kerb."""
+ assert probe["free"] == "free", \
+ "userData.placement lost — the host will settle panels to the ground"
+
+
+def test_the_diffuser_map_is_a_shared_linear_profile_that_never_hits_zero(probe):
+ """No bloom pass here, so the panel's own falloff is the glow. The
+ map must be a LINEAR multiplier (a decoded sRGB one would lift the
+ rim and flatten the core), one texture across every panel, and its
+ rim must stay off zero: a rim at zero uncovers the dark base colour
+ and draws a black bezel around every lamp in the scene."""
+ m = probe
+ assert m["texLinear"], "emissiveMap would be sRGB-decoded"
+ assert m["texShared"], "a new diffuser texture per panel light"
+ assert m["texCore"] > 0.9, m["texCore"]
+ assert 0.25 < m["texRim"] < 0.45, f"rim {m['texRim']}: bezel or no falloff"
+ assert m["texMid"] < m["texCore"], "no roll-off at all"
+ assert m["texFlips"] > 4, \
+ f"monotone ramp ({m['texFlips']} flips) — an 8-bit gradient that bands"
+
+
+def test_the_halo_is_additive_spill_hidden_behind_its_own_panel(probe):
+ """The spill quad sits BEHIND the panel so the depth test hides its
+ blown centre and leaves only the glow around the edges; additive and
+ fog-exempt, because additive fog ADDS the fog colour instead of
+ fading the glow into it."""
+ m = probe
+ assert m["haloThere"] and m["haloBehindPanel"], m
+ assert m["haloAdditive"] and not m["haloDepthWrite"], m
+ assert m["haloFog"] is False, "additive halo would add the fog colour"
+ assert m["haloOpacity"] == 0.6, m["haloOpacity"]
+ assert m["haloHex"] == m["glowHex"], "halo disagrees with the light"
+ assert m["haloW"] > m["panelW"] and m["haloH"] > m["panelH"], m
+ # aspect kept: a 4x2 panel must not get a square halo
+ assert m["haloW"] > m["haloH"], m
+ assert m["plainNoHalo"] and m["plainHasPanel"], "halo:false killed the panel"
+
+
+def test_light_classes_separate_and_order_by_temperature():
+ """The realism of a night street is its light classes SEPARATING —
+ sodium amber, tungsten homes, fluorescent shops, cool LED. So the
+ class table must actually order by temperature (red/blue ratio
+ falls as kelvin rises), the classes a scene mixes must be visibly
+ apart, and 'moon' must lean blue: moonlight photographs blue, and a
+ black-body 4100 K would hand a night scene a WARM moon."""
+ out = _measure("""
+import { kelvinColor, LIGHT_CLASSES, makePanelLight }
+ from './lib/lights.js';
+const ratio = (c) => c.r / Math.max(c.b, 1e-4);
+const classes = {};
+for (const [k, v] of Object.entries(LIGHT_CLASSES)) {
+ classes[k] = { kelvin: v.kelvin, ratio: ratio(v.color),
+ hex: v.color.getHexString() };
+}
+const shop = makePanelLight(2, 1, 'fluorescent');
+console.log(JSON.stringify({
+ classes,
+ k2000: ratio(kelvinColor(2000)),
+ k6500: ratio(kelvinColor(6500)),
+ clampLow: kelvinColor(200).getHexString()
+ === kelvinColor(1000).getHexString(),
+ panelHex: shop.userData.light.color.getHexString(),
+ fluorHex: LIGHT_CLASSES.fluorescent.color.getHexString(),
+ moonBlue: LIGHT_CLASSES.moon.color.b > LIGHT_CLASSES.moon.color.r,
+}));
+""")
+ cl = out["classes"]
+ # Warmer class, higher red/blue ratio — strictly, through the range.
+ order = ["sodium", "tungsten", "halogen", "fluorescent",
+ "metal_halide", "led_cool"]
+ ratios = [cl[k]["ratio"] for k in order]
+ assert all(a > b for a, b in zip(ratios, ratios[1:], strict=False)), cl
+ # The two classes one street mixes must be visibly apart. The
+ # reference put led_cool under 1.05; decoding the fit from sRGB
+ # deepens every ratio (its own point), and 6300 K lands at 1.10.
+ assert cl["sodium"]["ratio"] > 2.5, cl
+ assert cl["led_cool"]["ratio"] < 1.15, cl
+ assert out["k2000"] > out["k6500"], out
+ assert out["clampLow"], out
+ # A class NAME is a colour anywhere a colour goes.
+ assert out["panelHex"] == out["fluorHex"], out
+ assert out["moonBlue"], out
+
+
+def test_the_kelvin_fit_is_decoded_from_srgb_like_every_other_colour():
+ """The fit is an 8-bit sRGB triple. Written raw into three's
+ srgb-linear working space it states a gamma-encoded value as a
+ linear one and every class washes toward white — measured on our
+ renderer, the tungsten window panel read (158,152,145), a grey card
+ beside a fluorescent one that read (218,215,214). A hex colour
+ takes the decode inside three, so the fit must take it too or the
+ module's two colour paths disagree with each other.
+
+ The floor exists for the same reason: below 1900 K the fit snaps
+ blue to a hard 0, a discontinuity in the fit rather than physics,
+ and a dead channel makes a sodium pool clip to a pure hue and band.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { kelvinColor, LIGHT_CLASSES } from './lib/lights.js';
+// The Helland fit for 2700 K, in the 0-255 sRGB the formula produces.
+const t = 27;
+const raw = [255,
+ 99.4708025861 * Math.log(t) - 161.1195681661,
+ 138.5177312231 * Math.log(t - 10) - 305.0447927307];
+const asLinear = new THREE.Color().setRGB(
+ raw[0] / 255, raw[1] / 255, raw[2] / 255, THREE.SRGBColorSpace);
+const c = kelvinColor(2700);
+// the hex path, which three has always decoded
+const hex = new THREE.Color(0xffffff);
+const white = kelvinColor(6600);
+console.log(JSON.stringify({
+ decoded: [c.r, c.g, c.b],
+ expect: [asLinear.r, asLinear.g, asLinear.b],
+ hexWhiteR: hex.r,
+ whiteR: white.r,
+ sodiumB: LIGHT_CLASSES.sodium.color.b,
+ moonR: LIGHT_CLASSES.moon.color.r,
+}));
+""")
+ got, want = out["decoded"], out["expect"]
+ assert all(abs(a - b) < 1e-4 for a, b in zip(got, want, strict=True)), (got, want)
+ # the decode is what deepens the colour: raw, green would sit at 0.65
+ assert got[1] < 0.45, f"2700 K green {got[1]:.3f} — fit written raw"
+ # white still means white on both paths, so the default is unmoved
+ assert abs(out["whiteR"] - out["hexWhiteR"]) < 1e-6, out
+ # no dead channel anywhere in the table
+ assert 0 < out["sodiumB"] < 0.01, out["sodiumB"]
+ # moon was ALREADY a hex and must not have moved
+ assert abs(out["moonR"] - 0.4620) < 5e-3, out["moonR"]
+
+
+_SCENE = """
+import * as THREE from 'three';
+import { makePanelLight } from './lib/lights.js';
+export const BOUNDS = { min: [-8, 0, -8], max: [8, 8, 8] };
+export function heightAt() { return 0; }
+export async function createScene() {
+ const scene = new THREE.Scene();
+ const wall = new THREE.Mesh(new THREE.BoxGeometry(6, 4, 0.3),
+ new THREE.MeshStandardMaterial({ color: 0x8a8378, roughness: 0.9 }));
+ wall.position.set(0, 2, -2);
+ scene.add(wall);
+ const shop = makePanelLight(2.4, 1.2, 'fluorescent', 9);
+ shop.position.set(0, 2.2, -1.6);
+ shop.lookAt(0, 1.6, 4);
+ scene.add(shop);
+ const fill = makePanelLight(3, 2, 'tungsten', 5, { panel: false });
+ fill.position.set(2, 2, 2);
+ fill.lookAt(0, 2, -2);
+ scene.add(fill);
+ const cameras = [{ name: 'a', position: [0, 2, 5], lookAt: [0, 2, -2], fov: 45 }];
+ return { scene, cameras, update() {} };
+}
+"""
+
+
+def test_a_panel_light_compiles_on_the_gpu():
+ """RectAreaLight is its own shader permutation (the LTC path), and a
+ missing LTC table is silent — black, no error. Boot a lit scene
+ headless so the permutation is proved to build on this host.
+ """
+ code, out = compile_scene(_SCENE, _LIBS, timeout_s=120.0)
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_materials.py b/harness/tests/scene_runtime/lib/test_materials.py
new file mode 100644
index 00000000..df13aeaa
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_materials.py
@@ -0,0 +1,187 @@
+"""materials.js — one material per look, dark albedos never black, dielectric water/glass.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference (test_material_cache.py,
+test_material_dark_albedo.py, test_dielectric_materials.py). The aesthetic brief's
+albedo band (non-emissive 0.02..0.8 linear) and the hue-break contract are pinned here.
+"""
+from __future__ import annotations
+
+import re
+
+import pytest
+from _probe import LIB_DIR, measure
+
+pytestmark = pytest.mark.node
+
+_CACHE = """
+import * as MAT from './lib/materials.js';
+const mats = new Set(), tex = new Set();
+for (let i = 0; i < 2552; i++) {
+ const m = MAT.plaster({ variant: (i * 0.37) % 1, color: 0xd8cfc0 });
+ mats.add(m.uuid);
+ for (const s of ['map', 'roughnessMap']) if (m[s]) tex.add(m[s].uuid);
+}
+const seeded = new Set(), seededTex = new Set();
+for (let i = 0; i < 500; i++) {
+ const m = MAT.foliage({ color: 0x3d662f, scale: 16, seed: 40 + i * 7 });
+ seeded.add(m.uuid);
+ for (const s of ['map', 'roughnessMap']) if (m[s]) seededTex.add(m[s].uuid);
+}
+const a = MAT.brick({ variant: 0.5 });
+const before = a.color.getHex();
+const w = MAT.weather(a, 0.5);
+const t1 = MAT.tint(a, 0.2), t2 = MAT.tint(a, 0.2), t3 = MAT.tint(a, 0.9);
+console.log(JSON.stringify({ fabricMaterials: mats.size, fabricTextures: tex.size,
+ seededMaterials: seeded.size, seededTextures: seededTex.size,
+ sharesOnIdenticalOptions: a === MAT.brick({ variant: 0.5 }),
+ differsOnDistantVariant: a !== MAT.brick({ variant: 0.0 }),
+ weatherCopies: w !== a, weatherLeftOriginal: a.color.getHex() === before,
+ weatherRougher: w.roughness > a.roughness,
+ tintPooled: t1 === t2 && t1 !== t3 && t1 !== a,
+ uniqueIsFresh: MAT.brick({ unique: true }) !== MAT.brick({ unique: true }) }));
+"""
+
+
[email protected](scope="module")
+def cache() -> dict:
+ return measure(_CACHE, ("materials.js",))
+
+
+def test_a_city_of_one_look_costs_one_material_bucket(cache):
+ """2 552 plaster calls at jittered variants collapse to the 9 variant buckets
+ (and their texture pairs), not 2 552 materials / 1 309 textures."""
+ assert cache["fabricMaterials"] <= 9, cache
+ assert cache["fabricTextures"] <= 18, cache
+
+
+def test_a_per_copy_seed_does_not_buy_a_per_copy_texture(cache):
+ assert cache["seededMaterials"] <= 6 and cache["seededTextures"] <= 12, cache
+
+
+def test_identical_options_share_and_mutators_copy(cache):
+ assert cache["sharesOnIdenticalOptions"] and cache["differsOnDistantVariant"]
+ assert cache["weatherCopies"] and cache["weatherLeftOriginal"] and cache["weatherRougher"]
+ assert cache["tintPooled"] and cache["uniqueIsFresh"]
+
+
+_ALBEDO = """
+import * as MAT from './lib/materials.js';
+const L = (c) => 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
+const sr = (c) => c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
+const authored = (h) => 0.2126 * sr((h >> 16) / 255) + 0.7152 * sr(((h >> 8) & 255) / 255) + 0.0722 * sr((h & 255) / 255);
+const out = {};
+out.conifer = L(MAT.foliage({ color: 0x163e23, seed: 7 }).color);
+out.trunk = L(MAT.weatheredWood({ color: 0x3a2518, seed: 7 }).color);
+out.near_black = L(MAT.foliage({ color: 0x040604, seed: 7 }).color);
+out.snow = L(MAT.plaster({ color: 0xf4f7fb, seed: 7 }).color);
+out.v0 = L(MAT.foliage({ color: 0x163e23, seed: 7, variant: 0 }).color);
+out.v1 = L(MAT.foliage({ color: 0x163e23, seed: 7, variant: 1 }).color);
+out.authored_conifer = authored(0x163e23);
+out.authored_snow = authored(0xf4f7fb);
+// Every factory default albedo in the brief's band, 0.02..0.8 linear.
+const names = ['plaster','brick','travertine','granite','cobble','asphalt','terracotta','weatheredWood',
+ 'paintedWood','paintedIron','brushedSteel','giltBronze','fabric','foliage','soil','skin'];
+out.albedos = {};
+for (const n of names) out.albedos[n] = L(MAT[n]().color);
+// The map carries a HUE break, not only value: a granite map's texels
+// must spread in R-B difference, not just brightness.
+const map = MAT.granite().map.image.data;
+let rb = 0, n = 0;
+for (let i = 0; i < map.length; i += 4 * 97) { rb += Math.abs(map[i] - map[i + 2]); n++; }
+out.granite_rb = rb / n;
+const mapPaint = MAT.brushedSteel().map.image.data;
+rb = 0; n = 0;
+for (let i = 0; i < mapPaint.length; i += 4 * 97) { rb += Math.abs(mapPaint[i] - mapPaint[i + 2]); n++; }
+out.steel_rb = rb / n;
+// Water and glass are dielectrics with an IOR fresnel; water dark, glass transparent.
+const w = MAT.water(), g = MAT.glass();
+out.water = { metalness: w.metalness, ior: w.ior, physical: !!w.isMeshPhysicalMaterial, opaque: !w.transparent };
+out.glass = { metalness: g.metalness, ior: g.ior, transparent: g.transparent, opacity: g.opacity };
+// SEAMS: a repeated map whose lattice does not wrap shows a hard line at
+// every tile edge. Compare the wrap-edge step (last column against the
+// first) with an interior step of the same texture: a seamless field makes
+// them the same size, an unwrapped one makes the wrap ~12x bigger.
+const seam = (o) => {
+ const t = MAT.noiseTexture(o), d = t.image.data, n = t.image.width;
+ let wrapX = 0, innerX = 0, wrapY = 0, innerY = 0;
+ for (let y = 0; y < n; y++) {
+ wrapX += Math.abs(d[(y * n + n - 1) * 4] - d[y * n * 4]);
+ innerX += Math.abs(d[(y * n + n / 2 - 1) * 4] - d[(y * n + n / 2) * 4]);
+ }
+ for (let x = 0; x < n; x++) {
+ wrapY += Math.abs(d[((n - 1) * n + x) * 4] - d[x * 4]);
+ innerY += Math.abs(d[(n / 2 - 1) * n * 4 + x * 4] - d[(n / 2) * n * 4 + x * 4]);
+ }
+ return { wrapX: wrapX / n, innerX: innerX / n, wrapY: wrapY / n, innerY: innerY / n };
+};
+out.seams = {
+ soil: seam({ scale: 20, seed: 3, contrast: 0.4, hueBreak: 0.18 }),
+ wood: seam({ scale: 8, seed: 5, contrast: 0.4, streak: 0.9 }),
+ steel: seam({ scale: 18, seed: 2, contrast: 0.12, streak: 0.95 }),
+ rough: seam({ scale: 34, seed: 50, contrast: 0.5, linear: true }),
+ fractional: seam({ scale: 10.2, seed: 8, contrast: 0.5 }),
+};
+// The field still averages the authored colour after the wrap.
+const meanOf = (o) => { const d = MAT.noiseTexture(o).image.data; let s = 0, n = 0;
+ for (let i = 0; i < d.length; i += 4) { s += d[i]; n++; } return s / n / 255; };
+out.means = { soil: meanOf({ scale: 20, seed: 3, contrast: 0.4 }),
+ plain: meanOf({ scale: 6, seed: 1, contrast: 0.3 }) };
+console.log(JSON.stringify(out));
+"""
+
+
[email protected](scope="module")
+def albedo() -> dict:
+ return measure(_ALBEDO, ("materials.js",))
+
+
+def test_a_dark_authored_colour_is_never_black(albedo):
+ assert albedo["conifer"] > 0.5 * albedo["authored_conifer"], albedo
+ assert albedo["trunk"] > 0.004 and albedo["near_black"] > 0.0004, albedo
+
+
+def test_a_bright_colour_is_still_reproduced_and_variant_spreads(albedo):
+ assert albedo["snow"] > 0.8 * albedo["authored_snow"], albedo
+ assert albedo["v1"] > albedo["v0"], albedo
+
+
+def test_every_factory_albedo_sits_in_the_linear_sane_band(albedo):
+ bad = {k: v for k, v in albedo["albedos"].items() if not (0.02 <= v <= 0.8)}
+ assert not bad, bad
+
+
+def test_mineral_maps_carry_hue_variance_and_finishes_carry_less(albedo):
+ assert albedo["granite_rb"] > 4, albedo["granite_rb"]
+ assert albedo["steel_rb"] < albedo["granite_rb"], albedo
+
+
+def test_water_and_glass_are_dielectrics(albedo):
+ assert albedo["water"]["metalness"] == 0 and abs(albedo["water"]["ior"] - 1.333) < 1e-6
+ assert albedo["water"]["physical"] and albedo["water"]["opaque"]
+ assert albedo["glass"]["metalness"] == 0 and albedo["glass"]["ior"] == 1.5
+ assert albedo["glass"]["transparent"] and 0 < albedo["glass"]["opacity"] < 1
+
+
+def test_every_noise_map_tiles_without_a_seam(albedo):
+ """Measured 2026-09-01: the reference lattice did not wrap, so a soil map's
+ wrap edge stepped 11.83 grey levels against an interior 0.94 — the hard grid
+ lines a 120 m ground at repeat 10 showed as paving joints in the dirt."""
+ for name, s in albedo["seams"].items():
+ assert s["wrapX"] <= max(1.6 * s["innerX"], 1.0), (name, s)
+ assert s["wrapY"] <= max(1.6 * s["innerY"], 1.0), (name, s)
+
+
+def test_the_wrapped_field_still_delivers_the_authored_colour(albedo):
+ """A colour map MULTIPLIES the authored colour, so the field must still
+ average ~0.5 of full scale after the lattice wrap (base 1, so ~0.93 here)."""
+ for name, m in albedo["means"].items():
+ assert 0.85 <= m <= 1.0, (name, m)
+
+
+def test_the_shipped_source_never_subtracts_a_fixed_lightness_step():
+ src = (LIB_DIR / "materials.js").read_text(encoding="utf-8")
+ code = "\n".join(ln.split("//")[0] for ln in src.splitlines())
+ assert not re.search(r"Math\.random\s*\(", code)
+ assert "hsl.l * 0.5" in code, "shade() must scale lightness as a ratio"
+ water = code[code.index("export const water"):code.index("export const glass")]
+ assert "metalness: 0," in water and not re.search(r"metalness:\s*0\.[1-9]", water)
diff --git a/harness/tests/scene_runtime/lib/test_merge.py b/harness/tests/scene_runtime/lib/test_merge.py
new file mode 100644
index 00000000..3a780a9c
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_merge.py
@@ -0,0 +1,442 @@
+"""merge.js — mergeStatic must collapse placed props into ONE true draw call.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_merge_lib.py). The reference's whole scenario is kept: 300 placed
+boxes, a third of them non-indexed, become one mesh with world matrices and
+material colours baked in; groups are traversed with the parent transform; the
+wrapper fails loud. Draw calls are the same currency on our host (headless
+Chrome falls back to SwiftShader whenever the GPU launch does not take), so
+none of that needed retargeting.
+
+Everything from ``test_the_surface_response_survives_the_merge`` down covers
+what the port CHANGED, all four of them things the showcase render caught:
+
+* the rebuilt material copied only roughness/metalness/flatShading and three
+ maps, so a merged batch lost its ``emissive`` (lantern boxes rendered as dead
+ grey blocks) and its ``side`` (6 of 13 DoubleSide fence slats vanished);
+* a mirrored placement (``scale.x = -1``) baked its flipped winding and
+ rendered as its own interior — three flips winding per draw from a matrix
+ that the bake throws away;
+* ``visible = false`` pieces were baked in permanently;
+* a shader-patched material was silently reduced to a plain standard one, and
+ ``Material.clone()`` would not have saved it (it copies userData but not
+ ``onBeforeCompile`` — a dead chain still holding a live cache key), so the
+ patch chain is replayed onto the merged material over the SOURCE uniform map.
+
+The last test covers the one deliberate look change: ``variance`` (default
+0.12) spreads each piece's baked albedo, because a 40-stone wall cut from one
+material otherwise arrives as a single flat swatch — modal_frac 0.49 of the
+wall region in the before render, 0.17 after.
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("merge.js",)
+
+# The reference's probe: 300 coloured boxes -> one mesh, colours survive.
+# Every third box is non-indexed so the probe also covers the mixed-index
+# unification that mergeGeometries itself refuses. variance is off here: these
+# assertions grade the BAKE, and the spread is graded on its own below.
+_PROBE = """
+import * as THREE from 'three';
+import { mergeStatic } from './lib/merge.js';
+
+const N = 300;
+const boxes = [];
+const cols = [];
+for (let i = 0; i < N; i++) {
+ const c = new THREE.Color().setHSL((i * 0.618033) % 1, 0.7, 0.5);
+ cols.push([c.r, c.g, c.b]);
+ let g = new THREE.BoxGeometry(1, 1, 1);
+ if (i % 3 === 0) g = g.toNonIndexed();
+ const m = new THREE.Mesh(g, new THREE.MeshStandardMaterial({
+ color: c, roughness: 0.6, metalness: 0.1 }));
+ m.position.set((i % 20) * 4 - 38, (i % 5) * 2, Math.floor(i / 20) * 4 - 28);
+ m.rotation.y = i * 0.37;
+ m.scale.setScalar(1 + (i % 7) * 0.25);
+ boxes.push(m);
+}
+const merged = mergeStatic(boxes, { variance: 0 });
+
+// One TRUE draw call: a single mesh, no children, no material array,
+// no geometry groups (each group is its own draw call).
+const oneMesh = !!merged.isMesh && merged.children.length === 0
+ && !Array.isArray(merged.material)
+ && merged.geometry.groups.length === 0;
+
+// mergeGeometries concatenates in input order; with everything
+// unified to non-indexed, each box owns an equal vertex run.
+const pos = merged.geometry.attributes.position;
+const col = merged.geometry.attributes.color;
+const stride = pos.count / N;
+let colOk = 0, posOk = 0, yHalf150 = 0;
+for (const i of [0, 1, 3, 7, 50, 150, 299]) {
+ let dc = 0;
+ const centroid = new THREE.Vector3();
+ for (let v = i * stride; v < (i + 1) * stride; v++) {
+ dc = Math.max(dc,
+ Math.abs(col.getX(v) - cols[i][0]),
+ Math.abs(col.getY(v) - cols[i][1]),
+ Math.abs(col.getZ(v) - cols[i][2]));
+ centroid.add(new THREE.Vector3(pos.getX(v), pos.getY(v), pos.getZ(v)));
+ if (i === 150) {
+ yHalf150 = Math.max(yHalf150,
+ Math.abs(pos.getY(v) - boxes[150].position.y));
+ }
+ }
+ centroid.divideScalar(stride);
+ if (dc < 1e-3) colOk++;
+ if (centroid.distanceTo(boxes[i].position) < 1e-3) posOk++;
+}
+
+// Groups are traversed and PARENT transforms reach the bake.
+const grp = new THREE.Group();
+grp.position.set(100, 0, 0);
+for (const dx of [-2, 0, 2]) {
+ const m = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),
+ new THREE.MeshStandardMaterial({ color: 0x8899aa }));
+ m.position.x = dx;
+ grp.add(m);
+}
+const gm = mergeStatic([grp], { variance: 0 });
+gm.geometry.computeBoundingBox();
+const bb = gm.geometry.boundingBox;
+const groupCenterX = (bb.min.x + bb.max.x) / 2;
+
+// Fail-loud contract: empty input and mesh-less input both throw.
+let threwEmpty = false, threwNoMesh = false;
+try { mergeStatic([]); } catch (e) { threwEmpty = true; }
+try { mergeStatic([new THREE.Group()]); } catch (e) { threwNoMesh = true; }
+
+console.log(JSON.stringify({
+ oneMesh, stride, colOk, posOk, yHalf150, groupCenterX,
+ vertexColors: merged.material.vertexColors === true,
+ isStandard: merged.material.isMeshStandardMaterial === true,
+ roughness: merged.material.roughness,
+ metalness: merged.material.metalness,
+ hasNormals: !!merged.geometry.attributes.normal,
+ hasUv: !!merged.geometry.attributes.uv,
+ shadows: merged.castShadow && merged.receiveShadow,
+ threwEmpty, threwNoMesh,
+}));
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch of _PROBE, shared by every test that reads it."""
+ return measure(_PROBE, _LIBS)
+
+
+def test_three_hundred_boxes_collapse_to_one_draw_call(probe):
+ """300 placed props become ONE mesh — no children, no material array, no
+ geometry groups; anything else is still N draw calls under a new name."""
+ m = probe
+ assert m["oneMesh"], m
+ # Mixed indexed/non-indexed inputs were unified (36 verts per box once
+ # expanded); a fractional stride means a box was dropped.
+ assert m["stride"] == 36, f"vertex runs uneven: {m['stride']}"
+
+
+def test_world_transforms_and_per_box_colors_are_baked(probe):
+ """Each box's vertex run must sit at its world position (pos + rot +
+ scale) and carry its material colour as vertex colour — the
+ render-visible promise the reference's probe grades."""
+ m = probe
+ assert m["posOk"] == 7, f"world matrices not baked: {m['posOk']}/7"
+ assert m["colOk"] == 7, f"material colors lost: {m['colOk']}/7"
+ # Box 150 has scale 1.75 with yaw-only rotation: its baked y half-extent
+ # must be 0.875, or scale was dropped in the bake.
+ assert abs(m["yHalf150"] - 0.875) < 1e-3, m["yHalf150"]
+
+
+def test_one_standard_lit_material_with_vertex_colors(probe):
+ """One LIT MeshStandardMaterial with vertexColors on, normals + uv
+ present, shadows on — a basic/unlit or colour-blind material renders the
+ whole merge flat."""
+ m = probe
+ assert m["isStandard"] and m["vertexColors"], m
+ assert abs(m["roughness"] - 0.6) < 1e-6, m["roughness"]
+ assert abs(m["metalness"] - 0.1) < 1e-6, m["metalness"]
+ assert m["hasNormals"] and m["hasUv"], m
+ assert m["shadows"], "merged mesh does not cast/receive shadows"
+
+
+def test_groups_are_traversed_and_parent_transforms_reach_the_bake(probe):
+ """Assets are Groups: passing one must merge its leaf meshes with the
+ PARENT transform included — a bake that reads only the mesh's local
+ matrix would pile every asset at the origin."""
+ m = probe
+ assert abs(m["groupCenterX"] - 100) < 1e-3, m["groupCenterX"]
+
+
+def test_fails_loud_on_empty_or_meshless_input(probe):
+ """The wrapper throws instead of returning an empty mesh: a silent no-op
+ would ship a scene missing its props with nothing in the logs (fail loud
+ is the repo-wide contract)."""
+ m = probe
+ assert m["threwEmpty"], "empty array did not throw"
+ assert m["threwNoMesh"], "mesh-less group did not throw"
+
+
+def test_the_surface_response_survives_the_merge():
+ """Everything but colour comes from the batch's first material, and the
+ port's rebuilt material dropped most of it. `emissive` is the one that
+ costs a look outright — merged lantern boxes rendered as dead grey blocks
+ (lantern region mean_lum 0.644 -> 0.777 day, 0.376 -> 0.642 night) — and
+ `side` deletes geometry: 6 of 13 DoubleSide slats were culled. A batch
+ that DISAGREES about the response must say so, because those differences
+ are lost either way."""
+ out = measure("""
+import * as THREE from 'three';
+import { mergeStatic } from './lib/merge.js';
+const tex = new THREE.Texture();
+const mat = new THREE.MeshStandardMaterial({
+ color: 0x334455, roughness: 0.31, metalness: 0.22, side: THREE.DoubleSide,
+ emissive: new THREE.Color(0xff9944), emissiveIntensity: 2.6,
+ transparent: true, opacity: 0.8, envMapIntensity: 1.7, flatShading: true,
+ normalMap: tex, aoMap: tex, alphaMap: tex, dithering: true,
+});
+mat.normalScale.set(0.4, 0.4);
+const mk = (m) => new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), m);
+const one = mergeStatic([mk(mat)]).material;
+
+// a batch whose second piece disagrees about more than colour warns once
+const warns = [];
+const realWarn = console.warn;
+console.warn = (msg) => warns.push(String(msg));
+const odd = new THREE.MeshStandardMaterial({ color: 0x334455, roughness: 0.9 });
+mergeStatic([mk(mat), mk(odd)]);
+mergeStatic([mk(mat), mk(mat.clone())]); // colour-equal: no warning
+console.warn = realWarn;
+
+console.log(JSON.stringify({
+ emissive: one.emissive.getHexString(),
+ emissiveIntensity: one.emissiveIntensity,
+ doubleSide: one.side === THREE.DoubleSide,
+ roughness: one.roughness, metalness: one.metalness,
+ opacity: one.opacity, transparent: one.transparent,
+ envMapIntensity: one.envMapIntensity, flatShading: one.flatShading,
+ dithering: one.dithering,
+ maps: ['normalMap', 'aoMap', 'alphaMap'].filter((k) => one[k] === tex).length,
+ normalScale: one.normalScale.x,
+ // colour is NOT copied: it lives per-vertex, and copying it would
+ // multiply the bake a second time
+ white: one.color.getHex() === 0xffffff,
+ warnCount: warns.length, warned: warns.join(' ').includes('surface response'),
+}));
+""", _LIBS)
+ assert out["emissive"] == "ff9944" and out["emissiveIntensity"] == 2.6, out
+ assert out["doubleSide"], "side dropped — back-facing cards disappear"
+ assert out["transparent"] and out["opacity"] == 0.8, out
+ assert out["envMapIntensity"] == 1.7 and out["flatShading"], out
+ assert out["dithering"], "dithering dropped — merged gradients band"
+ assert out["maps"] == 3 and out["normalScale"] == 0.4, out
+ assert abs(out["roughness"] - 0.31) < 1e-6, out
+ assert out["white"], "the first material's colour was copied AND baked"
+ assert out["warnCount"] == 1 and out["warned"], out
+
+
+def test_a_mirrored_piece_is_not_baked_inside_out():
+ """`scale.x = -1` is how a matching pair gets made. Its world matrix has
+ a negative determinant, so the bake reverses which side of every triangle
+ faces out; three normally fixes that per draw from the matrix, which the
+ merge throws away. The right-hand buttress slab rendered as its own
+ interior — no sunlit top, a flat dark front — until the winding was
+ flipped back (crop pair fx/crop_merge_slab_before.png -> _after.png)."""
+ out = measure("""
+import * as THREE from 'three';
+import { mergeStatic } from './lib/merge.js';
+const facing = (mesh) => {
+ const g = mesh.geometry;
+ const p = g.attributes.position, n = g.attributes.normal;
+ const idx = g.index;
+ const tri = idx ? idx.count / 3 : p.count / 3;
+ const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
+ let out = 0;
+ for (let t = 0; t < tri; t++) {
+ const i0 = idx ? idx.getX(t * 3) : t * 3;
+ const i1 = idx ? idx.getX(t * 3 + 1) : t * 3 + 1;
+ const i2 = idx ? idx.getX(t * 3 + 2) : t * 3 + 2;
+ a.fromBufferAttribute(p, i0);
+ b.fromBufferAttribute(p, i1).sub(a);
+ c.fromBufferAttribute(p, i2).sub(a);
+ b.cross(c);
+ const vn = new THREE.Vector3().fromBufferAttribute(n, i0);
+ if (b.dot(vn) > 0) out++;
+ }
+ return [out, tri];
+};
+const mk = (sx, geo) => {
+ const m = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x998877 }));
+ m.position.set(4, 1, 0); m.rotation.set(0.2, 0.5, 0.13); m.scale.x = sx;
+ return m;
+};
+const plain = facing(mergeStatic([mk(1, new THREE.BoxGeometry(0.5, 1.9, 1.1))]));
+const mirrored = facing(mergeStatic([mk(-1, new THREE.BoxGeometry(0.5, 1.9, 1.1))]));
+// the non-indexed path flips vertex runs instead of index triples
+const nonIdx = facing(mergeStatic(
+ [mk(-1, new THREE.BoxGeometry(0.5, 1.9, 1.1).toNonIndexed())]));
+// a mirrored piece merged NEXT TO a plain one must not disturb it
+const both = facing(mergeStatic([mk(1, new THREE.BoxGeometry(1, 1, 1)),
+ mk(-1, new THREE.BoxGeometry(1, 1, 1))]));
+console.log(JSON.stringify({ plain, mirrored, nonIdx, both }));
+""", _LIBS)
+ for name in ("plain", "mirrored", "nonIdx", "both"):
+ out_faces, tris = out[name]
+ assert tris > 0 and out_faces == tris, (
+ f"{name}: {out_faces}/{tris} triangles wind outward")
+
+
+def test_invisible_pieces_are_left_out():
+ """`visible = false` is how a scene hides an LOD stand-in or a debug
+ proxy. Baking one in makes it permanent and un-hideable, and it is the
+ merged mesh's own visibility that would have to go instead."""
+ out = measure("""
+import * as THREE from 'three';
+import { mergeStatic } from './lib/merge.js';
+const mk = () => new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),
+ new THREE.MeshStandardMaterial({ color: 0x778899 }));
+const a = mk(), b = mk(), c = mk();
+b.visible = false;
+const hiddenGroup = new THREE.Group();
+hiddenGroup.visible = false;
+hiddenGroup.add(c);
+const n = (o) => mergeStatic(o).geometry.attributes.position.count;
+let threwAllHidden = false;
+try { mergeStatic([b]); } catch (e) { threwAllHidden = true; }
+console.log(JSON.stringify({
+ one: n([a]), withHidden: n([a, b]), withHiddenGroup: n([a, hiddenGroup]),
+ threwAllHidden,
+}));
+""", _LIBS)
+ assert out["withHidden"] == out["one"], "an invisible mesh was baked in"
+ assert out["withHiddenGroup"] == out["one"], "a hidden group was baked in"
+ assert out["threwAllHidden"], "an all-hidden batch merged silently"
+
+
+def test_a_shader_patched_batch_keeps_its_patch():
+ """A patched stone material (patchRockStrata, patchTriplanar, …) is the
+ normal case for the props worth merging, and rebuilding the material threw
+ the whole chain away — the merged wall lost its look with nothing in the
+ logs. The chain is replayed onto the merged material over the SOURCE
+ uniform map, so one `tickShaders` still advances both, and the cache key
+ still names the chain (the first material to compile a key decides the
+ GLSL for every material holding it)."""
+ out = measure("""
+import * as THREE from 'three';
+import { mergeStatic } from './lib/merge.js';
+import { patchStandard, tickShaders } from './lib/shader.js';
+const mat = new THREE.MeshStandardMaterial({ color: 0x8b8377 });
+patchStandard(mat, { name: 'Strata', uniforms: { uBand: { value: 0.4 } },
+ fragmentBody: 'diffuseColor.rgb *= 1.0 - uBand;' });
+patchStandard(mat, { name: 'Streaks', fragmentBody: 'diffuseColor.rgb *= 0.9;' });
+const merged = mergeStatic([new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), mat)]);
+const mm = merged.material;
+const s = { uniforms: {}, vertexShader: '#include <begin_vertex>',
+ fragmentShader: '#include <color_fragment>' };
+mm.onBeforeCompile(s, null);
+const root = new THREE.Group();
+root.add(merged);
+tickShaders(root, 3.25);
+console.log(JSON.stringify({
+ patches: (mm.userData.astraPatches || []).map((p) => p.name),
+ key: mm.customProgramCacheKey(),
+ sharedUniforms: mm.userData.uniforms === mat.userData.uniforms,
+ glslInOrder: s.fragmentShader.indexOf('1.0 - uBand')
+ < s.fragmentShader.indexOf('*= 0.9'),
+ boundUniform: s.uniforms.uBand !== undefined,
+ ticked: mat.userData.uniforms.uTime.value,
+ stillVertexColors: mm.vertexColors === true,
+}));
+""", ("merge.js", "shader.js"))
+ assert out["patches"] == ["Strata", "Streaks"], out
+ assert out["key"] == "astra:Strata+Streaks", out
+ assert out["sharedUniforms"], "the merged material got a dead uniform map"
+ assert out["glslInOrder"] and out["boundUniform"], out
+ assert out["ticked"] == 3.25, "tickShaders no longer reaches the patch"
+ assert out["stillVertexColors"], "the replay dropped vertexColors"
+
+
+def test_variance_stops_a_one_material_batch_reading_as_one_solid():
+ """The deliberate look change. A dry-stone wall cut from one material
+ arrives as ONE albedo, and one albedo over 44 stones reads as an extruded
+ solid: the wall region of the before render put 49% of its pixels in a
+ single luminance bin (modal_frac 0.4918, val_std 0.1245) against 17% after
+ (0.1727, val_std 0.1448). The offset is hashed from where the piece SITS,
+ so it is stable across runs and independent of input order, it stays
+ inside its stated bound, and `variance: 0` turns it off for baked colours
+ that are data."""
+ out = measure("""
+import * as THREE from 'three';
+import { mergeStatic } from './lib/merge.js';
+const V = 0.12;
+const mk = (i) => {
+ const m = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),
+ new THREE.MeshStandardMaterial({ color: 0x8b8377 }));
+ m.position.set(i * 1.7 - 20, 0.5 + (i % 3) * 0.4, (i % 5) * 1.1);
+ return m;
+};
+const N = 24;
+const pieces = [];
+for (let i = 0; i < N; i++) pieces.push(mk(i));
+const pieceMeans = (mesh) => {
+ const c = mesh.geometry.attributes.color;
+ const stride = c.count / N;
+ const out = [];
+ for (let i = 0; i < N; i++) {
+ let r = 0, g = 0, b = 0;
+ for (let v = i * stride; v < (i + 1) * stride; v++) {
+ r += c.getX(v); g += c.getY(v); b += c.getZ(v);
+ }
+ out.push([r / stride, g / stride, b / stride]);
+ }
+ return out;
+};
+const varied = pieceMeans(mergeStatic(pieces));
+const flat = pieceMeans(mergeStatic(pieces, { variance: 0 }));
+// reordering the batch must not change what any piece looks like
+const shuffled = pieces.slice().reverse();
+const reordered = pieceMeans(mergeStatic(shuffled)).reverse();
+
+const lum = (c) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
+const warmth = (c) => c[0] / Math.max(1e-6, c[2]);
+const spread = (f, a) => {
+ const v = a.map(f);
+ const mean = v.reduce((s, x) => s + x, 0) / v.length;
+ return Math.sqrt(v.reduce((s, x) => s + (x - mean) ** 2, 0) / v.length) / mean;
+};
+let maxDev = 0, maxOrderDev = 0;
+const base = lum(flat[0]);
+for (let i = 0; i < N; i++) {
+ maxDev = Math.max(maxDev, Math.abs(lum(varied[i]) - base) / base);
+ maxOrderDev = Math.max(maxOrderDev,
+ Math.abs(lum(varied[i]) - lum(reordered[i])));
+}
+console.log(JSON.stringify({
+ flatSpread: spread(lum, flat),
+ variedSpread: spread(lum, varied),
+ warmSpread: spread(warmth, varied),
+ flatWarmSpread: spread(warmth, flat),
+ maxDev, maxOrderDev, V,
+ meanShift: Math.abs(
+ varied.reduce((s, c) => s + lum(c), 0) / N - base) / base,
+ inRange: varied.every((c) => c.every((x) => x > 0.02 && x <= 0.8)),
+}));
+""", _LIBS)
+ assert out["flatSpread"] < 1e-9, "variance: 0 still varied the batch"
+ assert out["flatWarmSpread"] < 1e-9, out
+ # every piece its own value AND its own warm/cool, none of it beyond the
+ # documented +-variance / +-0.6*variance
+ assert out["variedSpread"] > 0.03, f"batch is still one swatch: {out}"
+ assert out["warmSpread"] > 0.01, f"value-only spread, no hue: {out}"
+ assert out["maxDev"] <= out["V"] * 1.6 + 1e-6, out
+ assert out["maxOrderDev"] < 1e-9, "the spread depends on input order"
+ # a grade, not a brightness change: the batch mean barely moves
+ assert out["meanShift"] < 0.05, out
+ # and the result stays a sane non-emissive albedo
+ assert out["inRange"], out
diff --git a/harness/tests/scene_runtime/lib/test_mirror.py b/harness/tests/scene_runtime/lib/test_mirror.py
new file mode 100644
index 00000000..c9e47ba2
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_mirror.py
@@ -0,0 +1,545 @@
+"""mirror.js: the one real planar mirror, and the cheap route for everything
+else — a baked equirect city that a whole facade can reflect for free.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_mirror_lib.py). Their budget, standoff, target-shape and
+retarget scenarios are kept as they stood; their `logarithmicDepthBuffer:
+true` renderer contract is retargeted (ours has it OFF by default, but
+`--log-depth` is still a host option and the addon's four chunks cost
+nothing, so the "never hand the Reflector a replacement shader" law stays);
+and their render probe is dropped in favour of the showcase harness, which
+renders this module through OUR host at fx/out/mirror/{before,after}.
+
+THE PORT'S OWN LAWS — each one a frame rendered on our host, looked at, and
+measured, and each one a defect the reference shipped:
+
+1. THE BAKE HAS TO SHIP sRGB BYTES. Every colour in `bakeSkylineEnvironment`
+ is mixed in the LINEAR working space a THREE.Color holds, and the
+ DataTexture it writes is flagged SRGBColorSpace — so it is DECODED as
+ sRGB when sampled. The reference wrote the linear numbers straight into
+ the bytes and ran the transfer backwards: the intended zenith 0x5d8fd6
+ shipped as (28,70,171) and came back as linear (0.011,0.061,0.415). A
+ sixth of the light, and blue pulled far ahead of red, because the error
+ is a power curve and not a scale. On our host every facade `glazeFacade`
+ touched rendered as a flat navy slab: mean_lum 0.145, saturation 0.72,
+ modal_frac 0.153 — the "black hole" the module's own docstring says the
+ cheap route exists to prevent. After the fix, 0.355 / 0.334 / 0.046,
+ with the reflected skyline legible in the frame.
+
+2. A CURTAIN WALL'S MIRROR LIVES IN THE COATING, NOT THE METAL. A metal's
+ F0 IS its colour, and this glass tint is linear (0.031,0.058,0.088), so
+ the reference's metalness 0.35 multiplied a third of the reflection by a
+ near-black blue. An untinted `clearcoat` is what real reflective glazing
+ actually is: the sky arrives in the sky's own colour, with its own
+ fresnel. Measured together with law 1 on the glazed block: pane region
+ p05 0.063 -> 0.256.
+
+3. A REFLECTED CITY IS NOT ONE SWATCH, AND IT KNOWS WHAT TIME IT IS. The
+ skyline was one hue scaled by one random number per building, unlit
+ unless asked, and lit by a hardcoded noon palette even when handed a
+ sun that had set. It now takes hue and saturation per building, shades
+ facades by the key light's own azimuth, hazes toward the horizon, and
+ flips to the night mood — moon where lib/environment.js puts the moon,
+ windows on — the moment `sunDir` goes below the horizon.
+"""
+
+from __future__ import annotations
+
+import math
+
+import pytest
+
+from tests.scene_runtime.lib._probe import LIB_DIR, NODE_MODULES, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("mirror.js", "wetground.js", "building.js", "materials.js",
+ "noise.js")
+
+_PROBE = """
+import * as THREE from 'three';
+import { makeMirror, envMirrorMaterial, bakeSkylineEnvironment,
+ glassFacadeMaterial, glazeFacade, reflectionBudget,
+ setReflectionBudget } from './lib/mirror.js';
+import { makeMirrorFloor } from './lib/wetground.js';
+import { block } from './lib/building.js';
+import { mulberry32 } from './lib/noise.js';
+
+// 1) The one real mirror, and what the Reflector was handed.
+const scene = new THREE.Scene();
+const m1 = makeMirror(4, 3, { scene });
+scene.add(m1);
+const surf = m1.userData.surface;
+const rttTex = surf.material.uniforms.tDiffuse.value;
+const rttSamples = surf.getRenderTarget().samples;
+const tint = surf.material.uniforms.color.value;
+const back = m1.getObjectByName('MirrorBack');
+const frame = m1.getObjectByName('MirrorFrame');
+
+// 2) A SECOND surface in the same scene must not get its own RTT.
+const m2 = makeMirror(4, 3, { scene });
+
+// 3) A mirror floor built by another module charges the same budget.
+setReflectionBudget(1);
+const wet = new THREE.Scene();
+wet.add(makeMirrorFloor(20, 20));
+const m3 = makeMirror(4, 3, { scene: wet });
+const wetBudget = reflectionBudget(wet);
+
+// 4) A fresh budget hands out a real mirror again; 'env' never takes one.
+setReflectionBudget(1);
+const forcedEnv = makeMirror(4, 3, { mode: 'env' });
+const m4 = makeMirror(4, 3, {});
+
+// 5) The baked environment: deterministic, filtered, structured, sRGB.
+const e1 = bakeSkylineEnvironment({ seed: 3 });
+const e2 = bakeSkylineEnvironment({ seed: 3 });
+const flat = bakeSkylineEnvironment({ seed: 3, skyline: false });
+const warm = bakeSkylineEnvironment({ seed: 3, lit: 0.6 });
+// A sun straight DOWN leaves the upper hemisphere free of glow, so the top
+// row is the requested zenith and nothing else: the transfer function is
+// then the only thing between the hex asked for and the bytes shipped.
+const clean = bakeSkylineEnvironment({
+ seed: 3, skyline: false, sunDir: new THREE.Vector3(0, -1, 0),
+ zenith: 0x5d8fd6, horizon: 0xdce9f2, ground: 0x8a7f6a });
+const d1 = e1.image.data, d2 = e2.image.data;
+let sameBake = d1.length === d2.length;
+for (let i = 0; sameBake && i < d1.length; i++) {
+ if (d1[i] !== d2[i]) sameBake = false;
+}
+const W = e1.image.width, H = e1.image.height;
+function rowMean(data, r0, r1) {
+ let s = 0, n = 0;
+ for (let y = r0; y < r1; y++) {
+ for (let x = 0; x < W; x++) {
+ const i = (y * W + x) * 4;
+ s += (data[i] + data[i + 1] + data[i + 2]) / 3;
+ n++;
+ }
+ }
+ return s / n;
+}
+function rowMin(data, r0, r1) {
+ let m = 255;
+ for (let y = r0; y < r1; y++) {
+ for (let x = 0; x < W; x++) {
+ const i = (y * W + x) * 4;
+ const l = (data[i] + data[i + 1] + data[i + 2]) / 3;
+ if (l < m) m = l;
+ }
+ }
+ return m;
+}
+// Circular spread of hue, in degrees, over the pixels with colour in them.
+function hueStdDeg(data, r0, r1) {
+ let cx = 0, cy = 0, n = 0;
+ for (let y = r0; y < r1; y++) {
+ for (let x = 0; x < W; x++) {
+ const i = (y * W + x) * 4;
+ const r = data[i], g = data[i + 1], b = data[i + 2];
+ const M = Math.max(r, g, b), mn = Math.min(r, g, b), c = M - mn;
+ if (M <= 0 || c / M <= 0.04) continue;
+ let h;
+ if (M === r) h = ((g - b) / c + 6) % 6;
+ else if (M === g) h = (b - r) / c + 2;
+ else h = (r - g) / c + 4;
+ const a = h * 60 * Math.PI / 180;
+ cx += Math.cos(a); cy += Math.sin(a); n++;
+ }
+ }
+ if (n < 64) return 0;
+ const R = Math.min(1, Math.hypot(cx, cy) / n);
+ return Math.sqrt(-2 * Math.log(Math.max(R, 1e-9))) * 180 / Math.PI;
+}
+// Rows just above the horizon (v = 0.5) are where the neighbours are.
+const bandTop = (H >> 1) + 2, bandBot = (H >> 1) + 22;
+let warmPx = 0;
+for (let y = bandTop; y < bandBot; y++) {
+ for (let x = 0; x < W; x++) {
+ const i = (y * W + x) * 4;
+ const wd = warm.image.data;
+ if (wd[i] > 110 && wd[i] - wd[i + 2] > 30) warmPx++;
+ }
+}
+const topRow = (H - 1) * W * 4;
+const cd = clean.image.data;
+
+// 6) The same bake once the sun has set: azimuth 215, elevation -20, the
+// vector sunRig() reports as `sunDir` on a night scene.
+const nEl = -20 * Math.PI / 180, nAz = 215 * Math.PI / 180;
+const nightSun = new THREE.Vector3(
+ Math.cos(nEl) * Math.cos(nAz), Math.sin(nEl), Math.cos(nEl) * Math.sin(nAz));
+const night = bakeSkylineEnvironment({ seed: 3, sunDir: nightSun });
+const nd = night.image.data;
+// Where is the brightest pixel of the night sky? The moon, and it has to be
+// ABOVE the horizon: a set sun left as the glow source puts it underground.
+let bestY = -1, bestV = -1;
+for (let y = 0; y < H; y++) {
+ for (let x = 0; x < W; x++) {
+ const i = (y * W + x) * 4;
+ const l = (nd[i] + nd[i + 1] + nd[i + 2]) / 3;
+ if (l > bestV) { bestV = l; bestY = y; }
+ }
+}
+let nightWarmPx = 0;
+for (let y = bandTop; y < bandBot; y++) {
+ for (let x = 0; x < W; x++) {
+ const i = (y * W + x) * 4;
+ if (nd[i] > 90 && nd[i] - nd[i + 2] > 20) nightWarmPx++;
+ }
+}
+
+// 7) A facade from lib/building.js, retargeted.
+// block() splits its panes on `rand()`, and its default rand is a
+// constant 0.5 that always lands in bin 0 — a seeded one is what makes
+// the second batch exist at all.
+const b = block({ w: 16, d: 14, h: 30, style: 'glass',
+ rand: mulberry32(5) });
+const glazing = b.getObjectByName('Glazing');
+const glazing2 = b.getObjectByName('Glazing2');
+const reveals = b.getObjectByName('Reveals');
+const revealsBefore = reveals.material.uuid;
+glazeFacade(b, { envMap: e1 });
+const gm = glazing.material;
+// The same tower, glazed with an explicit material: one value everywhere.
+const b2 = block({ w: 16, d: 14, h: 30, style: 'glass',
+ rand: mulberry32(5) });
+glazeFacade(b2, { material: glassFacadeMaterial({ envMap: e1 }) });
+
+const chrome = envMirrorMaterial({ envMap: e1 });
+const gTrans = glassFacadeMaterial({ opacity: 0.6 });
+
+console.log(JSON.stringify({
+ mode1: m1.userData.mode, mode2: m2.userData.mode,
+ mode3: m3.userData.mode, mode4: m4.userData.mode,
+ modeForcedEnv: forcedEnv.userData.mode,
+ wetUsed: wetBudget.used, wetLeft: wetBudget.left,
+ tintLinear: tint.r,
+ rttW: rttTex.image.width, rttH: rttTex.image.height,
+ rttSamples,
+ standoff: surf.position.z, backZ: back.position.z,
+ surfCast: surf.castShadow, surfReceive: surf.receiveShadow,
+ forward: m1.userData.forward,
+ backLum: back.material.color.r * 0.2126 + back.material.color.g * 0.7152
+ + back.material.color.b * 0.0722,
+ frameLum: frame.material.color.r * 0.2126
+ + frame.material.color.g * 0.7152 + frame.material.color.b * 0.0722,
+ frameWarm: frame.material.color.r - frame.material.color.b,
+ sameBake,
+ envW: W, envH: H,
+ equirect: e1.mapping === THREE.EquirectangularReflectionMapping,
+ srgb: e1.colorSpace === THREE.SRGBColorSpace,
+ linearFiltered: e1.minFilter === THREE.LinearFilter
+ && e1.magFilter === THREE.LinearFilter,
+ zenith: rowMean(e1.image.data, H - 6, H - 1),
+ bandSkyline: rowMean(e1.image.data, bandTop, bandBot),
+ bandOpenSky: rowMean(flat.image.data, bandTop, bandBot),
+ bandMin: rowMin(e1.image.data, bandTop, bandBot),
+ bandHueStd: hueStdDeg(e1.image.data, bandTop, bandBot),
+ openHueStd: hueStdDeg(flat.image.data, bandTop, bandBot),
+ warmPx,
+ cleanTop: [cd[topRow], cd[topRow + 1], cd[topRow + 2]],
+ nightZenith: rowMean(nd, H - 6, H - 1),
+ dayZenith: rowMean(e1.image.data, H - 6, H - 1),
+ nightBandMin: rowMin(nd, bandTop, bandBot),
+ nightMoonAboveHorizon: bestY > (H >> 1),
+ nightWarmPx,
+ glazed: b.userData.glazed,
+ glazeIsPhysical: !!gm.isMeshPhysicalMaterial,
+ glazeEnv: gm.envMap === e1,
+ glazeIor: gm.ior, glazeTransparent: gm.transparent,
+ glazeClearcoat: gm.clearcoat, glazeMetalness: gm.metalness,
+ batchesDiffer: glazing.material.uuid !== glazing2.material.uuid,
+ batchEnvBoth: glazing2.material.envMap === e1,
+ forcedOneMaterial: b2.getObjectByName('Glazing').material.uuid
+ === b2.getObjectByName('Glazing2').material.uuid,
+ revealsUntouched: reveals.material.uuid === revealsBefore,
+ chromeMetal: chrome.metalness, chromeRough: chrome.roughness,
+ transFlag: gTrans.transparent, transOpacity: gTrans.opacity,
+}));
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch of _PROBE, shared by every test that reads it."""
+ return measure(_PROBE, _LIBS)
+
+
+def test_the_scene_gets_one_real_mirror_and_no_more(probe):
+ """The budget is the module's reason to exist: a second RTT surface
+ renders INSIDE the first one's pass, so it cannot be left to the
+ caller's discipline. A mirror floor from wetground.js counts too --
+ the budget is per scene, not per module."""
+ m = probe
+ assert m["mode1"] == "rtt", "the first mirror must be a real one"
+ assert m["mode2"] == "env", (
+ "a second mirror in the same scene took its own render target"
+ )
+ assert m["mode3"] == "env", (
+ "a wetground makeMirrorFloor in the scene did not charge the "
+ "budget — two RTT surfaces ship whenever the modules differ"
+ )
+ assert (m["wetUsed"], m["wetLeft"]) == (1, 0), m
+ assert m["mode4"] == "rtt", "a fresh budget hands out a real mirror"
+ assert m["modeForcedEnv"] == "env", "mode:'env' still took an RTT"
+
+
+def test_the_reflection_is_untinted_and_frame_shaped(probe):
+ """Two Reflector defaults are wrong for a mirror. Its 0x7f7f7f
+ OVERLAY-blends to ~0.42x on darks (dim, dirty glass) — overlay's
+ identity is linear 0.5. And its square target oversamples vertically at
+ 1.8x the pixel cost, because the target holds a SCREEN-space image, not
+ a picture of the mirror.
+
+ Overlay's identity holds on OUR host for a second reason worth keeping
+ written down: the addon renders the reflection to a render target, where
+ three forces NoToneMapping and a linear output, and applies the tone map
+ and the sRGB encode in the mirror's OWN fragment tail instead. So the
+ values `color` blends against are linear radiance that can exceed 1, and
+ blendOverlay at 0.5 is the identity there too."""
+ m = probe
+ assert abs(m["tintLinear"] - 0.5) < 0.02, (
+ f"mirror tint is linear {m['tintLinear']:.3f}, not the overlay "
+ "identity 0.5 — the reflection is being darkened or blown out"
+ )
+ assert abs(m["rttW"] / m["rttH"] - 16 / 9) < 0.02, (
+ f"reflection target {m['rttW']}x{m['rttH']} is not frame-shaped"
+ )
+ assert m["rttW"] >= 640, f"reflection target too coarse: {m['rttW']}"
+ assert m["rttSamples"] == 0, (
+ f"MSAA {m['rttSamples']} on the reflection target: measured 28 "
+ "ms/frame on SwiftShader for a difference invisible at 1:1 — "
+ "the reflection is minified onto the mirror and the frame is "
+ "antialiased anyway"
+ )
+
+
+def test_nothing_sits_within_a_centimetre_behind_the_glass(probe):
+ """Measured: geometry within 1 cm behind the glass leaks past the
+ Reflector's oblique clip plane and fills the mirror with a dark slab
+ from 20 degrees off-axis (2 cm is clean to 55 degrees). The standoff is
+ what buys that clearance, so it is not decoration."""
+ m = probe
+ assert m["standoff"] >= 0.02, (
+ f"glass stands only {m['standoff']} m off the mount plane"
+ )
+ assert m["standoff"] - m["backZ"] >= 0.02, (
+ f"backing plate is {m['standoff'] - m['backZ']:.3f} m behind "
+ "the glass — it will leak into the reflection"
+ )
+ assert not m["surfCast"] and not m["surfReceive"], (
+ "an RTT plane that casts shadows shadows the scene it resamples"
+ )
+ assert m["forward"] == "+Z", m["forward"]
+
+
+def test_the_frame_is_the_only_lit_thing_next_to_the_reflection(probe):
+ """PORT LAW. A mirror is full of the scene's own brightness, so the two
+ surfaces around it decide whether it reads as an object or as a hole cut
+ in the wall — and the reference set both at the floor of a legal albedo
+ (frame 0x4a3a2a, linear 0.068; plate 0x2a2724, linear 0.024). Rendered
+ on our host at exposure 1.0 the frame came back as a black border with
+ no grain in it at all. Walnut keeps it a dark frame and gives it a hue:
+ the close view's frame band went p05 0.170 -> 0.217 and hue spread
+ 0.843 -> 0.928."""
+ m = probe
+ assert m["frameLum"] > 0.05, (
+ f"frame albedo is linear {m['frameLum']:.3f} — under ACES at "
+ "exposure 1.0 that is a black rectangle, not a frame"
+ )
+ assert m["frameWarm"] > 0.03, (
+ "the frame has no hue in it; wood is warmer than it is blue"
+ )
+ assert m["backLum"] > 0.025, (
+ f"backing plate is linear {m['backLum']:.3f} — it has nowhere "
+ "left to fall in shade"
+ )
+
+
+def test_the_bake_ships_srgb_bytes_and_not_linear_ones(probe):
+ """PORT LAW 1, and the worst defect in the module. Every colour is mixed
+ in the LINEAR working space a THREE.Color holds, and the DataTexture is
+ flagged SRGBColorSpace, so it is DECODED as sRGB on sample. Writing the
+ linear numbers straight out runs the transfer backwards: 0x5d8fd6 left
+ as (28,70,171) instead of (93,143,214) and came back as a sixth of the
+ light with blue far ahead of red, because the error is a power curve and
+ not a scale. On our host that is what made every glazed facade a flat
+ navy slab."""
+ r, g, b = probe["cleanTop"]
+ for got, want, ch in ((r, 0x5d, "r"), (g, 0x8f, "g"), (b, 0xd6, "b")):
+ assert abs(got - want) <= 3, (
+ f"zenith {ch} shipped as byte {got}, asked for {want} — the "
+ f"bake wrote {ch} in the linear working space into a texture "
+ "that is decoded as sRGB"
+ )
+
+
+def test_the_baked_environment_carries_a_city_not_a_gradient(probe):
+ """The cheap route only beats a plain sky gradient if the bake has
+ neighbours in it: a dark band of towers above the horizon is what a glass
+ facade actually mirrors. Deterministic, or a fix round re-rolls the
+ skyline; LINEAR filtered, or a DataTexture's Nearest default prints the
+ bake's texel grid across every facade.
+
+ PORT LAW 3 adds the two floors under it. The band must not bottom out
+ near black — aerial perspective is what a city actually does to its own
+ contrast, and without it the darkest facades were the ones a mirror
+ turned into a hole. And it must carry more than one hue: the reference
+ scaled a single wall colour by one random number per building, which is
+ the "stamped asset" verdict in swatch form."""
+ m = probe
+ assert m["sameBake"], "two bakes of one seed differ"
+ assert m["equirect"] and m["srgb"], m
+ assert m["linearFiltered"], (
+ "environment left on the DataTexture Nearest default"
+ )
+ assert (m["envW"], m["envH"]) == (512, 256), m
+ assert m["bandSkyline"] < 0.7 * m["bandOpenSky"], (
+ f"the horizon band reads {m['bandSkyline']:.1f} with a skyline "
+ f"vs {m['bandOpenSky']:.1f} without — no neighbours were baked"
+ )
+ assert m["zenith"] > m["bandSkyline"], "the sky is darker than the city"
+ assert m["warmPx"] > 200, (
+ f"lit: 0.6 lit only {m['warmPx']} window pixels"
+ )
+ assert m["bandMin"] >= 40, (
+ f"darkest neighbour in the band is byte {m['bandMin']:.0f} — a "
+ "facade that mirrors it renders as a hole"
+ )
+ assert m["bandHueStd"] > 2.5 * max(m["openHueStd"], 0.8), (
+ f"the skyline's hue spread is {m['bandHueStd']:.2f} deg against "
+ f"{m['openHueStd']:.2f} for bare sky — every neighbour was baked "
+ "from one swatch"
+ )
+
+
+def test_the_bake_knows_what_time_it_is(probe):
+ """PORT LAW 3. `sunDir` already carries the hour, so a bake that keeps
+ noon hexes while the scene hands it a set sun mirrors a noon sky off
+ every pane at midnight — the one hardcoded-light-colour failure this
+ module could still commit. Below the horizon the palette flips to the
+ night mood the rest of the library uses, the glow moves to where
+ lib/environment.js puts the MOON (opposite the sun, 30-55 deg up, not
+ underground), and the reflected city has its lights on without being
+ asked. The lower half stays off the floor on purpose: a night horizon
+ carries a city's skyglow and a night street carries its own lamps, and
+ neither is a fraction of the zenith."""
+ m = probe
+ assert m["nightZenith"] < 0.45 * m["dayZenith"], (
+ f"night zenith {m['nightZenith']:.1f} vs day "
+ f"{m['dayZenith']:.1f} — the palette did not follow sunDir down"
+ )
+ assert m["nightMoonAboveHorizon"], (
+ "the brightest pixel of the night sky is below the horizon — the "
+ "glow is still sitting on the set sun instead of the moon"
+ )
+ assert m["nightWarmPx"] > 150, (
+ f"only {m['nightWarmPx']} warm window pixels after dark — a city "
+ "with every light out is a ruin, not a night"
+ )
+ assert m["nightBandMin"] >= 18, (
+ f"darkest night neighbour is byte {m['nightBandMin']:.0f}"
+ )
+
+
+def test_a_building_facade_is_retargeted_without_losing_its_lit_windows(
+ probe,
+):
+ """The whole point of the cheap route: one call makes a lib/building.js
+ tower mirror the sky. Lit windows live on the Reveals mesh and must keep
+ glowing — glazing every mesh would put out the lights that make a dusk
+ city read as inhabited.
+
+ PORT LAW 2 and its corollary. The mirror a curtain wall shows lives in
+ an UNTINTED coating, not in metalness: a metal's F0 is its colour, and
+ this tint is linear (0.031,0.058,0.088), so the reference multiplied a
+ third of every reflection by a near-black blue and got the flat navy
+ hole its own docstring warns about. And building.js already splits its
+ panes into two batches precisely because "real glazing is never one
+ value" — retargeting both to a single material threw that away."""
+ m = probe
+ assert m["glazed"] >= 2, "no Glazing/Pane mesh was retargeted"
+ assert m["glazeIsPhysical"] and m["glazeEnv"], m
+ assert m["glazeIor"] > 1.5, (
+ f"ior {m['glazeIor']:.2f}: uncoated glass reflects ~4% head-on "
+ "and renders as a black hole"
+ )
+ assert m["glazeClearcoat"] >= 0.5, (
+ f"clearcoat {m['glazeClearcoat']} — without an untinted coat the "
+ "sky arrives on the glass multiplied by the glass's own near-black"
+ )
+ assert m["glazeMetalness"] <= 0.25, (
+ f"metalness {m['glazeMetalness']} tints and dims that much of the "
+ "reflection with the pane's own colour"
+ )
+ assert not m["glazeTransparent"], (
+ "opaque by default — transparent glazing stops writing depth"
+ )
+ assert m["batchesDiffer"] and m["batchEnvBoth"], (
+ "both pane batches got one material: building.js splits Glazing "
+ "and Glazing2 to keep a facade off one flat value, and glazeFacade "
+ "collapsed the split"
+ )
+ assert m["forcedOneMaterial"], (
+ "opts.material must be applied as-is — no variants behind the "
+ "caller's back"
+ )
+ assert m["revealsUntouched"], "glazeFacade put out the lit windows"
+ assert m["chromeMetal"] == 1 and m["chromeRough"] > 0, m
+ assert m["transFlag"] and abs(m["transOpacity"] - 0.6) < 1e-9, m
+
+
+def test_the_reflection_shader_is_the_addons_and_never_a_replacement():
+ """Retargeted, not dropped. Our renderer.js runs
+ `logarithmicDepthBuffer` OFF by default, but `--log-depth` is still a
+ host option, and a custom ShaderMaterial without the logdepthbuf chunks
+ is erased by any opaque geometry behind it under that flag. The addon
+ Reflector carries all four; this module must never hand it a
+ replacement shader, which is also why the glass tint below is a
+ material parameter and not a patched fragment."""
+ src = (LIB_DIR / "mirror.js").read_text(encoding="utf-8")
+ for banned in ("fragmentShader", "vertexShader", "onBeforeCompile",
+ "ShaderMaterial"):
+ assert banned not in src, (
+ f"mirror.js touches {banned} — a custom reflection shader "
+ "must include logdepthbuf_pars_vertex / logdepthbuf_vertex "
+ "/ logdepthbuf_pars_fragment / logdepthbuf_fragment"
+ )
+ addon = (NODE_MODULES / "three" / "examples" / "jsm" / "objects"
+ / "Reflector.js")
+ if not addon.is_file():
+ pytest.skip("no three.js addon install to read the Reflector from")
+ text = addon.read_text(encoding="utf-8")
+ for chunk in ("logdepthbuf_pars_vertex", "logdepthbuf_vertex",
+ "logdepthbuf_pars_fragment", "logdepthbuf_fragment"):
+ assert f"#include <{chunk}>" in text, (
+ f"the shipped Reflector lost <{chunk}> — every mirror will "
+ "vanish behind opaque geometry under --log-depth"
+ )
+
+
+def test_the_module_stays_dom_free_and_seeded():
+ """Asset code runs in a headless page with no canvas and must re-render
+ identically every round: Math.random and any DOM API are banned outright
+ (mulberry32 from noise.js is the one PRNG)."""
+ src = (LIB_DIR / "mirror.js").read_text(encoding="utf-8")
+ for banned in ("Math.random", "document.", "createElement",
+ "new Image", "canvas"):
+ assert banned not in src, f"mirror.js uses {banned}"
+
+
+def test_the_transfer_function_is_the_real_srgb_curve():
+ """A guard on the fix itself, cheap enough to keep. The encode has to be
+ the piecewise sRGB OETF, not a 1/2.2 power approximation: the two differ
+ by up to 4 bytes in the darks, which is exactly where the reflected city
+ lives."""
+ src = (LIB_DIR / "mirror.js").read_text(encoding="utf-8")
+ assert "0.0031308" in src and "1 / 2.4" in src, (
+ "mirror.js is not encoding with the piecewise sRGB transfer"
+ )
+ # and the curve it names is the right one, at the two ends and the knee
+ for lin, want in ((0.0, 0.0), (0.0031308, 0.04045), (1.0, 1.0)):
+ got = (lin * 12.92 if lin <= 0.0031308
+ else 1.055 * math.pow(lin, 1 / 2.4) - 0.055)
+ assert abs(got - want) < 1e-3, (lin, got, want)
diff --git a/harness/tests/scene_runtime/lib/test_neon.py b/harness/tests/scene_runtime/lib/test_neon.py
new file mode 100644
index 00000000..a19e3ea7
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_neon.py
@@ -0,0 +1,782 @@
+"""neon.js: the light a sign MAKES, and the light it throws.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_neon_lib.py). Their laws are kept as they stood — a tube that
+stops following its path draws a shape nobody asked for, a spill that never
+reaches zero leaves every wall in the scene washed by every sign, two lanes
+riding the same direction is a road where all the traffic goes one way, and
+added light is the default because a night city is the dark frame added
+light is correct over. Their GPU compile runs through
+`_probe.compile_scene`, which stages the fixture as a workspace
+`src/scene.js` — the shape `check_shaders.mjs` boots.
+
+THE PORT'S OWN LAWS — each one a frame rendered on our host at
+fx/out/neon/, looked at, and measured:
+
+1. THE ADDITIVE STACK IS BUDGETED FOR A HOST THAT TONE MAPS PER FRAGMENT.
+ Their renderer resolved a post chain, so an additive shell wrote linear
+ HDR and was tone mapped once at the end. Ours has no post chain: ACES
+ and sRGB run in the fragment tail and additive layers then sum in
+ DISPLAY space. The middle of a tube carries four such layers — the near
+ and far walls of the double-sided core, and the halo over them twice —
+ and the old gains put a sum of ~2.5 there, where every channel of every
+ colour clips. Both signs in the showcase rendered WHITE: measured, 29.9%
+ of the effect's glow pixels had all three channels past 0.90, and a cyan
+ tube's brightest pixel was (255, 255, 255). Budgeted to ~1.4 the strong
+ channel still clips (a tube must) and the weak ones sit where the hue
+ lives: 10.2% white core, cyan peak (241, 255, 255), and the harness's own
+ blown_frac for that view fell 0.0122 -> 0.0006 with mean_lum barely moved
+ (0.1445 -> 0.1371).
+
+2. THE GAS COLOUR SURVIVES THE MIDDLE OF THE GLASS. The whitening ran
+ `pow(face, 5.0) * hot`, which is more than half of the tube's width and
+ went all the way to white — applied BEFORE a 2.5x stack, so it was the
+ larger half of law 1. A fifth of the way to white, inside the middle
+ third, is a hot line in coloured glass instead.
+
+3. A HALO MAY NOT DRAW ITS OWN POLYGON. The chord weighting is exact for a
+ cylinder and the shell is an n-gon, so at the outermost facet the
+ interpolated normal is still 180/n degrees off perpendicular and the
+ glow ended on a live alpha — a 10-gon at 3.6 radii drew a visible
+ straight-edged crease around every letter. 18 sides and a toe on the
+ chord put that edge under the shader's own discard.
+
+4. HUE VARIANCE INSIDE EVERY EFFECT. One tube was one flat colour and five
+ vehicles were five copies of one lamp. The gas now drifts a few degrees
+ along each stroke (so a word bent one stroke per letter is four related
+ colours), and each vehicle carries its own colour temperature — spent as
+ a hue ROTATION, which moves a saturated tail-light, and as a warm/cool
+ TILT, which is the only thing that moves a near-white head-light. In the
+ rendered frame the tail lane went from five identical reds to amber,
+ salmon and deep red (crop pair fx/c_neon_trails_before.png ->
+ fx/c_neon_trails_after.png).
+
+5. EVERY WIDE GRADIENT CARRIES A DITHER. A halo, a metre-wide wash on
+ tarmac and a spill pool on a flat wall are the three softest ramps in
+ this library and all three banded in 8-bit output.
+"""
+
+from __future__ import annotations
+
+import json
+
+from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "neon.js", "surface_wear.js", "windows.js")
+
+# The scene our check_shaders.mjs boots. Fog, because a night sign ships
+# into a fogged scene and asset mode never defines USE_FOG; a camera,
+# because a scene with none is reported as not booted and never reaches
+# the compile stage at all; both blend modes, because `ambient` picks
+# between two different materials; and the wall material carrying the
+# spill CHAINED under two other patches, which is the namespace collision
+# that only shows up when three libraries share one material's GLSL.
+_SCENE = """
+import * as THREE from 'three';
+import { makeNeonTube, patchNeonSpill, makeLightTrails }
+ from './lib/neon.js';
+import { patchMicroBreakup } from './lib/surface_wear.js';
+import { patchWindowInteriors } from './lib/windows.js';
+
+export const BOUNDS = { min: [-24, 0, -12], max: [24, 12, 12] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0x05070d, 0.010);
+ scene.add(new THREE.HemisphereLight(0x0b1626, 0x04050a, 0.22));
+ const night = makeNeonTube({
+ path: [[[-1.2, 0, 0], [-1.2, 0.9, 0], [-0.4, 0.9, 0]],
+ [[0.3, 0, 0], [0.3, 0.9, 0]]],
+ radius: 0.05, color: 0xff2f74, flicker: 0.4, seed: 3 });
+ night.position.set(0, 3, -0.4);
+ scene.add(night);
+ const day = makeNeonTube({ radius: 0.05, ambient: 0.8, seed: 5 });
+ day.position.set(6, 3, -0.4);
+ scene.add(day);
+ const wallMat = new THREE.MeshStandardMaterial({ color: 0x3a2a26 });
+ patchMicroBreakup(wallMat, { scale: 0.5, strength: 0.14, seed: 5 });
+ patchWindowInteriors(wallMat, { rows: 4, cols: 8, lit: 0.3, seed: 4 });
+ patchNeonSpill(wallMat, {
+ sources: night.userData.spillSources(4), radius: 6, strength: 1.4,
+ flicker: 0.4, seed: 3 });
+ const wall = new THREE.Mesh(new THREE.BoxGeometry(14, 8, 0.4), wallMat);
+ wall.position.set(0, 4, 0);
+ scene.add(wall);
+ const trails = makeLightTrails({
+ path: [[-20, 0, 6], [0, 0, 7], [20, 0, 6]], count: 5, seed: 7 });
+ scene.add(trails);
+ const hazy = makeLightTrails({
+ path: [[-20, 0, 9], [20, 0, 9]], ambient: 0.9, seed: 8 });
+ scene.add(hazy);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [6, 3, 12], lookAt: [0, 3, 0],
+ fov: 45 }],
+ update(t) {
+ night.userData.tick(t); day.userData.tick(t);
+ trails.userData.tick(t); hazy.userData.tick(t);
+ },
+ };
+}
+"""
+
+# Pull a scalar GLSL helper out of the SHIPPED source and run it as JS.
+# The two dialects agree on everything here except the declarations, so
+# the numbers below are the numbers the GPU computes — not a second
+# implementation that could drift from the one that renders. `extra`
+# carries helpers this one calls, themselves extracted the same way, so a
+# hash is never re-written in JS either.
+_GLSL_AS_JS = """
+const glslFn = (src, name, args, extra) => {
+ const re = new RegExp('float ' + name + '\\\\(([\\\\s\\\\S]*?)\\\\)\\\\s*\\\\{');
+ const m = re.exec(src);
+ if (!m) throw new Error('no ' + name + '() in the shipped source');
+ let depth = 0, end = -1;
+ for (let i = src.indexOf('{', m.index); i < src.length; i++) {
+ if (src[i] === '{') depth++;
+ else if (src[i] === '}' && --depth === 0) { end = i; break; }
+ }
+ const body = src.slice(src.indexOf('{', m.index) + 1, end)
+ .replace(/\\bfloat\\b/g, 'let');
+ const names = Object.keys(extra || {});
+ const fn = new Function(...args, ...names, 'clamp', 'max', 'min',
+ 'fract', 'step', 'smoothstep', 'mix', 'pow',
+ 'exp', 'sin', 'floor', body);
+ return (...v) => fn(...v, ...names.map((k) => extra[k]),
+ (x, a, b) => Math.min(Math.max(x, a), b), Math.max, Math.min,
+ (x) => x - Math.floor(x),
+ (e, x) => (x < e ? 0 : 1),
+ (a, b, x) => {
+ const t = Math.min(Math.max((x - a) / (b - a), 0), 1);
+ return t * t * (3 - 2 * t);
+ },
+ (a, b, t) => a + (b - a) * t,
+ Math.pow, Math.exp, Math.sin, Math.floor);
+};
+"""
+
+# Distance from a point to a polyline: the one number that says whether a
+# swept body still rides the path it was given.
+_TO_PATH = """
+const toPath = (p, path) => {
+ let best = Infinity;
+ for (let i = 1; i < path.length; i++) {
+ const a = path[i - 1], b = path[i];
+ const dx = b[0] - a[0], dy = b[1] - a[1], dz = b[2] - a[2];
+ const ll = dx * dx + dy * dy + dz * dz;
+ let t = ll < 1e-12 ? 0
+ : ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy + (p[2] - a[2]) * dz)
+ / ll;
+ t = Math.min(1, Math.max(0, t));
+ best = Math.min(best, Math.hypot(p[0] - (a[0] + dx * t),
+ p[1] - (a[1] + dy * t),
+ p[2] - (a[2] + dz * t)));
+ }
+ return best;
+};
+"""
+
+# The peak DISPLAY alpha one shell writes, from the shipped uniforms and
+# the shipped roll-off. `face` is 1 down the axis of the tube, where the
+# toe is fully open, so the whole peak is the gain's own curve.
+_STACK = """
+const peak = (mesh) => {
+ const u = mesh.material.uniforms;
+ return 1 - Math.exp(-u.uGain.value * 1.6);
+};
+"""
+
+
+def test_every_program_compiles_in_a_fogged_scene():
+ """Every shader this module ships, on the GPU, in the scene shape it
+ ships into. Asset mode builds an UNFOGGED scene, so `USE_FOG` is
+ never defined and the fog branch of each of these shaders is never
+ compiled; neon ships into fogged night scenes, so the branch has to be
+ real. So does the normal-blended `ambient` branch, which is a
+ different material, and the spill chained under two other libraries'
+ patches, which is where a GLSL namespace collides."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "no fog chunks" not in out, out
+ # A green exit on an empty compile proves nothing: the scene holds two
+ # tubes (two shells each), two lanes of trails twice over and one
+ # patched wall, and every one of those nine has to have reached the
+ # GPU.
+ # A floor, not an equality: `custom_materials` also counts materials a
+ # sibling library staged into this scene patches, so an exact number
+ # here goes stale on somebody else's edit.
+ report = json.loads(out[out.index("{"):out.rindex("}") + 1])
+ assert report["compile"]["custom_materials"] >= 9, report
+ assert report["compile"]["programs"] >= 4, report
+
+
+def test_every_glow_mesh_is_kept_out_of_the_override_passes():
+ """GTAOPass redraws the scene with an OPAQUE override material, in
+ which a glow shell is a solid wall. The same guard stops the mesh
+ casting a shadow, which is what a light source must never do."""
+ out = measure("""
+import { makeNeonTube, makeLightTrails } from './lib/neon.js';
+
+const rows = [];
+for (const g of [makeNeonTube({ path: [[0, 0, 0], [0, 1, 0], [1, 1, 0]],
+ radius: 0.05, seed: 3 }),
+ makeLightTrails({ path: [[-9, 0, 0], [9, 0, 0]],
+ seed: 7 })]) {
+ g.traverse((o) => {
+ if (!o.isMesh) return;
+ rows.push({ name: o.name,
+ guarded: o.userData.astraNoOverride === true,
+ shadow: !!o.castShadow,
+ transparent: !!o.material.transparent });
+ });
+}
+console.log(JSON.stringify({ rows }));
+""", _LIBS)
+ rows = out["rows"]
+ assert len(rows) == 4, rows
+ for r in rows:
+ assert r["transparent"], r
+ assert r["guarded"], f"{r['name']} would be a solid wall to GTAO"
+ assert not r["shadow"], f"{r['name']} casts a shadow"
+
+
+def test_the_spill_falls_off_with_distance_and_stops_at_its_radius():
+ """Read straight out of the GLSL the patch ships. A bare inverse
+ square never reaches zero, so every wall in the scene would keep a wash
+ of every sign in it and the night would go flat — the windowed form is
+ what makes `radius` mean something."""
+ out = measure(_GLSL_AS_JS + """
+import * as THREE from 'three';
+import { patchNeonSpill } from './lib/neon.js';
+
+const m = new THREE.MeshStandardMaterial({ color: 0x333333 });
+patchNeonSpill(m, { sources: [[0, 0, 0]], radius: 4, strength: 1 });
+const patch = m.userData.astraPatches.find((p) => p.name === 'neon:spill');
+const fall = glslFn(patch.fragmentHead, 'astraNeonFall', ['d', 'r']);
+const curve = [];
+for (let i = 0; i <= 40; i++) curve.push(fall(i * 0.15, 4));
+console.log(JSON.stringify({
+ curve, at0: fall(0, 4), atR: fall(4, 4),
+ beyond: [fall(4.5, 4), fall(9, 4), fall(400, 4)],
+}));
+""", _LIBS)
+ assert out["at0"] > 0.9, out["at0"]
+ curve = out["curve"]
+ for a, b in zip(curve, curve[1:], strict=False):
+ assert b <= a, f"spill rises with distance: {a} -> {b}"
+ inside = [c for c in curve[:27] if c > 0]
+ assert len(inside) > 20 and inside[0] > 8 * inside[-1], inside
+ assert out["atR"] == 0, out["atR"]
+ assert out["beyond"] == [0, 0, 0], out["beyond"]
+
+
+def test_the_falloff_is_what_actually_lights_the_wall():
+ """A falloff nothing multiplies is decorative. The spill must reach
+ the frame through `totalEmissiveRadiance` (light ARRIVING on the
+ surface, which no albedo term can fake), weighted by how the surface
+ faces the source, with `instanceMatrix` folded in by hand — an
+ instanced facade is otherwise lit as though every copy sat at the mesh
+ origin."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchNeonSpill } from './lib/neon.js';
+
+const m = new THREE.MeshStandardMaterial();
+patchNeonSpill(m, { sources: [[0, 2, 0]], radius: 5 });
+const p = m.userData.astraPatches.find((q) => q.name === 'neon:spill');
+console.log(JSON.stringify({
+ body: p.fragmentBody, vert: p.vertexBody,
+ count: m.userData.uniforms.uNeonCount.value,
+ radius: m.userData.uniforms.uNeonRadius.value,
+}));
+""", _LIBS)
+ body = out["body"]
+ assert "astraNeonFall(d, uNeonRadius)" in body, body
+ assert "totalEmissiveRadiance +=" in body, body
+ assert "dot(nsN, dv" in body, body
+ assert "USE_INSTANCING" in out["vert"], out["vert"]
+ assert out["count"] == 1 and out["radius"] == 5, out
+
+
+def test_the_two_lanes_of_traffic_run_in_opposite_directions():
+ """Warm one way and red the other is what says a road has two
+ directions. Both lanes riding the same sign of `uDir` is a road where
+ every vehicle travels the same way — measured by tracking each lane's
+ comet HEADS along the shipped phase function."""
+ out = measure(_GLSL_AS_JS + """
+import { makeLightTrails } from './lib/neon.js';
+
+const g = makeLightTrails({ path: [[-20, 0, 0], [20, 0, 0]], count: 5,
+ speed: 14, seed: 7 });
+const heads = (mesh, t) => {
+ const u = mesh.material.uniforms;
+ const phase = glslFn(mesh.material.fragmentShader, 'astraTrailPhase',
+ ['v', 'dir', 't', 'rate', 'count']);
+ const at = (v) => phase(v, u.uDir.value, t, u.uRate.value,
+ u.uCount.value);
+ const out = [];
+ let prev = at(0);
+ for (let i = 1; i <= 20000; i++) {
+ const v = i / 20000, p = at(v);
+ if (Math.abs(prev - p) > 0.5) out.push(v);
+ prev = p;
+ }
+ return out;
+};
+const track = (mesh) => {
+ const a = heads(mesh, 0), b = heads(mesh, 0.05);
+ const near = a.reduce((x, y) => (Math.abs(y - 0.5) < Math.abs(x - 0.5)
+ ? y : x));
+ const to = b.reduce((x, y) => (Math.abs(y - near) < Math.abs(x - near)
+ ? y : x));
+ return { from: near, to, n: a.length };
+};
+const warm = g.getObjectByName('TrailsWarm');
+const cool = g.getObjectByName('TrailsCool');
+console.log(JSON.stringify({
+ warm: track(warm), cool: track(cool),
+ warmColor: warm.material.uniforms.uColor.value.toArray(),
+ coolColor: cool.material.uniforms.uColor.value.toArray(),
+ dirs: [warm.material.uniforms.uDir.value,
+ cool.material.uniforms.uDir.value],
+}));
+""", _LIBS)
+ warm, cool = out["warm"], out["cool"]
+ assert warm["n"] == 5 and cool["n"] == 5, out
+ assert warm["to"] > warm["from"], warm
+ assert cool["to"] < cool["from"], cool
+ assert out["dirs"][0] * out["dirs"][1] < 0, out["dirs"]
+ # Head-lights are warm white, tail-lights are red: the red lane must
+ # be unmistakably red, and the warm lane must not be.
+ wr, wg, wb = out["warmColor"]
+ cr, cg, cb = out["coolColor"]
+ assert wg > 0.55 * wr and wb > 0.3 * wr, out["warmColor"]
+ assert cg < 0.25 * cr and cb < 0.25 * cr, out["coolColor"]
+
+
+def test_the_trails_run_along_the_road_they_were_given():
+ """A streak that crosses the road instead of following it is the whole
+ effect lost. Every ribbon vertex stays inside the lane it was asked
+ for, the ribbons span the path end to end, and they lie ON the road
+ rather than floating over it."""
+ out = measure(_TO_PATH + """
+import { makeLightTrails } from './lib/neon.js';
+
+const path = [[-20, 0, 0], [0, 0, 6], [20, 0, 0]];
+const g = makeLightTrails({ path, count: 5, width: 0.5, lane: 2.0,
+ lift: 0.03, seed: 7 });
+const rows = {};
+g.traverse((o) => {
+ if (!o.isMesh) return;
+ const a = o.geometry.attributes.position.array;
+ let far = 0, minX = 1e9, maxX = -1e9, offY = 0;
+ for (let i = 0; i < a.length; i += 3) {
+ far = Math.max(far, toPath([a[i], 0, a[i + 2]], path));
+ minX = Math.min(minX, a[i]);
+ maxX = Math.max(maxX, a[i]);
+ offY = Math.max(offY, Math.abs(a[i + 1]));
+ }
+ rows[o.name] = { far, minX, maxX, offY };
+});
+console.log(JSON.stringify(rows));
+""", _LIBS)
+ # lane 2.0 + half the 3 m ribbon + the corner fillet's own bound.
+ tol = 2.0 + 0.5 * 3.0 + 4.0 / 4
+ for name, r in out.items():
+ assert r["far"] <= tol, f"{name} strays {r['far']:.2f} m off"
+ assert r["minX"] < -19.5 and r["maxX"] > 19.5, r
+ assert 0 < r["offY"] < 0.1, r
+
+
+def test_the_tube_follows_the_path_it_was_bent_along():
+ """The sign IS the path. A sweep that wanders off it draws a shape
+ nobody asked for, and a sweep that stops short leaves a letter
+ unfinished — so both bounds are checked."""
+ out = measure(_TO_PATH + """
+import { makeNeonTube } from './lib/neon.js';
+
+// One stroke per character, which is how a sign shop bends a word.
+const strokes = [[[0, 0, 0], [0, 1.2, 0], [0.7, 0, 0], [0.7, 1.2, 0]],
+ [[1.2, 0, 0], [1.2, 1.2, 0], [1.9, 1.2, 0],
+ [1.9, 0, 0], [1.2, 0, 0]]];
+const g = makeNeonTube({ path: strokes, radius: 0.05, bend: 0.3,
+ seed: 3 });
+const core = g.getObjectByName('NeonCore');
+const a = core.geometry.attributes.position.array;
+let far = 0;
+for (let i = 0; i < a.length; i += 3) {
+ far = Math.max(far, Math.min(
+ ...strokes.map((s) => toPath([a[i], a[i + 1], a[i + 2]], s))));
+}
+let gap = 0;
+for (const s of strokes) {
+ for (let k = 0; k <= 60; k++) {
+ const t = k / 60 * (s.length - 1);
+ const i = Math.min(s.length - 2, Math.floor(t)), f = t - i;
+ const p = [0, 1, 2].map((j) => s[i][j] + (s[i + 1][j] - s[i][j]) * f);
+ let near = Infinity;
+ for (let q = 0; q < a.length; q += 3) {
+ near = Math.min(near, Math.hypot(a[q] - p[0], a[q + 1] - p[1],
+ a[q + 2] - p[2]));
+ }
+ gap = Math.max(gap, near);
+ }
+}
+const single = makeNeonTube({ path: [[0, 0, 0], [2, 0, 0]], radius: 0.05 });
+console.log(JSON.stringify({
+ far, gap, verts: a.length / 3,
+ singleVerts: single.getObjectByName('NeonCore')
+ .geometry.attributes.position.count,
+}));
+""", _LIBS)
+ # radius, plus the bend/4 a filleted corner is allowed to cut.
+ assert out["far"] <= 0.05 + 0.3 / 4 + 1e-3, out["far"]
+ assert out["gap"] <= 0.05 + 0.3 / 4 + 0.02, out["gap"]
+ assert out["verts"] > 400, out
+ # A bare polyline is one stroke, not a stroke list, and still builds.
+ assert out["singleVerts"] > 100, out
+
+
+def test_the_same_seed_builds_the_same_sign_twice():
+ """No Math.random anywhere: two runs of one brief must be the same
+ frame, and a different seed must change the stutter rather than the
+ glass — a re-seeded sign is the same sign, flickering differently."""
+ out = measure("""
+import { makeNeonTube, makeLightTrails } from './lib/neon.js';
+
+const tube = (seed) => {
+ const g = makeNeonTube({ path: [[0, 0, 0], [0, 1, 0], [1, 1, 0]],
+ radius: 0.05, flicker: 0.5, seed });
+ const c = g.getObjectByName('NeonCore');
+ return { pos: Array.from(c.geometry.attributes.position.array),
+ key: c.material.uniforms.uKey.value };
+};
+const trail = (seed) => makeLightTrails({ seed })
+ .getObjectByName('TrailsWarm').material.uniforms.uKey.value;
+const a = tube(3), b = tube(3), c = tube(4);
+console.log(JSON.stringify({
+ same: a.pos.length === b.pos.length
+ && a.pos.every((v, i) => v === b.pos[i]),
+ sameKey: a.key === b.key,
+ otherKey: c.key,
+ geomStable: a.pos.every((v, i) => v === c.pos[i]),
+ trails: [trail(7), trail(7), trail(8)],
+}));
+""", _LIBS)
+ assert out["same"] and out["sameKey"], out
+ assert out["otherKey"] != out["sameKey"], out
+ assert out["geomStable"], out
+ t = out["trails"]
+ assert t[0] == t[1] and t[0] != t[2], t
+
+
+def test_one_tick_advances_every_material_in_the_group():
+ """A shader whose uTime never moves is a still frame inside a moving
+ one. `tick` has to reach the halo as well as the core, both lanes,
+ and the spill patch through `tickShaders`."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeNeonTube, patchNeonSpill, makeLightTrails }
+ from './lib/neon.js';
+import { tickShaders } from './lib/shader.js';
+
+const sign = makeNeonTube({ path: [[0, 0, 0], [0, 1, 0]], seed: 3 });
+const trails = makeLightTrails({ seed: 7 });
+const n = sign.userData.tick(4.25) + trails.userData.tick(4.25);
+const times = [];
+for (const g of [sign, trails]) {
+ g.traverse((o) => {
+ if (o.isMesh) times.push(o.material.uniforms.uTime.value);
+ });
+}
+const wall = new THREE.MeshStandardMaterial();
+patchNeonSpill(wall, { sources: [[0, 3, 0]], radius: 5 });
+const mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), wall);
+const m = tickShaders(mesh, 4.25);
+console.log(JSON.stringify({
+ n, times, patched: [m, wall.userData.uniforms.uTime.value],
+}));
+""", _LIBS)
+ assert out["n"] == 4, out
+ assert out["times"] == [4.25] * 4, out
+ assert out["patched"] == [1, 4.25], out
+
+
+def test_added_light_is_the_default_and_daylight_is_the_escape():
+ """Added light survives a DARK frame and clips over a bright one, and
+ a night city is the dark frame — so additive is the default. The
+ escape has to sit BELOW the middle of the range: a composer handed
+ "0 an unlit street to 1 open daylight" and no instinct picks 0.5, and
+ 0.5 must be the mode that cannot clip."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeNeonTube, patchNeonSpill, makeLightTrails }
+ from './lib/neon.js';
+
+const mode = (g) => {
+ const out = [];
+ g.traverse((o) => {
+ if (o.isMesh) out.push(o.material.blending === THREE.AdditiveBlending);
+ });
+ return out;
+};
+const gain = (amb) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchNeonSpill(m, { sources: [[0, 3, 0]], radius: 5, strength: 1,
+ ambient: amb });
+ return m.userData.uniforms.uNeonGain.value;
+};
+console.log(JSON.stringify({
+ night: mode(makeNeonTube({})).concat(mode(makeLightTrails({}))),
+ mid: mode(makeNeonTube({ ambient: 0.5 }))
+ .concat(mode(makeLightTrails({ ambient: 0.5 }))),
+ day: mode(makeNeonTube({ ambient: 1 }))
+ .concat(mode(makeLightTrails({ ambient: 1 }))),
+ gains: [gain(undefined), gain(0.5), gain(1)],
+}));
+""", _LIBS)
+ assert out["night"] == [True] * 4, out["night"]
+ assert out["mid"] == [False] * 4, out["mid"]
+ assert out["day"] == [False] * 4, out["day"]
+ g = out["gains"]
+ assert g[0] > g[1] > g[2] >= 0, g
+
+
+def test_a_sign_hands_its_own_light_over_to_the_wall_behind_it():
+ """The bridge that makes "the sign lights its wall" one line: the
+ sources come back in WORLD space through the group's current matrix,
+ so placing the sign moves the light it throws. Sources read off an
+ unplaced group light the world origin instead."""
+ out = measure("""
+import { makeNeonTube } from './lib/neon.js';
+
+const g = makeNeonTube({ path: [[-1, 0, 0], [1, 0, 0]], radius: 0.05,
+ color: 0x00ff88, seed: 3 });
+const before = g.userData.spillSources(4);
+g.position.set(10, 4, -2);
+const after = g.userData.spillSources(4);
+console.log(JSON.stringify({
+ n: after.length,
+ capped: g.userData.spillSources(99).length,
+ before: before.map((s) => s.position.toArray()),
+ after: after.map((s) => s.position.toArray()),
+ color: after[0].color.toArray(),
+ spread: Math.max(...after.map((s) => s.position.x))
+ - Math.min(...after.map((s) => s.position.x)),
+}));
+""", _LIBS)
+ assert out["n"] == 4 and out["capped"] == 8, out
+ for b, a in zip(out["before"], out["after"], strict=True):
+ assert [round(v, 6) for v in a] == [
+ round(b[0] + 10, 6), round(b[1] + 4, 6), round(b[2] - 2, 6)], out
+ assert out["color"][1] > 0.5 and out["color"][0] < 0.1, out["color"]
+ # Spread along the tube, not four copies of one point.
+ assert out["spread"] > 1.0, out["spread"]
+
+
+# ---------------------------------------------------------------------
+# The port's own laws.
+
+
+def test_the_additive_stack_is_budgeted_for_a_host_that_tone_maps():
+ """LAW 1. No post chain here: ACES and sRGB run in the fragment tail,
+ so additive layers sum in DISPLAY space. The middle of a tube carries
+ four of them — the near and far walls of the double-sided core, and
+ the halo twice over — and a sum past ~2 clips every channel of every
+ colour, which is a white sign whatever gas it holds. It still has to
+ reach past 1, because a tube that cannot clip its strongest channel
+ does not read as a light source at all."""
+ out = measure(_STACK + """
+import { makeNeonTube } from './lib/neon.js';
+
+const g = makeNeonTube({ path: [[-1, 0, 0], [1, 0, 0]], seed: 3 });
+const core = g.getObjectByName('NeonCore');
+const halo = g.getObjectByName('NeonHalo');
+const day = makeNeonTube({ path: [[-1, 0, 0], [1, 0, 0]], ambient: 0.8 });
+console.log(JSON.stringify({
+ core: peak(core), halo: peak(halo),
+ sides: [core.material.side, halo.material.side],
+ double: 2,
+ dayCore: peak(day.getObjectByName('NeonCore')),
+ dayAdditive: day.getObjectByName('NeonCore').material.blending,
+}));
+""", _LIBS)
+ # Both shells are double-sided, so each is read twice on the middle
+ # of the glass; that is the whole point of the chord weighting.
+ stack = 2 * (out["core"] + out["halo"])
+ assert 1.05 < stack < 1.80, (stack, out)
+ # And the core is the larger half of it: a halo that outweighs its own
+ # tube is fog with a line in it.
+ assert out["core"] > out["halo"], out
+ # The normal-blended daylight branch is a different budget: nothing
+ # stacks there, so it is allowed to stay strong.
+ assert out["dayCore"] > 0.9, out
+
+
+def test_the_gas_colour_survives_the_middle_of_the_glass():
+ """LAW 2, read out of the shipped GLSL and run as arithmetic. The
+ filament is what whitens the core, and applied before the display-space
+ stack of law 1 it is what threw the colour away: at the old
+ `pow(face, 5.0) * hot` all the way to white, a cyan tube's red channel
+ arrived at 0.90 of its blue and the tube rendered grey."""
+ out = measure(_GLSL_AS_JS + """
+import { makeNeonTube } from './lib/neon.js';
+
+const g = makeNeonTube({ path: [[-1, 0, 0], [1, 0, 0]], color: 0x2ad7ff,
+ seed: 3 });
+const core = g.getObjectByName('NeonCore');
+const src = core.material.fragmentShader;
+const fil = glslFn(src, 'astraNeonFilament', ['face', 'hot']);
+const hot = core.material.uniforms.uHot.value;
+const gas = core.material.uniforms.uColor.value.toArray();
+// The colour the shader writes: mix(gas, vec3(1.0), filament).
+const at = (face) => gas.map(
+ (v) => v + (1 - v) * fil(face, hot));
+console.log(JSON.stringify({
+ hot,
+ peak: fil(1.0, hot),
+ curve: [0.6, 0.7, 0.8, 0.9, 0.95, 1.0].map((f) => fil(f, hot)),
+ mid: at(1.0), edge: at(0.8),
+}));
+""", _LIBS)
+ # Never more than a fifth of the way to white, even dead centre.
+ assert 0.05 < out["peak"] <= 0.21, out
+ curve = out["curve"]
+ for a, b in zip(curve, curve[1:], strict=False):
+ assert b >= a, curve
+ # Confined to the middle of the glass: two thirds of the way out it is
+ # already invisible, which is what leaves the flanks fully coloured.
+ assert curve[2] < 0.02, curve
+ # And the gas is still cyan where it is hottest: the weak channel of a
+ # saturated colour stays far below the strong one.
+ r, gg, b = out["mid"]
+ assert r < 0.35 * b, out["mid"]
+ assert out["edge"][0] < 0.10 * out["edge"][2], out["edge"]
+
+
+def test_the_halo_shell_never_draws_its_own_polygon():
+ """LAW 3. `astraFacing` is the exact chord through a CYLINDER and the
+ shell is an n-gon, so at the outermost facet the interpolated normal is
+ still 180/n degrees off perpendicular and the glow ends on a live
+ alpha. At 10 sides and 3.6 radii that was a straight-edged crease
+ drawn around every letter. Measured here at the worst facet the shell
+ has, against the shader's own discard."""
+ out = measure("""
+import { makeNeonTube } from './lib/neon.js';
+
+const g = makeNeonTube({ path: [[-1, 0, 0], [1, 0, 0]], radius: 0.05,
+ halo: 3.6, seed: 3 });
+const rows = {};
+for (const name of ['NeonHalo', 'NeonCore']) {
+ const m = g.getObjectByName(name);
+ const uv = m.geometry.attributes.uv.array;
+ const us = new Set();
+ for (let i = 0; i < uv.length; i += 2) us.add(uv[i].toFixed(5));
+ const u = m.material.uniforms;
+ // The shipped roll-off, at the worst normal a facet boundary carries.
+ const sides = us.size - 1;
+ const face = Math.sin(Math.PI / sides);
+ const t = Math.min(Math.max(face / u.uToe.value, 0), 1);
+ const body = Math.pow(face, u.uCore.value) * t * t * (3 - 2 * t);
+ rows[name] = { sides, face,
+ alpha: 1 - Math.exp(-u.uGain.value * body * 1.6),
+ toe: u.uToe.value };
+}
+console.log(JSON.stringify(rows));
+""", _LIBS)
+ halo = out["NeonHalo"]
+ # A 10-gon is what drew the polygon; the halo is the widest shell in
+ # the effect and needs the sides.
+ assert halo["sides"] >= 16, halo
+ assert halo["toe"] >= 0.4, halo
+ # Under the shader's own `if (a < 0.003) discard`, so the last facet is
+ # never drawn at all rather than drawn faintly.
+ assert halo["alpha"] < 0.003, halo
+ # The core is exempt from the alpha bound and not from the sides: its
+ # rim IS the edge of the glass and is meant to be visible, but at a
+ # tenth of the halo's radius its facets land inside a pixel, so all it
+ # needs is a silhouette round enough not to read as a prism.
+ assert out["NeonCore"]["sides"] >= 12, out["NeonCore"]
+
+
+def test_a_lane_is_traffic_and_not_one_lamp_copied():
+ """LAW 4, the road half. Five vehicles sharing one colour is a lane
+ of clones. The temperature offset is read out of the shipped GLSL,
+ with the hash it calls extracted the same way rather than rewritten,
+ and it has to SPREAD across the vehicles a lane actually carries — and
+ to be spent both ways, because a rotation alone leaves a near-white
+ head-light exactly where it was."""
+ out = measure(_GLSL_AS_JS + """
+import { makeLightTrails } from './lib/neon.js';
+
+const g = makeLightTrails({ count: 5, seed: 7 });
+const rows = {};
+for (const name of ['TrailsWarm', 'TrailsCool']) {
+ const m = g.getObjectByName(name);
+ const src = m.material.fragmentShader;
+ const hash = glslFn(src, 'astraHash11', ['p']);
+ const temp = glslFn(src, 'astraTrailTemp', ['id', 'vary'],
+ { astraHash11: hash });
+ const key = m.material.uniforms.uKey.value;
+ const vary = m.material.uniforms.uVary.value;
+ const ws = [];
+ for (let i = 0; i < 5; i++) ws.push(temp(i + key, vary));
+ rows[name] = { vary, ws, spread: Math.max(...ws) - Math.min(...ws),
+ rotates: src.includes('astraHueShift(uColor, w)'),
+ tilts: src.includes('vec3(1.0 + w') };
+}
+console.log(JSON.stringify(rows));
+""", _LIBS)
+ for name, r in out.items():
+ assert r["vary"] > 0, (name, r)
+ # Both lanes: five vehicles, five different lamps.
+ assert len(set(round(w, 6) for w in r["ws"])) == 5, (name, r)
+ assert r["spread"] > 0.25 * r["vary"], (name, r)
+ # A rotation is what moves a saturated tail-light and a warm/cool
+ # tilt is the only thing that moves a near-white head-light, so a
+ # library that ships both colours needs both.
+ assert r["rotates"] and r["tilts"], (name, r)
+ # The head-lights vary more than the tail-lights: a lane of white
+ # lamps has nothing else to tell one car from the next.
+ assert out["TrailsWarm"]["vary"] > out["TrailsCool"]["vary"], out
+
+
+def test_the_gas_drifts_along_the_tube_and_every_ramp_is_dithered():
+ """LAWS 4 and 5, the sign half. One flat colour along a bent tube is
+ a printed decal; the drift rides the stroke's own v, so a word bent
+ one stroke per letter comes out four related colours. And the three
+ widest ramps in this module — the halo, the wash on tarmac and the
+ spill pool on a flat wall — all banded in 8-bit output until each
+ carried a hash jitter."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeNeonTube, patchNeonSpill, makeLightTrails }
+ from './lib/neon.js';
+
+const sign = makeNeonTube({ path: [[-1, 0, 0], [1, 0, 0]], seed: 3 });
+const trails = makeLightTrails({ seed: 7 });
+const wall = new THREE.MeshStandardMaterial();
+patchNeonSpill(wall, { sources: [[0, 3, 0]], radius: 5 });
+const spill = wall.userData.astraPatches
+ .find((p) => p.name === 'neon:spill');
+const rows = {};
+for (const g of [sign, trails]) {
+ g.traverse((o) => {
+ if (!o.isMesh) return;
+ const src = o.material.fragmentShader;
+ rows[o.name] = {
+ dither: src.includes('astraHash21(gl_FragCoord.xy'),
+ vary: o.material.uniforms.uVary.value,
+ drifts: src.includes('astraHueShift(uColor, drift * uVary)'),
+ };
+ });
+}
+rows.spill = { dither: spill.fragmentBody
+ .includes('astraHash21(gl_FragCoord.xy') };
+console.log(JSON.stringify(rows));
+""", _LIBS)
+ for name, r in out.items():
+ assert r["dither"], f"{name} lays a wide ramp with no dither"
+ for name in ("NeonCore", "NeonHalo"):
+ assert out[name]["vary"] > 0 and out[name]["drifts"], out[name]
diff --git a/harness/tests/scene_runtime/lib/test_noise.py b/harness/tests/scene_runtime/lib/test_noise.py
new file mode 100644
index 00000000..c4f2b09f
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_noise.py
@@ -0,0 +1,85 @@
+"""noise.js — seeded, non-flat, tiling; measured under node.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference (tests/test_noise_lib.py).
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import measure
+
+pytestmark = pytest.mark.node
+
+_PROBE = """
+import * as THREE from 'three';
+import { mulberry32, fbm2, fbm3, noiseDataTexture, displaceY } from './lib/noise.js';
+
+const build = (seed) => {
+ const g = new THREE.PlaneGeometry(160, 160, 64, 64);
+ g.rotateX(-Math.PI / 2);
+ displaceY(g, 14, 0.02, seed);
+ return g;
+};
+const a = build(3).attributes.position, b = build(3).attributes.position, c = build(9).attributes.position;
+let minY = 1e9, maxY = -1e9, maxSame = 0, maxOther = 0;
+for (let i = 0; i < a.count; i++) {
+ minY = Math.min(minY, a.getY(i)); maxY = Math.max(maxY, a.getY(i));
+ maxSame = Math.max(maxSame, Math.abs(a.getY(i) - b.getY(i)));
+ maxOther = Math.max(maxOther, Math.abs(a.getY(i) - c.getY(i)));
+}
+const n = build(3).attributes.normal;
+let tilted = 0;
+for (let i = 0; i < n.count; i++) if (n.getY(i) < 0.999) tilted++;
+
+const tex = noiseDataTexture(64, (u, v) => 0.5 + 0.5 * fbm2(u * 6, v * 6, { seed: 5 }));
+const d = tex.image.data;
+let tMin = 255, tMax = 0;
+for (let i = 0; i < d.length; i += 4) { tMin = Math.min(tMin, d[i]); tMax = Math.max(tMax, d[i]); }
+
+const r1 = mulberry32(42), r2 = mulberry32(42);
+let seqSame = true, inRange = true;
+for (let i = 0; i < 100; i++) { const v1 = r1(), v2 = r2(); if (v1 !== v2) seqSame = false; if (!(v1 >= 0 && v1 < 1)) inRange = false; }
+
+let fMin = 1e9, fMax = -1e9, fDiff = 0;
+for (let i = 0; i < 400; i++) {
+ const x = (i % 20) * 0.37, z = Math.floor(i / 20) * 0.53;
+ const v = fbm2(x, z, { seed: 1 });
+ fMin = Math.min(fMin, v); fMax = Math.max(fMax, v);
+ fDiff = Math.max(fDiff, Math.abs(v - fbm2(x, z, { seed: 2 })));
+ const v3 = fbm3(x, 0.7, z, { octaves: 5 });
+ fMin = Math.min(fMin, v3); fMax = Math.max(fMax, v3);
+}
+console.log(JSON.stringify({ yRange: maxY - minY, maxSame, maxOther, tiltedFrac: tilted / n.count,
+ wraps: tex.wrapS === THREE.RepeatWrapping && tex.wrapT === THREE.RepeatWrapping,
+ mipmapped: tex.minFilter === THREE.LinearMipmapLinearFilter && tex.generateMipmaps === true,
+ texSpread: tMax - tMin, seqSame, inRange, fMin, fMax, fDiff }));
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ return measure(_PROBE, ("noise.js",))
+
+
+def test_displaced_plane_is_not_flat_and_normals_follow(probe):
+ assert probe["yRange"] > 5, probe["yRange"]
+ assert probe["tiltedFrac"] > 0.5, probe["tiltedFrac"]
+
+
+def test_same_seed_rebuilds_the_identical_terrain(probe):
+ assert probe["maxSame"] == 0 and probe["maxOther"] > 0.5, probe
+
+
+def test_noise_texture_wraps_filters_and_is_non_uniform(probe):
+ """RepeatWrapping for tiled maps, mipmaps so a puddle mask does not tear
+ into stair-steps at grazing angles, and real content."""
+ assert probe["wraps"] and probe["mipmapped"]
+ assert probe["texSpread"] > 30, probe["texSpread"]
+
+
+def test_mulberry32_is_reproducible_and_uniform_range(probe):
+ assert probe["seqSame"] and probe["inRange"]
+
+
+def test_fbm_stays_normalized(probe):
+ assert probe["fMin"] >= -1.001 and probe["fMax"] <= 1.001, probe
+ assert probe["fMax"] - probe["fMin"] > 0.5 and probe["fDiff"] > 0.1, probe
diff --git a/harness/tests/scene_runtime/lib/test_place.py b/harness/tests/scene_runtime/lib/test_place.py
new file mode 100644
index 00000000..04f54ed1
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_place.py
@@ -0,0 +1,418 @@
+"""place.js — cameras and placements ship as derived quantities.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_place_lib.py). The reference scenario is kept whole: a bumpy
+ground, a camera requested 1 m UNDER it and 0.4 m from a wall, and a 10x24x8
+tower to bbox-fit — the measured failure shape (5 of 8 audited failing scenes
+shipped cameras buried under their own terrain or pressed into a facade). It
+needed no retargeting: place.js is arithmetic over three.js objects, with no
+renderer contract in it at all.
+
+Everything from ``test_an_interior_camera_stays_under_its_own_ceiling`` down
+covers what the port FIXED, each one measured on this host before the change:
+
+* the down-ray that grounds things started far overhead and took its NEAREST
+ hit, i.e. the top of the column — so anything with a roof over it flew UP
+ onto that roof. A crate under a 3 m arch seated at y 3.62, and an interior
+ camera handed its room group (which is exactly what the catalog tells
+ composers to pass indoors) shipped at eye 4.60 in a room whose ceiling tops
+ out at 3.00. Both now resolve the surface UNDER the body, and only fall
+ back to the lowest surface above it when there is nothing under it at all —
+ which is what still lifts an object authored at y = 0 onto a hillside;
+* ``establishingShot`` never checked whether anything stood between the eye
+ and the hero: a hero behind a 9 m ridge shipped a frame filled by ridge at
+ 1.19 m of an 8.92 m shot. It now slides along the fit sphere — up first,
+ then around, re-fitting at each candidate — instead of retreating the way
+ ``shot()`` does, because backing away shrinks the hero the shot exists to
+ show;
+* ``route()`` rolled wheels from ``s``, which only ever grows, so a cart on
+ the return leg of a ping-pong path drove backwards with its wheels spinning
+ forwards (-0.4 m of travel against +0.8 rad of wheel);
+* ``alongPath`` divided an OPEN path by n instead of n-1, so a row stopped a
+ whole gap short of its own last waypoint (6 posts over a 12 m quay ended at
+ x = 10, and the missing post is visible in the showcase frame).
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("place.js",)
+
+
+def _measure(script: str) -> dict:
+ return measure(script, _LIBS)
+
+
+# --- the reference's own probe, kept whole -------------------------------
+
+_PROBE = """
+import * as THREE from 'three';
+import { shot, establishingShot } from './lib/place.js';
+
+// A bumpy ground whose surface sits around y = 3.
+const geo = new THREE.PlaneGeometry(80, 80, 40, 40);
+geo.rotateX(-Math.PI / 2);
+const gp = geo.attributes.position;
+for (let i = 0; i < gp.count; i++) {
+ gp.setY(i, 3 + Math.sin(gp.getX(i) * 0.35) * 1.2
+ + Math.cos(gp.getZ(i) * 0.25) * 0.8);
+}
+geo.computeVertexNormals();
+const ground = new THREE.Mesh(geo, new THREE.MeshBasicMaterial());
+ground.updateMatrixWorld(true);
+
+const groundAt = (x, z) => {
+ const r = new THREE.Raycaster(new THREE.Vector3(x, 200, z),
+ new THREE.Vector3(0, -1, 0));
+ return r.intersectObject(ground, true)[0].point.y;
+};
+const surfaceY = groundAt(0, 0);
+
+// A wall directly between the camera and its subject, 0.4 m away.
+const wall = new THREE.Mesh(new THREE.BoxGeometry(30, 40, 0.5),
+ new THREE.MeshBasicMaterial());
+wall.position.set(0, surfaceY + 20, -0.65); // near face at z = -0.4
+wall.updateMatrixWorld(true);
+
+// The measured failure shape: requested 1 m BELOW the surface and
+// 0.4 m from a wall that fills the frame.
+const cam = shot('street', [0, surfaceY - 1, 0], [0, surfaceY + 2, -30],
+ 55, [ground, wall]);
+
+// Re-check the shipped entry the way the census would.
+const cpos = new THREE.Vector3(...cam.position);
+const cdir = new THREE.Vector3(...cam.lookAt).sub(cpos);
+const cdist = cdir.length();
+const ray = new THREE.Raycaster(cpos, cdir.clone().normalize());
+ray.far = cdist;
+const hits = ray.intersectObjects([ground, wall], true);
+
+// Hero fit: a 10 x 24 x 8 tower standing on the ground.
+const hero = new THREE.Mesh(new THREE.BoxGeometry(10, 24, 8),
+ new THREE.MeshBasicMaterial());
+hero.position.set(0, groundAt(0, 0) + 12, 0);
+hero.updateMatrixWorld(true);
+const est = establishingShot('establishing', hero,
+ { azDeg: 40, elDeg: 25, fov: 45, coverage: 0.8, surfaces: ground });
+const ecam = new THREE.PerspectiveCamera(est.fov, 16 / 9, 0.1, 1e6);
+ecam.position.set(...est.position);
+ecam.lookAt(new THREE.Vector3(...est.lookAt));
+ecam.updateMatrixWorld(true);
+const hbox = new THREE.Box3().setFromObject(hero);
+let inside = 0;
+let maxExt = 0;
+for (const cx of [hbox.min.x, hbox.max.x])
+ for (const cy of [hbox.min.y, hbox.max.y])
+ for (const cz of [hbox.min.z, hbox.max.z]) {
+ const ndc = new THREE.Vector3(cx, cy, cz).project(ecam);
+ if (Math.abs(ndc.x) <= 1 && Math.abs(ndc.y) <= 1
+ && Math.abs(ndc.z) <= 1) inside++;
+ maxExt = Math.max(maxExt, Math.abs(ndc.x), Math.abs(ndc.y));
+ }
+
+// A grazing establishing shot of a small hero must still clear the
+// ground under the eye.
+const small = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2),
+ new THREE.MeshBasicMaterial());
+small.position.set(10, groundAt(10, 0) + 1, 0);
+small.updateMatrixWorld(true);
+const low = establishingShot('low', small,
+ { azDeg: 10, elDeg: 2, fov: 45, coverage: 0.8, surfaces: ground });
+
+console.log(JSON.stringify({
+ surfaceY,
+ camY: cam.position[1],
+ groundAtCam: groundAt(cam.position[0], cam.position[2]),
+ firstHit: hits.length ? hits[0].distance : null,
+ clearNeeded: Math.max(2, cdist * 0.05),
+ inside,
+ maxExt,
+ estY: est.position[1],
+ lowY: low.position[1],
+ lowGround: groundAt(low.position[0], low.position[2]),
+}));
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch of _PROBE, shared by every test that reads it."""
+ return _measure(_PROBE)
+
+
+def test_a_buried_camera_is_lifted_above_the_ground_it_shoots_from(probe):
+ """A camera below its own terrain photographs the unlit backside.
+
+ The Santorini failure: 3 of 5 authored cameras below the exported
+ h(x, z), including the establishing shot.
+ """
+ m = probe
+ assert m["camY"] > m["surfaceY"] + 1.5, m
+ assert m["camY"] > m["groundAtCam"] + 1.5, m
+
+
+def test_a_wall_pressed_camera_backs_off_to_clear_frame(probe):
+ """Nothing may fill the frame from closer than max(2m, 5% dist)."""
+ m = probe
+ assert (m["firstHit"] is None
+ or m["firstHit"] >= m["clearNeeded"] - 1e-6), m
+
+
+def test_establishing_shot_frames_the_hero(probe):
+ """>= 6 of 8 bbox corners must land inside NDC — the fitted dolly."""
+ m = probe
+ assert m["inside"] >= 6, m
+ assert 0.4 < m["maxExt"] <= 1.05, m
+
+
+def test_a_low_establishing_shot_still_clears_the_ground(probe):
+ """The fit dolly can land the eye underground; the seat ray must
+ lift it, exactly as shot() does."""
+ m = probe
+ assert m["lowY"] >= m["lowGround"] + 1.6 - 0.01, m
+
+
+# --- what the port fixed -------------------------------------------------
+
+_PORT = """
+import * as THREE from 'three';
+import { shot, establishingShot, seat, alongPath, route, crowdOn }
+ from './lib/place.js';
+
+const basic = () => new THREE.MeshBasicMaterial();
+const out = {};
+
+// A room with a real ceiling — the catalog tells composers to hand the
+// whole room group to shot(), not just the floor.
+const room = new THREE.Group();
+const floor = new THREE.Mesh(new THREE.BoxGeometry(6, 0.2, 6), basic());
+floor.position.y = -0.1; // top at y = 0
+room.add(floor);
+const ceil = new THREE.Mesh(new THREE.BoxGeometry(6, 0.2, 6), basic());
+ceil.position.y = 2.9; // ceiling slab, top at 3.0
+room.add(ceil);
+const backWall = new THREE.Mesh(new THREE.BoxGeometry(6, 2.8, 0.2), basic());
+backWall.position.set(0, 1.4, -2.9);
+room.add(backWall);
+room.updateMatrixWorld(true);
+const interior = shot('interior', [0, 1.65, 2.0], [0, 1.2, -2.6], 50, [room]);
+out.interiorEyeY = interior.position[1];
+out.ceilingTop = 3.0;
+// ... and a room too LOW for the 1.6 m clearance still keeps the eye in it.
+const low = new THREE.Group();
+const lowFloor = floor.clone(); low.add(lowFloor);
+const lowCeil = new THREE.Mesh(new THREE.BoxGeometry(6, 0.2, 6), basic());
+lowCeil.position.y = 1.7; // ceiling top at 1.8
+low.add(lowCeil);
+low.updateMatrixWorld(true);
+out.lowRoomEyeY = shot('low', [0, 1.2, 2.0], [0, 1.0, -2.0], 50,
+ [low]).position[1];
+
+// seat(): a crate under an arch stays under the arch.
+const gnd = new THREE.Mesh(new THREE.BoxGeometry(400, 0.2, 400), basic());
+gnd.position.y = -0.1; // top at y = 0
+gnd.updateMatrixWorld(true);
+const arch = new THREE.Mesh(new THREE.BoxGeometry(4, 0.3, 4), basic());
+arch.position.set(0, 3, 0); // underside 2.85, top 3.15
+arch.updateMatrixWorld(true);
+const crate = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), basic());
+crate.position.set(0, 0.5, 0);
+seat(crate, [gnd, arch]);
+out.crateUnderArchY = crate.position.y;
+// the quay/seabed rule is unchanged: what is UNDER the object wins.
+const quay = new THREE.Mesh(new THREE.BoxGeometry(8, 1, 8), basic());
+quay.position.set(0, 1.5, 0); // deck top at 2.0
+quay.updateMatrixWorld(true);
+const seabed = new THREE.Mesh(new THREE.BoxGeometry(40, 0.2, 40), basic());
+seabed.position.y = -3.1;
+seabed.updateMatrixWorld(true);
+const barrel = new THREE.Mesh(new THREE.BoxGeometry(0.8, 0.8, 0.8), basic());
+barrel.position.set(0, 6, 0);
+seat(barrel, [seabed, quay]);
+out.barrelOnQuayY = barrel.position.y;
+// an object authored at y = 0 on a hillside — nothing under it at all,
+// so the LOWEST surface above wins and the hut is lifted onto the hill.
+const hill = new THREE.Mesh(new THREE.BoxGeometry(20, 0.4, 20), basic());
+hill.position.set(600, 12, 0); // top at 12.2, off the plate
+hill.updateMatrixWorld(true);
+const hut = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), basic());
+hut.position.set(600, 1, 0);
+seat(hut, [gnd, hill]);
+out.hutOnHillY = hut.position.y;
+
+// establishingShot(): a ridge between the eye and the hero.
+const hero = new THREE.Mesh(new THREE.BoxGeometry(3, 4, 3), basic());
+hero.position.set(0, 2, 0);
+hero.updateMatrixWorld(true);
+const ridge = new THREE.Mesh(new THREE.BoxGeometry(40, 9, 3), basic());
+ridge.position.set(0, 4.5, 6); // a wall 6 m to +z of it
+ridge.updateMatrixWorld(true);
+const est = establishingShot('est', hero, { azDeg: 90, elDeg: 14, fov: 45,
+ coverage: 0.7, surfaces: [gnd, ridge] });
+const ep = new THREE.Vector3(...est.position);
+const ec = new THREE.Vector3(...est.lookAt);
+const dir = ec.clone().sub(ep);
+const dist = dir.length();
+const ray = new THREE.Raycaster(ep, dir.clone().normalize());
+ray.far = dist;
+const rh = ray.intersectObjects([gnd, ridge], true);
+out.estBlockedAt = rh.length ? rh[0].distance : null;
+out.estClearNeeded = Math.max(2, dist * 0.05);
+const ecam = new THREE.PerspectiveCamera(est.fov, 16 / 9, 0.1, 1e6);
+ecam.position.copy(ep); ecam.lookAt(ec); ecam.updateMatrixWorld(true);
+const hb = new THREE.Box3().setFromObject(hero);
+let inside = 0;
+for (const cx of [hb.min.x, hb.max.x])
+ for (const cy of [hb.min.y, hb.max.y])
+ for (const cz of [hb.min.z, hb.max.z]) {
+ const n = new THREE.Vector3(cx, cy, cz).project(ecam);
+ if (Math.abs(n.x) <= 1 && Math.abs(n.y) <= 1 && Math.abs(n.z) <= 1) {
+ inside++;
+ }
+ }
+out.estInside = inside;
+
+// route(): ping-pong wheels roll with the direction of travel.
+const axle = new THREE.Object3D();
+const cart = new THREE.Object3D();
+const pp = route([[0, 0, 0], [10, 0, 0]],
+ { closed: false, speed: 2, wheels: [{ node: axle, radius: 0.5 }] });
+const at = (t) => { pp.poseAt(t, cart);
+ return { x: cart.position.x, rot: axle.rotation.x }; };
+const o1 = at(1.0), o2 = at(1.2); // outbound (turns at t = 5)
+const b1 = at(6.0), b2 = at(6.2); // return leg
+out.outDx = o2.x - o1.x;
+out.outDrot = o2.rot - o1.rot;
+out.backDx = b2.x - b1.x;
+out.backDrot = b2.rot - b1.rot;
+out.wheelRadius = 0.5;
+// a closed loop must not snap the wheel at the lap boundary.
+const axle2 = new THREE.Object3D();
+const loop = route([[0, 0, 0], [5, 0, 0], [5, 0, 5], [0, 0, 5]],
+ { closed: true, speed: 3, wheels: [{ node: axle2, radius: 0.4 }] });
+const dummy = new THREE.Object3D();
+loop.poseAt(loop.length / 3 - 0.001, dummy);
+const r1 = axle2.rotation.x;
+loop.poseAt(loop.length / 3 + 0.001, dummy);
+out.loopRotJump = Math.abs(axle2.rotation.x - r1);
+
+// alongPath(): an open path spans end to end, a closed one does not.
+const open = alongPath([[0, 0, 0], [12, 0, 0]], 6, { closed: false });
+out.openFirstX = open[0].position.x;
+out.openLastX = open[open.length - 1].position.x;
+out.openN = open.length;
+const ring = alongPath([[0, 0, 0], [6, 0, 0], [6, 0, 6], [0, 0, 6]], 8, {});
+out.ringN = ring.length;
+out.ringFirstToLast = ring[0].position.distanceTo(ring[7].position);
+out.ringStep = ring[0].position.distanceTo(ring[1].position);
+
+// crowdOn(): walkers on one route never bunch, at any time.
+const stalls = new THREE.Group();
+for (const [x, z] of [[3, 1], [-2, 2], [0, -3]]) {
+ const s = new THREE.Mesh(new THREE.BoxGeometry(1.2, 1.0, 1.2), basic());
+ s.name = 'stall';
+ s.position.set(x, 0.5, z);
+ stalls.add(s);
+}
+stalls.updateMatrixWorld(true);
+const lane = route([[6, 0, 0], [0, 0, 6], [-6, 0, 0], [0, 0, -6]],
+ { speed: 1.2, avoid: stalls, clearance: 0.5 });
+const figs = [];
+for (let i = 0; i < 7; i++) figs.push(new THREE.Object3D());
+const crowd = crowdOn(lane, figs, { spacing: 2, laneStep: 0.7 });
+let minGap = Infinity;
+for (let k = 0; k < 240; k++) {
+ crowd.tick(k * 0.25);
+ for (let i = 0; i < figs.length; i++)
+ for (let j = i + 1; j < figs.length; j++)
+ minGap = Math.min(minGap, figs[i].position.distanceTo(figs[j].position));
+}
+out.crowdMinGap = minGap;
+// the avoided path keeps its distance from the stalls it was routed around
+let minStall = Infinity;
+for (let k = 0; k < 400; k++) {
+ const p = lane.poseAt(k * (lane.length / 400) / 1.2).position;
+ for (const s of stalls.children) {
+ const b = new THREE.Box3().setFromObject(s);
+ const dx = Math.max(b.min.x - p.x, 0, p.x - b.max.x);
+ const dz = Math.max(b.min.z - p.z, 0, p.z - b.max.z);
+ minStall = Math.min(minStall, Math.hypot(dx, dz));
+ }
+}
+out.minStallGap = minStall;
+
+console.log(JSON.stringify(out));
+"""
+
+
[email protected](scope="module")
+def port() -> dict:
+ """One node launch of _PORT, shared by the port-fix tests."""
+ return _measure(_PORT)
+
+
+def test_an_interior_camera_stays_under_its_own_ceiling(port):
+ """Handed the room group, the eye stayed 1.6 m above the CEILING and
+ the shot shipped from on top of the roof (measured 4.60 in a 3.00 m
+ room). It must stand on the floor instead, and a room too low for
+ the clearance keeps it inside rather than ejecting it."""
+ m = port
+ assert m["interiorEyeY"] < m["ceilingTop"] - 0.2, m
+ assert m["interiorEyeY"] >= 1.6 - 1e-6, m
+ assert 0.3 <= m["lowRoomEyeY"] <= 1.8 - 0.25 + 1e-6, m
+
+
+def test_seat_puts_a_body_on_what_is_under_it_not_on_the_roof(port):
+ """The old down-ray took the top of the column: a crate under a 3 m
+ arch seated at 3.62. The quay-beats-seabed and lift-onto-the-hill
+ behaviours both have to survive the fix."""
+ m = port
+ assert abs(m["crateUnderArchY"] - 0.47) < 0.02, m # 0.5 - bite
+ assert abs(m["barrelOnQuayY"] - (2.0 + 0.4 - 0.03)) < 0.02, m
+ assert abs(m["hutOnHillY"] - (12.2 + 1.0 - 0.03)) < 0.02, m
+
+
+def test_an_establishing_shot_is_not_a_photograph_of_the_ridge(port):
+ """A hero behind a 9 m ridge shipped a frame blocked at 1.19 m of an
+ 8.92 m shot. Sliding along the fit sphere has to clear the view AND
+ keep the hero framed — retreating would only shrink it."""
+ m = port
+ assert (m["estBlockedAt"] is None
+ or m["estBlockedAt"] >= m["estClearNeeded"] - 1e-6), m
+ assert m["estInside"] >= 6, m
+
+
+def test_ping_pong_wheels_roll_the_way_the_cart_is_going(port):
+ """`s` only grows, so the return leg drove backwards with the wheels
+ spinning forwards. Roll is the arc distance COVERED — and a closed
+ loop must still not snap at the lap boundary."""
+ m = port
+ assert m["outDx"] > 0 and m["outDrot"] > 0, m
+ assert m["backDx"] < 0 and m["backDrot"] < 0, m
+ for dx, drot in ((m["outDx"], m["outDrot"]), (m["backDx"], m["backDrot"])):
+ assert abs(drot - dx / m["wheelRadius"]) < 2e-3, m # no slip
+ assert m["loopRotJump"] < 0.05, m
+
+
+def test_an_open_path_reaches_its_last_waypoint(port):
+ """6 posts over a 12 m quay ended at x = 10 — a whole gap short. A
+ CLOSED path keeps dividing by n: its last sample belongs one step
+ before the start, not on top of it."""
+ m = port
+ assert m["openN"] == 6, m
+ assert abs(m["openFirstX"]) < 1e-6, m
+ assert abs(m["openLastX"] - 12) < 1e-6, m
+ assert m["ringN"] == 8, m
+ assert abs(m["ringFirstToLast"] - m["ringStep"]) < 0.35 * m["ringStep"], m
+
+
+def test_a_crowd_on_one_route_never_bunches_or_walks_through_a_stall(port):
+ """The two guarantees the catalog sells: deterministic lane+phase
+ keeps walkers apart forever, and `avoid` re-projects the path clear
+ of furniture-scale solids at build time."""
+ m = port
+ assert m["crowdMinGap"] >= 0.6, m
+ assert m["minStallGap"] >= 0.45, m
diff --git a/harness/tests/scene_runtime/lib/test_rain.py b/harness/tests/scene_runtime/lib/test_rain.py
new file mode 100644
index 00000000..e05aefa7
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_rain.py
@@ -0,0 +1,712 @@
+"""rain.js: falling streaks, impacts, a wet-material conversion, a puddle.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_rain_lib.py). Its two laws are kept exactly as they stood,
+because both are about the delivery frame rather than about their renderer:
+rain must read FROZEN (a frozen drop is a speck, a frozen STREAK is rain,
+and one synchronized splash phase is no splash at all), and every custom
+ShaderMaterial here must be assembled by lib/shader.js or it is silently
+discarded. Their renderer-contract assertions are not kept: our renderer
+runs logarithmicDepthBuffer OFF by default and has no GTAO override pass,
+so the logdepth chunks are no-ops here — the two that survive are the ones
+that break a COMPILE (an `#include` sharing its line, and the fragment
+chunk not being first in main), plus the degenerate base quad, which our
+shadow pass still draws with its own material.
+
+THE PORT'S OWN LAWS — each one a frame rendered on our host at
+fx/out/rain/, looked at, and measured against a control render of the same
+scene with the rain field (or the soak) removed:
+
+1. A STREAK MUST PRINT ON A BLOWN SKY, AND IT CAN ONLY DO IT DARK. ACES at
+ exposure 1.0 puts this host's overcast sky at 0.94, so a pale streak
+ laid over it moves the pixel about 3/255: measured against a no-rain
+ control, the shipped field touched 0.82% of the sky band by a mean of
+ 3.4/255 and read as nothing at all in the still. A streak is ~2 px
+ wide, so a bright-core / dark-rim split ACROSS it averages back to one
+ tone inside a single pixel — the split has to run along its LENGTH,
+ where it has hundreds of pixels. Head bright (the specular blob),
+ tail dark (the trail the drop refracts light out of): 2.03% of the sky
+ band, mean 12.8/255, peak 86/255, and every touched pixel darker than
+ the control rather than lighter. Horizontal gradient over the same
+ band 0.08 -> 0.45 against a flat 0.11 vertical: still streaks, not
+ noise.
+
+2. WATER IS COLOURLESS: IT SHOWS YOU THE SKY. Every tint here was a
+ hardcoded pale blue at full strength, so a night street got white-hot
+ crowns — the brightest thing in the frame, on a car nothing else lit.
+ Streaks, rings and crowns now read the scene's own fog colour, which
+ is the one piece of scene state a ShaderMaterial already has each
+ frame: its HUE at the effect's own luminance, and its BRIGHTNESS on a
+ fourth root (a night scene is ~140x darker in linear light, and a
+ plain multiply would delete the effect instead of dimming it). On the
+ night frame the crown band's hottest pixels fell 0.62 -> 0.56 and the
+ pixels over 0.55 by 2.8x, with the crowns still plainly there.
+
+3. ONE STAMP REPEATED 500 TIMES IS NOT A FIELD. Every crown drew the same
+ 64 px starburst at the same handedness: a row of identical white pine
+ cones along the car's roof line (fx/crop_rain_crowns_before.png). The
+ bake is an ATLAS of four crowns, each with its own ray count, angles
+ and rim shape, picked per impact and mirrored per impact — 8 stamps
+ before anything repeats (fx/crop_rain_crowns_after.png).
+
+4. A SOAK MAY NOT LIGHT THE OBJECT UP, OR CRUSH IT TO BLACK. three scales
+ the diffuse irradiance with `envMapIntensity` as well as the
+ reflection, so the reference's 1.2 gain against a 0.45 albedo cut came
+ out NET BRIGHTER: the wet car measured 0.613 against a 0.568 dry
+ control on the roof and read as white plastic. The gain is the
+ largest that keeps `(1 - darken) * (1 + envGain)` under 1. At the
+ other end the same multiply crushed black trim: a wet tyre's shadow
+ side sat at 0.0006 of a night frame, which is a hole. An albedo floor
+ of 0.02 in linear light lifts it to 0.0112 (and the car's flank with
+ it) without touching anything mid-toned.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "rain.js")
+
+# Everything the reference's one big probe measured, in one node launch.
+_PROBE = """
+import * as THREE from 'three';
+import { makeRain, makeSplashes, makePuddle, wetten, splashTexture }
+ from './lib/rain.js';
+
+// --- rain: instanced, camera-following, deterministic ---------------
+const rain = makeRain({ seed: 5, count: 400 });
+const rain2 = makeRain({ seed: 5, count: 400 });
+const a1 = rain.geometry.attributes.iOff.array;
+const a2 = rain2.geometry.attributes.iOff.array;
+let rainIdentical = a1.length === a2.length;
+for (let i = 0; i < a1.length && rainIdentical; i++) {
+ if (a1[i] !== a2[i]) rainIdentical = false;
+}
+const a3 = makeRain({ seed: 6, count: 400 }).geometry.attributes.iOff.array;
+let rainSeedMatters = false;
+for (let i = 0; i < a1.length; i++) {
+ if (a1[i] !== a3[i]) { rainSeedMatters = true; break; }
+}
+const rainT0 = rain.material.uniforms.uTime.value;
+rain.userData.update(1.7);
+const rainT1 = rain.material.uniforms.uTime.value;
+// The base quad must be degenerate: the shadow pass draws `position`
+// verbatim with its own material, ignoring this vertex shader.
+let basePos = 0;
+const bp = rain.geometry.attributes.position.array;
+for (let i = 0; i < bp.length; i++) basePos = Math.max(basePos, Math.abs(bp[i]));
+const rx = rain.geometry.attributes.iExtra;
+let jitMin = 1, jitMax = 0;
+for (let i = 0; i < rx.count; i++) {
+ jitMin = Math.min(jitMin, rx.getZ(i));
+ jitMax = Math.max(jitMax, rx.getZ(i));
+}
+
+// --- splashes: raycast onto a real surface --------------------------
+const car = new THREE.Mesh(new THREE.BoxGeometry(2, 1.4, 4.5),
+ new THREE.MeshStandardMaterial());
+car.position.set(0, 0.7, 0);
+car.updateMatrixWorld(true);
+const sp = makeSplashes({ seed: 11, count: 300, surfaces: [car],
+ area: { x: 0, z: 0, w: 20, d: 20 } });
+const rings = sp.getObjectByName('SplashRings');
+const crowns = sp.getObjectByName('SplashCrowns');
+const off = rings.geometry.attributes.iOff.array;
+const nrm = rings.geometry.attributes.iNrm.array;
+const ext = rings.geometry.attributes.iExtra;
+let onRoof = 0, onGround = 0, sideways = 0, minPhase = 1, maxPhase = 0;
+const phaseHist = [0, 0, 0, 0];
+const cells = {};
+for (let i = 0; i < ext.count; i++) {
+ const y = off[i * 3 + 1];
+ if (y > 1.4) onRoof++; else if (y < 0.1) onGround++;
+ if (nrm[i * 3 + 1] < 0.4) sideways++;
+ const p = ext.getY(i);
+ minPhase = Math.min(minPhase, p);
+ maxPhase = Math.max(maxPhase, p);
+ phaseHist[Math.min(3, Math.floor(p * 4))]++;
+ cells[ext.getW(i)] = (cells[ext.getW(i)] || 0) + 1;
+}
+// A near-vertical face must not collect splashes; the whole field then
+// comes from the ground fallback.
+const wall = new THREE.Mesh(new THREE.PlaneGeometry(8, 8),
+ new THREE.MeshStandardMaterial({ side: THREE.DoubleSide }));
+wall.rotation.x = -Math.PI / 2 + 1.4; // 80 deg off horizontal
+wall.position.set(0, 3, 0);
+wall.updateMatrixWorld(true);
+const spWall = makeSplashes({ seed: 4, count: 120, surfaces: [wall],
+ area: { x: 0, z: 0, w: 20, d: 20 }, surfaceBias: 1.0 });
+const wallRings = spWall.getObjectByName('SplashRings');
+const wallStuck = wallRings ? wallRings.geometry.instanceCount : 0;
+const spMixed = makeSplashes({ seed: 4, count: 120, surfaces: [wall],
+ area: { x: 0, z: 0, w: 20, d: 20 } });
+const mixedRings = spMixed.getObjectByName('SplashRings');
+const mixedOff = mixedRings.geometry.attributes.iOff.array;
+let mixedHigh = 0;
+for (let i = 0; i < mixedOff.length / 3; i++) {
+ if (mixedOff[i * 3 + 1] > 0.5) mixedHigh++;
+}
+const noSurf = makeSplashes({ seed: 4, count: 80, ground: false });
+let emptyUpdates = false;
+try { noSurf.userData.update(1.7); emptyUpdates = true; } catch (e) {}
+
+// --- what shader.js owes every one of these materials ---------------
+const mats = [rain.material, rings.material, crowns.material];
+const fromHelper = mats.every((m) => m.userData.astraShader === true);
+const outChunks = mats.every(
+ (m) => m.fragmentShader.includes('<tonemapping_fragment>')
+ && m.fragmentShader.includes('<colorspace_fragment>'));
+const sources = mats.flatMap((m) => [m.vertexShader, m.fragmentShader]);
+const NL = String.fromCharCode(10);
+const includesAlone = sources.every((s) => s.split(NL).every((ln) => {
+ const t = ln.trim();
+ return !t.includes('#include')
+ || (t.indexOf('#include <') === 0 && t.indexOf('>') === t.length - 1);
+}));
+const fragFirst = mats.every((m) => {
+ const lines = m.fragmentShader.split(NL).map((l) => l.trim());
+ const i = lines.findIndex((l) => l.indexOf('void main') === 0);
+ return i >= 0 && lines[i + 1] === '#include <logdepthbuf_fragment>';
+});
+
+// --- the crown atlas -------------------------------------------------
+const t1 = splashTexture(48), t2 = splashTexture(48);
+let texIdentical = true;
+for (let i = 0; i < t1.image.data.length; i++) {
+ if (t1.image.data[i] !== t2.image.data[i]) { texIdentical = false; break; }
+}
+let alphaMax = 0, alphaSum = 0;
+for (let i = 3; i < t1.image.data.length; i += 4) {
+ alphaMax = Math.max(alphaMax, t1.image.data[i]);
+ alphaSum += t1.image.data[i];
+}
+const sheet = splashTexture(32, 2);
+const cellSum = [0, 0, 0, 0];
+let borderMax = 0;
+for (let y = 0; y < 64; y++) {
+ for (let x = 0; x < 64; x++) {
+ const a = sheet.image.data[(y * 64 + x) * 4 + 3];
+ cellSum[(y < 32 ? 0 : 2) + (x < 32 ? 0 : 1)] += a;
+ // Every cell must be transparent at its own border or mip levels
+ // bleed one crown into the next.
+ if (x % 32 === 0 || x % 32 === 31 || y % 32 === 0 || y % 32 === 31) {
+ borderMax = Math.max(borderMax, a);
+ }
+ }
+}
+
+// --- wetten ----------------------------------------------------------
+const mk = (hex, rough) => {
+ const m = new THREE.MeshStandardMaterial(
+ { color: hex, roughness: rough, metalness: 0 });
+ m.envMapIntensity = 1;
+ return m;
+};
+const dry = mk(0x808080, 0.9);
+const wet = mk(0x808080, 0.9);
+wetten(wet, 1.0);
+const dryTrim = mk(0x14171b, 0.8);
+const wetTrim = mk(0x14171b, 0.8);
+wetten(wetTrim, 1.0);
+const porous = mk(0x808080, 0.95);
+wetten(porous, 1.0);
+const polished = mk(0x808080, 0.25);
+wetten(polished, 1.0);
+const chan = (c) => [c.r, c.g, c.b];
+// One shared material under two meshes must be wetted ONCE.
+const shared = mk(0x808080, 0.9);
+const grp = new THREE.Group();
+grp.add(new THREE.Mesh(new THREE.BoxGeometry(), shared));
+grp.add(new THREE.Mesh(new THREE.BoxGeometry(), shared));
+wetten(grp, 1.0);
+
+// --- puddle ----------------------------------------------------------
+const pud = makePuddle(6, 4, { seed: 3 });
+const ppos = pud.geometry.attributes.position;
+const pcol = pud.geometry.attributes.color;
+const pnrm = pud.geometry.attributes.normal;
+let yAbs = 0, yNonZero = 0, colMin = 2, colMax = 0, minNy = 1;
+let crestCool = 0, troughWarm = 0, tinted = 0;
+for (let i = 0; i < ppos.count; i++) {
+ const y = ppos.getY(i);
+ yAbs = Math.max(yAbs, Math.abs(y));
+ if (Math.abs(y) > 1e-6) yNonZero++;
+ const r = pcol.getX(i), g = pcol.getY(i), b = pcol.getZ(i);
+ colMin = Math.min(colMin, r);
+ colMax = Math.max(colMax, r);
+ if (Math.abs(r - b) > 1e-4) tinted++;
+ if (y > 1e-5 && b > r) crestCool++;
+ if (y < -1e-5 && r > b) troughWarm++;
+ if (Math.abs(g - 1) > 0.5) tinted--; // green stays the anchor
+ minNy = Math.min(minNy, pnrm.getY(i));
+}
+const coarse = makePuddle(6, 4, { seed: 3, segments: 12 });
+let coarseNy = 1;
+const cn = coarse.geometry.attributes.normal;
+for (let i = 0; i < cn.count; i++) coarseNy = Math.min(coarseNy, cn.getY(i));
+const before = [];
+for (let i = 0; i < 40; i++) before.push(ppos.getY(i * 7));
+pud.userData.update(1.7);
+let moved = 0;
+for (let i = 0; i < 40; i++) {
+ if (Math.abs(ppos.getY(i * 7) - before[i]) > 1e-7) moved++;
+}
+const pudB = makePuddle(6, 4, { seed: 3 });
+pudB.userData.update(1.7);
+let pudIdentical = true;
+const qpos = pudB.geometry.attributes.position;
+for (let i = 0; i < ppos.count; i++) {
+ if (ppos.getY(i) !== qpos.getY(i)) { pudIdentical = false; break; }
+}
+
+console.log(JSON.stringify({
+ rainIdentical, rainSeedMatters, rainT0, rainT1, basePos,
+ rainInstances: rain.geometry.instanceCount,
+ rainCulled: rain.frustumCulled,
+ rainMeshes: [rain.type, rain.name],
+ rainTransparent: rain.material.transparent,
+ rainDepthWrite: rain.material.depthWrite,
+ rainExtraSize: rx.itemSize, jitMin, jitMax,
+ splashKids: sp.children.map((c) => c.name),
+ splashInstances: rings.geometry.instanceCount,
+ extraSize: ext.itemSize, cells: Object.keys(cells).map(Number).sort(),
+ onRoof, onGround, sideways, minPhase, maxPhase, phaseHist,
+ wallStuck, mixedHigh,
+ mixedCount: mixedRings.geometry.instanceCount,
+ noSurfKids: noSurf.children.length, emptyUpdates,
+ includesAlone, fragFirst, fromHelper, outChunks,
+ texIdentical, alphaMax, alphaMean: alphaSum / (48 * 48),
+ texFiltered: t1.minFilter === THREE.LinearMipmapLinearFilter
+ && t1.magFilter === THREE.LinearFilter
+ && t1.generateMipmaps === true,
+ texAniso: t1.anisotropy, texSize: [t1.image.width, sheet.image.width],
+ cellSum, borderMax,
+ atlasUniform: crowns.material.uniforms.uAtlas.value,
+ atlasMap: crowns.material.uniforms.map.value.image.width,
+ dryColor: chan(dry.color), wetColor: chan(wet.color),
+ dryTrimColor: chan(dryTrim.color), wetTrimColor: chan(wetTrim.color),
+ dryRough: dry.roughness, wetRough: wet.roughness,
+ porousRough: porous.roughness, polishedRough: polished.roughness,
+ wetEnv: wet.envMapIntensity,
+ sharedColor: chan(shared.color),
+ yAbs, yNonZero, pVerts: ppos.count, colMin, colMax, minNy, moved,
+ crestCool, troughWarm, tinted,
+ pudIdentical, coarseNy, segDefault: Math.round(Math.sqrt(ppos.count)) - 1,
+}));
+"""
+
+# The scene our check_shaders.mjs boots. FOGGED, because the fog uniforms
+# are where these shaders read the scene's own colour: without `USE_FOG`
+# the branch that does it is never compiled.
+_SCENE = """
+import * as THREE from 'three';
+import { makeRain, makeSplashes, makePuddle, wetten } from './lib/rain.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 20, 20] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ __FOG__
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ const car = new THREE.Mesh(new THREE.BoxGeometry(2, 1.4, 4.5),
+ new THREE.MeshStandardMaterial({ color: 0x2a3542, roughness: 0.5 }));
+ car.position.set(0, 0.7, 0);
+ car.updateMatrixWorld(true);
+ wetten(car, 0.8);
+ scene.add(car);
+ const rain = makeRain({ seed: 5, count: 600 });
+ const splash = makeSplashes({ seed: 11, count: 200, surfaces: [car] });
+ const pud = makePuddle(6, 4, { seed: 3 });
+ pud.position.set(3, 0.02, 3);
+ scene.add(rain); scene.add(splash); scene.add(pud);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [8, 3, 10], lookAt: [0, 1, 0],
+ fov: 45 }],
+ update(t) {
+ rain.userData.update(t);
+ splash.userData.update(t);
+ pud.userData.update(t);
+ },
+ };
+}
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch of _PROBE, shared by every test that reads it."""
+ return measure(_PROBE, _LIBS)
+
+
+# --- the reference's laws, kept ---------------------------------------
+
+
+def test_every_material_is_assembled_by_the_shader_helper(probe):
+ """This host has NO post chain: ACES and the sRGB transfer happen in
+ the fragment tail, from the two chunks three appends to its own
+ shaders. A hand-built ShaderMaterial that skips them renders on a
+ different curve from every built-in beside it — measured on the
+ reference's own hex, (185,206,219) built-in against (85,139,194)
+ hand-built."""
+ assert probe["fromHelper"], (
+ "a rain material was not built by lib/shader.js makeShaderMaterial "
+ "(no userData.astraShader)")
+ assert probe["outChunks"], (
+ "a rain fragment shader is missing tonemapping_fragment / "
+ "colorspace_fragment — it renders untonemapped next to every "
+ "built-in material in the same frame")
+
+
+def test_no_include_shares_a_line_and_the_depth_chunk_leads_main(probe):
+ """Both are COMPILE failures, and a shader that fails to compile is
+ dropped with no error anywhere: the effect is just missing. Our
+ renderer keeps logarithmicDepthBuffer off, so the chunks themselves are
+ no-ops here — their placement is not."""
+ assert probe["includesAlone"], (
+ "an #include shares its line with other code — the GLSL "
+ "preprocessor rejects it and the whole shader fails to compile")
+ assert probe["fragFirst"], (
+ "logdepthbuf_fragment is not the first statement in main()")
+
+
+def test_the_base_quad_is_degenerate_for_override_passes(probe):
+ """Every field here is one instanced quad whose corners travel in
+ `aCorner`, because a pass that draws with its own material (the shadow
+ map, or a GTAO pass on a host that has one) ignores these vertex
+ shaders and draws `position` verbatim — a real unit quad there prints
+ at the world origin."""
+ assert probe["basePos"] == 0, (
+ f"base quad is not degenerate (max |position| {probe['basePos']})")
+
+
+def test_rain_is_one_instanced_camera_following_mesh(probe):
+ """Rain is a per-frame cost the whole scene pays: it must stay ONE draw
+ call, and it must not be frustum-culled, because the streak positions
+ are computed in the shader (the geometry's own bounds say nothing about
+ where the field ended up)."""
+ assert probe["rainMeshes"] == ["Mesh", "Rainfall"], probe["rainMeshes"]
+ assert probe["rainInstances"] == 400, probe["rainInstances"]
+ assert probe["rainCulled"] is False, (
+ "frustumCulled left on — the shader-placed field pops out of frame "
+ "whenever the unit quad's bounds leave it")
+ assert probe["rainTransparent"] and probe["rainDepthWrite"] is False, (
+ "streaks must not write depth, or they occlude each other")
+
+
+def test_the_field_replays_byte_for_byte_from_its_seed(probe):
+ """Refine rounds re-render the same scene to compare frames; any
+ Math.random in the field would make every round's rain a different
+ field and every comparison noise."""
+ assert probe["rainIdentical"], "two makeRain(seed 5) fields differ"
+ assert probe["rainSeedMatters"], "seed 6 gave the seed-5 field"
+ assert probe["texIdentical"], "two splashTexture() bakes differ"
+ assert probe["pudIdentical"], (
+ "two puddles at the same seed and t differ — ripples are not "
+ "reproducible across a re-render")
+
+
+def test_update_is_the_only_animation_handle(probe):
+ """update(t) drives everything; a scene that calls it must see the
+ phase move, and one that forgets must still get a formed effect rather
+ than a flat plate."""
+ assert probe["rainT0"] == 0 and probe["rainT1"] == 1.7, probe
+ assert probe["moved"] >= 35, (
+ f"puddle update(t) moved only {probe['moved']}/40 sampled vertices")
+ assert probe["yNonZero"] > probe["pVerts"] * 0.5, (
+ f"only {probe['yNonZero']}/{probe['pVerts']} vertices are displaced "
+ "at t=0 — a puddle nobody ticks would render flat")
+
+
+def test_splashes_land_on_the_surfaces_they_are_given(probe):
+ """The whole point of passing meshes: drops must hit the car roof at
+ its real height and tilt, not rain THROUGH it onto the road. And rain
+ does not splash on vertical faces, so a wall collects none."""
+ assert probe["splashKids"] == ["SplashRings", "SplashCrowns"], probe
+ assert probe["onRoof"] > 60, (
+ f"only {probe['onRoof']}/300 impacts reached the 1.4 m roof — "
+ "surfaceBias is not aiming samples at the surfaces")
+ assert probe["onGround"] > 40, (
+ f"{probe['onGround']} impacts on the ground — misses must fall "
+ "through to the ground plane, not be dropped")
+ assert probe["sideways"] == 0, (
+ "an impact kept a near-vertical normal; maxSlopeDeg must reject "
+ "walls and undersides")
+ assert probe["wallStuck"] == 0, (
+ f"{probe['wallStuck']} splashes stuck to an 80-degree face")
+ assert probe["mixedHigh"] == 0, probe["mixedHigh"]
+ assert probe["mixedCount"] == 120, (
+ f"the field shrank to {probe['mixedCount']}/120 around a steep face "
+ "— rejected samples must be re-drawn, not dropped")
+ assert probe["noSurfKids"] == 0 and probe["emptyUpdates"], (
+ "no surfaces and ground:false must yield an EMPTY group that still "
+ "ticks, not splashes hanging in the air or a crash")
+
+
+def test_splash_phases_span_the_whole_cycle(probe):
+ """Stills are the delivery frame. If every impact shared a phase the
+ frozen frame would show one synchronized pulse (or nothing at all);
+ spread phases put rings at every radius in the SAME frame, which is
+ what reads as continuous rainfall."""
+ assert probe["minPhase"] < 0.1 and probe["maxPhase"] > 0.9, probe
+ quarters = probe["phaseHist"]
+ assert min(quarters) > 40, (
+ f"phase quartiles {quarters} — impacts are clustered in the cycle, "
+ "so a frozen frame shows only part of the splash range")
+
+
+def test_the_crown_texture_is_filtered_like_every_other_datatexture(probe):
+ """DataTexture defaults to NearestFilter with NO mipmaps. A 64 px
+ crown seen 20 m down the street then stair-steps into hard blocks."""
+ assert probe["texFiltered"], "crown texture left on Nearest/no mipmaps"
+ assert probe["texAniso"] >= 8, probe["texAniso"]
+ assert probe["alphaMax"] > 200, (
+ f"crown never reaches opaque (max alpha {probe['alphaMax']}) — it "
+ "would read as a smudge")
+ assert 2 < probe["alphaMean"] < 60, (
+ f"crown alpha mean {probe['alphaMean']} — a crown is thin spray on "
+ "a transparent background, not a filled blob")
+
+
+def test_puddle_ripples_are_real_geometry(probe):
+ """The ripples must survive into a still under the scene's OWN
+ lighting, so they are vertex displacement with recomputed normals (a
+ scrolling normal map would need an animation to read), plus a
+ crest-brightening vertex colour so the rings stay legible even under
+ flat overcast light."""
+ assert 0.002 < probe["yAbs"] < 0.05, (
+ f"ripple amplitude {probe['yAbs']} m — millimetre waves on a "
+ "puddle, not surf")
+ assert probe["minNy"] < 0.999, (
+ f"steepest ripple normal {probe['minNy']} — the surface is flat to "
+ "the shading, so no crest can catch a highlight")
+ assert probe["coarseNy"] > probe["minNy"], (
+ f"a 12-segment puddle ({probe['coarseNy']}) is not flatter than the "
+ f"default {probe['segDefault']}-segment one ({probe['minNy']})")
+ assert probe["colMin"] < 0.95 and probe["colMax"] > 1.05, (
+ f"crest/trough vertex colours {probe['colMin']}..{probe['colMax']} "
+ "— the rings lose their fallback readability")
+
+
+def test_a_square_area_given_as_one_number_is_not_nan():
+ """`area` is documented as {x, z, w, d}. A number is truthy, so
+ `area: 12` read x and w as undefined and every ground-fallback impact
+ landed at NaN — 520 of 780 offset floats non-finite, with 260 instances
+ still created and drawn."""
+ out = measure("""
+import { makeSplashes } from './lib/rain.js';
+const finite = (g) => {
+ let bad = 0, total = 0;
+ g.traverse((o) => {
+ const a = o.geometry && o.geometry.getAttribute('iOff');
+ if (!a) return;
+ for (let i = 0; i < a.array.length; i++) {
+ total++; if (!Number.isFinite(a.array[i])) bad++;
+ }
+ });
+ return { bad, total };
+};
+const num = finite(makeSplashes({ area: 12, y: 0, seed: 4 }));
+const rect = finite(makeSplashes({ area: { x: 0, z: 0, w: 12, d: 12 },
+ y: 0, seed: 4 }));
+console.log(JSON.stringify({ num, rect }));
+""", _LIBS)
+ assert out["num"]["total"] > 0, "the probe found no offsets to check"
+ assert out["num"]["bad"] == 0, out["num"]
+ assert out["rect"]["bad"] == 0, out["rect"]
+
+
+# --- the port's own laws ----------------------------------------------
+
+
+def test_a_streak_is_bright_at_the_head_and_dark_down_the_tail():
+ """PORT LAW 1. Against this host's 0.94 sky a pale streak is worth
+ 3/255 and reads as nothing; the only mark that prints there is a dark
+ one. The split has to run along the streak's LENGTH — it is about two
+ pixels wide, so a core/rim split across it averages back to one tone
+ inside a single pixel. vUv.y = 1 is the leading end, so the tint runs
+ from the rim colour at the tail to the streak colour at the head, and
+ the alpha ramp lifts the tail's floor (0.45 -> 0.62) so the dark half
+ has enough coverage to print. Measured against a no-rain control on
+ the mid camera: 0.82% of the sky band touched at a mean 3.4/255,
+ against 2.03% at 12.8/255 with a peak of 86/255 — and every touched
+ pixel DARKER than the control, which is the only direction a drop can
+ move a blown sky."""
+ out = measure("""
+import { makeRain } from './lib/rain.js';
+const m = makeRain({ count: 200 }).material;
+const f = m.fragmentShader;
+const lum = (c) => 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
+console.log(JSON.stringify({
+ // the tail-to-head mix, on the length axis
+ mixesOnLength: /mix\\(rainAirHue\\(uRim[\\s\\S]{0,120}vUv\\.y\\)/.test(f),
+ head: lum(m.uniforms.uColor.value),
+ tail: lum(m.uniforms.uRim.value),
+ tailFloor: /0\\.62 \\+ 0\\.38 \\* vUv\\.y/.test(f),
+ dithered: f.includes('astraHash21(gl_FragCoord.xy)'),
+ // per-streak hue, so the field is not one flat hatch
+ jitters: f.includes('vJit'),
+}));
+""", _LIBS)
+ assert out["mixesOnLength"], (
+ "the streak tint does not run from uRim to uColor along vUv.y")
+ assert out["tailFloor"] and out["dithered"] and out["jitters"], out
+ # The tail has to be far below the sky it crosses, and the head far
+ # above the ground it crosses.
+ assert out["tail"] < 0.02, out
+ assert out["head"] > 0.6, out
+
+
+def test_every_tint_here_reads_the_scene_and_survives_a_scene_without_fog():
+ """PORT LAW 2. Water is colourless; a streak, a ring and a crown are
+ all showing you the sky. The fog uniforms are the one piece of scene
+ state a ShaderMaterial has for free every frame, so all three take the
+ fog colour's HUE at their own luminance and its BRIGHTNESS on a fourth
+ root. Both reads sit under `#ifdef USE_FOG` — a scene with no fog
+ never defines it, and an unguarded `fogColor` there is a compile error
+ that would delete the whole effect."""
+ out = measure("""
+import { makeRain, makeSplashes } from './lib/rain.js';
+const rain = makeRain({ count: 100 }).material;
+const sp = makeSplashes({ count: 40, seed: 2 });
+const ring = sp.getObjectByName('SplashRings').material;
+const crown = sp.getObjectByName('SplashCrowns').material;
+const mats = { rain, ring, crown };
+const out = {};
+for (const [k, m] of Object.entries(mats)) {
+ const f = m.fragmentShader;
+ const body = f.slice(f.indexOf('rainAirHue(vec3'));
+ out[k] = {
+ hue: (f.match(/rainAirHue\\(/g) || []).length,
+ lit: (f.match(/rainAirLit\\(/g) || []).length,
+ guarded: (body.match(/#ifdef USE_FOG/g) || []).length,
+ air: m.uniforms.uAir ? m.uniforms.uAir.value : null,
+ dim: m.uniforms.uDim ? m.uniforms.uDim.value : null,
+ };
+}
+console.log(JSON.stringify(out));
+""", _LIBS)
+ for k in ("rain", "ring", "crown"):
+ # one definition + at least one call
+ assert out[k]["hue"] >= 2, (k, out[k])
+ # both helpers guard their scene read
+ assert out[k]["guarded"] == 2, (k, out[k])
+ assert 0 < out[k]["air"] <= 1, (k, out[k])
+ # Streaks keep their own brightness — they are lit by whatever is
+ # behind them. Thrown water is a surface, and it goes dark with the
+ # scene: a night street had white-hot crowns before this.
+ assert out["rain"]["lit"] == 1, out["rain"]
+ assert out["ring"]["lit"] == 2 and out["crown"]["lit"] == 2, out
+ assert 0.2 <= out["crown"]["dim"] <= 0.5, out["crown"]
+
+
+def test_the_crown_field_is_not_one_stamp_repeated(probe):
+ """PORT LAW 3. 500 impacts drew the same 64 px starburst at the same
+ handedness, which along a car's roof line is a row of identical white
+ pine cones. The bake is an atlas — four crowns, each with its own ray
+ count, angles and rim — picked per impact and mirrored per impact.
+ Cells must be transparent at their borders, or a mip level averages
+ two crowns into one blur."""
+ assert probe["atlasUniform"] == 2, probe["atlasUniform"]
+ assert probe["atlasMap"] == 128, (
+ f"crown atlas is {probe['atlasMap']} px — a 2x2 sheet of 64 px "
+ "cells is 128")
+ assert probe["texSize"] == [48, 64], probe["texSize"]
+ sums = probe["cellSum"]
+ assert min(sums) > 0, sums
+ assert len(set(sums)) == 4, (
+ f"atlas cells carry {len(set(sums))} distinct crowns, not 4: {sums}")
+ assert max(sums) < min(sums) * 2.2, (
+ f"one crown is more than twice another's mass {sums} — a field of "
+ "wildly unequal splashes reads as an error, not as variation")
+ assert probe["borderMax"] <= 2, (
+ f"a cell reaches alpha {probe['borderMax']} at its own border — mip "
+ "levels will bleed the neighbouring crown into it")
+ assert probe["cells"] == [0, 1, 2, 3], (
+ f"impacts used atlas cells {probe['cells']} — all four must appear")
+ assert probe["extraSize"] == 4 and probe["rainExtraSize"] == 3, probe
+ assert probe["jitMin"] < 0.05 and probe["jitMax"] > 0.95, probe
+
+
+def test_a_soak_darkens_the_thing_it_soaks(probe):
+ """PORT LAW 4. Wet is darker AND shinier, and three gives the second
+ half no knob that does not also do the first: `envMapIntensity` scales
+ the diffuse irradiance with the reflection. At the reference's 1.2
+ gain the product (1 - 0.45) * 2.2 = 1.21 came out net BRIGHTER, and on
+ this host that measured 0.613 of wet roof against a 0.568 dry control
+ — a white plastic slab. The gain is the largest one that keeps the
+ product under 1 while still doubling nothing: 0.6."""
+ dry_l = sum(probe["dryColor"]) / 3
+ wet_l = sum(probe["wetColor"]) / 3
+ assert wet_l < dry_l * 0.75, (probe["dryColor"], probe["wetColor"])
+ assert probe["wetEnv"] > 1.5, (
+ f"envMapIntensity {probe['wetEnv']} — without the reflection boost "
+ "the surface just goes dark")
+ assert (wet_l / dry_l) * probe["wetEnv"] < 1.0, (
+ f"albedo x env = {(wet_l / dry_l) * probe['wetEnv']:.3f} — a soak "
+ "that lands over 1 lights the object up instead of wetting it")
+ assert probe["sharedColor"] == probe["wetColor"], (
+ "a material shared by two meshes was wetted twice, so shared "
+ "materials darken by however many meshes happen to use them")
+
+
+def test_a_soak_leaves_a_floor_under_black_trim(probe):
+ """PORT LAW 4, the other end. The same multiply that darkens mid tones
+ correctly takes near-black trim to nothing: a wet tyre's shadow side
+ measured 0.0006 of a night frame, and the car's flank with it — a hole,
+ not a dark surface. Water on black rubber is still lit by the sky.
+ The floor is on the albedo in LINEAR light, so it lifts only what was
+ already under it."""
+ trim = probe["wetTrimColor"]
+ dry = probe["dryTrimColor"]
+ assert max(trim) >= 0.0199, (
+ f"wet trim albedo {trim} — under the 0.02 floor, so it renders as "
+ "a hole in the frame")
+ assert max(trim) > max(dry), (
+ f"the floor did not engage: dry {dry}, wet {trim}")
+ # ...and a mid-grey is not lifted by it.
+ assert sum(probe["wetColor"]) / 3 < sum(probe["dryColor"]) / 3, probe
+
+
+def test_a_soaked_brick_is_not_a_mirror(probe):
+ """One flat roughness floor for every material made brick, dirt and car
+ paint identical the moment they got wet. A porous surface holds water
+ in its own relief and comes back a damp sheen; a polished one is
+ already close to the floor. Each keeps a share of its own roughness,
+ with the floor as the hard stop."""
+ assert probe["wetRough"] < 0.3 < probe["dryRough"], probe
+ assert probe["porousRough"] > probe["wetRough"] > probe["polishedRough"], (
+ f"porous {probe['porousRough']}, mid {probe['wetRough']}, polished "
+ f"{probe['polishedRough']} — wetting flattened them into one look")
+ assert probe["polishedRough"] >= 0.1 - 1e-9, probe["polishedRough"]
+
+
+def test_the_puddle_tints_its_crests_and_its_troughs(probe):
+ """A crest tips toward the sky it mirrors and goes cool; a trough shows
+ the bed under it and stays warm. The reference multiplied all three
+ channels by one number, which leaves the whole pool on a single flat
+ hue — the one thing standing water never has."""
+ assert probe["tinted"] > probe["pVerts"] * 0.9, (
+ f"only {probe['tinted']}/{probe['pVerts']} vertices carry a tint — "
+ "the vertex colours are achromatic")
+ assert probe["crestCool"] > 0 and probe["troughWarm"] > 0, probe
+
+
+def test_the_whole_field_compiles_on_the_real_renderer():
+ """A custom shader that fails to compile is discarded with no error at
+ all — the effect is simply absent. Both scenes have to be checked: the
+ fog uniforms are where these shaders read the scene's colour, and the
+ branch that does it exists only when the renderer defines USE_FOG, so
+ the fogged scene compiles the read and the fog-less one compiles the
+ fallback."""
+ fogged = _SCENE.replace(
+ "__FOG__", "scene.fog = new THREE.FogExp2(0xc9d6e0, 0.02);")
+ code, out = compile_scene(fogged, _LIBS)
+ assert code == 0, out
+ assert '"custom_materials":3' in out.replace(" ", ""), out
+ assert "WARN" not in out, out
+ code, out = compile_scene(_SCENE.replace("__FOG__", ""), _LIBS)
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_river.py b/harness/tests/scene_runtime/lib/test_river.py
new file mode 100644
index 00000000..58a10def
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_river.py
@@ -0,0 +1,497 @@
+"""A river is not a plane with a scrolling texture.
+
+Scroll a UV on a curved ribbon and the whole sheet slides one way, so
+round a bend the water stops following its own course — the one defect
+that reads instantly as "moving texture" instead of "river". ``river.js``
+carries the centreline tangent per vertex and advects its noise along
+THAT, so the geometry half of these tests holds the claim (the flow field
+is tangent to the course, and it turns where the course turns) rather
+than any pixel.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference test. The
+colour half is OURS: the surface is unlit, so every constant in it is a
+decision, and the reference's were three daylight constants baked into a
+factory. Measured on this harness's night rig with those defaults, the
+channel came back at luminance 0.40/0.54 over a frame whose mean was
+0.21/0.31 — a strip of white plastic lying in the dark. It now reads the
+scene's own key light, hemisphere fill and fog at the first render, so
+the tests below pin THAT as hard as they pin the flow field.
+"""
+
+from __future__ import annotations
+
+from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "river.js")
+
+# One S-bend, so a flow field that did not turn cannot pass by accident.
+_POINTS = "[[-14,0,-12],[-5,0,-6],[2,0,2],[-1,0,10],[4,0,16]]"
+
+# Rows are arc-length uniform, so a row's centre IS the centreline
+# there; this hands every probe the same frame to measure against.
+_FRAME = """
+const geom = (g) => g.getObjectByName('Channel').geometry;
+function frame(g) {
+ const a = geom(g).attributes;
+ const P = a.position.array, UV = a.uv.array;
+ let cols = 0;
+ while (cols < a.position.count && UV[cols * 2 + 1] === 0) cols++;
+ const rows = a.position.count / cols - 1;
+ const centre = [];
+ for (let j = 0; j <= rows; j++) {
+ let x = 0, y = 0, z = 0;
+ for (let i = 0; i < cols; i++) {
+ const k = (j * cols + i) * 3;
+ x += P[k]; y += P[k + 1]; z += P[k + 2];
+ }
+ centre.push([x / cols, y / cols, z / cols]);
+ }
+ return { a, cols, rows, centre };
+}
+"""
+
+# A scene the way `sunRig` builds one: a key directional light, a
+# hemisphere fill and fog. `adoptSceneLight` runs off `onBeforeRender`,
+# which a probe can call directly — no GPU needed to prove what it read.
+_LIT_SCENE = """
+function litScene(THREE, opts) {
+ const o = opts || {};
+ const scene = new THREE.Scene();
+ const key = new THREE.DirectionalLight(o.sunHex || 0xfff0d8,
+ o.sunI === undefined ? 5.4 : o.sunI);
+ // Direction is position -> target, so a light at +y+x shines DOWN and
+ // the adopted uSun must point back up at it.
+ key.position.set(30, 40, -10);
+ scene.add(key);
+ const hemi = new THREE.HemisphereLight(o.skyHex || 0x9db8e8, 0x8a7f6a,
+ o.fillI === undefined ? 1.4 : o.fillI);
+ scene.add(hemi);
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ return scene;
+}
+const adopt = (g, scene) => {
+ const m = g.getObjectByName('Channel');
+ m.onBeforeRender(null, scene);
+ return m.material.uniforms;
+};
+const hex = (c) => [+c.r.toFixed(4), +c.g.toFixed(4), +c.b.toFixed(4)];
+"""
+
+
+def test_the_ribbon_follows_the_given_points():
+ """The course is the contract: every waypoint the caller gave must
+ have channel under it, and the ribbon rests on the water surface
+ rather than sinking into it or floating over it."""
+ out = measure(_FRAME + """
+import { makeRiver } from './lib/river.js';
+const pts = __POINTS__;
+const g = makeRiver({ points: pts, width: 6, depth: 1.2, seed: 3 });
+const { a, centre } = frame(g);
+const miss = pts.map((p) => Math.min(...centre.map(
+ (c) => Math.hypot(c[0] - p[0], c[2] - p[2]))));
+let run = 0;
+for (let j = 1; j < centre.length; j++) {
+ run += Math.hypot(centre[j][0] - centre[j - 1][0],
+ centre[j][2] - centre[j - 1][2]);
+}
+const P = a.position.array;
+let minY = 1e9, maxY = -1e9;
+for (let i = 1; i < P.length; i += 3) {
+ minY = Math.min(minY, P[i]); maxY = Math.max(maxY, P[i]);
+}
+let poly = 0;
+for (let i = 1; i < pts.length; i++) {
+ poly += Math.hypot(pts[i][0] - pts[i - 1][0],
+ pts[i][2] - pts[i - 1][2]);
+}
+console.log(JSON.stringify({
+ worstMiss: +Math.max(...miss).toFixed(3),
+ run: +run.toFixed(2), poly: +poly.toFixed(2),
+ straight: +Math.hypot(pts[4][0] - pts[0][0],
+ pts[4][2] - pts[0][2]).toFixed(2),
+ minY: +minY.toFixed(3), maxY: +maxY.toFixed(3),
+ name: g.name, hasTick: typeof g.userData.tick === 'function',
+}));
+""".replace("__POINTS__", _POINTS), _LIBS)
+ # Sampled every ~0.55 m, so the nearest row centre to a waypoint is
+ # inside half that; a ribbon that cut the corner would miss by
+ # metres.
+ assert out["worstMiss"] < 0.35, out
+ # It runs the polyline's own length — neither shortcutting the
+ # corners nor wandering off between them.
+ assert out["poly"] <= out["run"] <= out["poly"] * 1.05, out
+ assert out["run"] > out["straight"] * 1.1, out
+ # Rests ON the surface: a hair above the water plane it joins, not
+ # a slab with thickness.
+ assert 0 < out["minY"] <= 0.02 and out["maxY"] - out["minY"] < 0.01
+ assert out["name"] == "River" and out["hasTick"]
+
+
+def test_the_flow_direction_is_tangent_to_the_centreline():
+ """The whole claim. `aFlow` is the world flow velocity, and its
+ direction must be the course's own tangent at that vertex — that is
+ what makes the advected pattern go round a bend instead of sliding
+ sideways as one sheet. A constant direction would pass a straight
+ reach and fail here, so the turn is measured too."""
+ out = measure(_FRAME + """
+import { makeRiver } from './lib/river.js';
+const g = makeRiver({ points: __POINTS__, width: 6, flow: 1.5, seed: 3 });
+const { a, cols, rows, centre } = frame(g);
+const F = a.aFlow.array;
+const ang = (v) => Math.atan2(v[1], v[0]) * 180 / Math.PI;
+let worst = 1, slow = 1e9, fast = -1e9;
+const flowH = [], courseH = [];
+for (let j = 1; j < rows; j++) {
+ // Central difference: second-order, so a real bend does not read as
+ // a tangency error the way a forward chord would.
+ const d = [centre[j + 1][0] - centre[j - 1][0],
+ centre[j + 1][2] - centre[j - 1][2]];
+ const dl = Math.hypot(d[0], d[1]);
+ for (let i = 0; i < cols; i++) {
+ const k = (j * cols + i) * 3;
+ const f = [F[k], F[k + 2]];
+ const fl = Math.hypot(f[0], f[1]);
+ worst = Math.min(worst, (f[0] * d[0] + f[1] * d[1]) / (fl * dl));
+ slow = Math.min(slow, fl); fast = Math.max(fast, fl);
+ if (i === 0) { flowH.push(ang(f)); courseH.push(ang(d)); }
+ }
+}
+// How far the heading swings over the whole course — an S returns to
+// where it started, so end-to-end would say a river never turns.
+const swing = (h) => Math.max(...h) - Math.min(...h);
+console.log(JSON.stringify({
+ worstDot: +worst.toFixed(5),
+ flowSwing: +swing(flowH).toFixed(1),
+ courseSwing: +swing(courseH).toFixed(1),
+ slow: +slow.toFixed(3), fast: +fast.toFixed(3),
+ y: Math.max(...[...F].filter((_, i) => i % 3 === 1).map(Math.abs)),
+}));
+""".replace("__POINTS__", _POINTS), _LIBS)
+ assert out["worstDot"] > 0.999, out
+ # It TURNS, and it turns by exactly what the course turns by.
+ assert out["flowSwing"] > 40, out
+ assert abs(out["flowSwing"] - out["courseSwing"]) < 3, out
+ # Magnitude is the surface speed, horizontal: the flow map advects
+ # in metres per second, so a wrong length is a wrong current.
+ assert out["slow"] > 1.2 and out["fast"] < 1.9, out
+ assert out["y"] == 0, out
+
+
+def test_it_runs_thin_over_the_bank_and_over_a_rock():
+ """Depth is what tells the eye where the channel is, and only the
+ CPU can find it: GLSL_UTIL's value noise is not the field the
+ terrain was built from, so `heightAt` is measured here and handed
+ over as an attribute or the pale shallows never line up with the
+ ground the water actually runs over."""
+ out = measure(_FRAME + """
+import { makeRiver } from './lib/river.js';
+// Flat bed at -1.6 with one boulder standing 1.3 m proud of it.
+const heightAt = (x, z) =>
+ Math.max(0, 1.3 - Math.hypot(x, z) * 1.2) - 1.6;
+const g = makeRiver({ points: [[-12, 0, 0], [12, 0, 0]], width: 6,
+ depth: 1.4, flow: 1.0, heightAt, seed: 2 });
+const { a, cols, rows, centre } = frame(g);
+const C = a.aChan.array;
+const at = (j, i, c) => C[(j * cols + i) * 4 + c];
+let bank = 0, mid = 0, rockDeep = 9, rockBrk = 0, calmBrk = 0;
+for (let j = 0; j <= rows; j++) {
+ bank = Math.max(bank, at(j, 0, 1), at(j, cols - 1, 1));
+ const c = at(j, (cols - 1) / 2, 1);
+ const onRock = Math.abs(centre[j][0]) < 0.6;
+ if (onRock) {
+ rockDeep = Math.min(rockDeep, c);
+ rockBrk = Math.max(rockBrk, at(j, (cols - 1) / 2, 2));
+ } else {
+ mid = Math.max(mid, c);
+ // Upstream only: the wake downstream of the rock keeps foaming.
+ if (centre[j][0] < -3) calmBrk = Math.max(calmBrk, at(j, 7, 2));
+ }
+}
+console.log(JSON.stringify({
+ bank: +bank.toFixed(3), mid: +mid.toFixed(3),
+ rockDeep: +rockDeep.toFixed(3), rockBrk: +rockBrk.toFixed(3),
+ calmBrk: +calmBrk.toFixed(3),
+}));
+""", _LIBS)
+ assert out["bank"] == 0 and 1.3 < out["mid"] <= 1.4, out
+ # The water over the boulder is thin, and it breaks there.
+ assert out["rockDeep"] < 0.25, out
+ assert out["rockBrk"] > 0.5, out
+ # ...and nowhere else: foam everywhere is foam nowhere.
+ assert out["calmBrk"] < 0.05, out
+
+
+def test_a_narrows_runs_faster_and_breaks():
+ """Flux, not decoration: the same water through a smaller gap has
+ to run faster, and that is what makes a narrows both race and go
+ white — one number driving both, so they cannot disagree."""
+ out = measure(_FRAME + """
+import { makeRiver } from './lib/river.js';
+const pinch = (u) => 6 * (1 - 0.45 * Math.exp(-Math.pow(
+ (u - 0.5) / 0.10, 2)));
+const g = makeRiver({ points: [[-12, 0, 0], [12, 0, 0]], width: pinch,
+ depth: 1.2, flow: 1.0, seed: 6 });
+const { a, cols, rows, centre } = frame(g);
+const F = a.aFlow.array, C = a.aChan.array;
+let gap = 1e9, wide = 0, gapV = 0, wideV = 9, gapBrk = 0, wideBrk = 0;
+for (let j = 0; j <= rows; j++) {
+ const k = (j * cols) * 3;
+ const v = Math.hypot(F[k], F[k + 2]);
+ const w = Math.hypot(
+ a.position.array[k] - a.position.array[k + (cols - 1) * 3],
+ a.position.array[k + 2] - a.position.array[k + (cols - 1) * 3 + 2]);
+ const brk = C[(j * cols + (cols - 1) / 2) * 4 + 2];
+ if (Math.abs(centre[j][0]) < 1.0) {
+ gap = Math.min(gap, w); gapV = Math.max(gapV, v);
+ gapBrk = Math.max(gapBrk, brk);
+ } else if (centre[j][0] < -6) {
+ wide = Math.max(wide, w); wideV = Math.min(wideV, v);
+ wideBrk = Math.max(wideBrk, brk);
+ }
+}
+console.log(JSON.stringify({
+ gap: +gap.toFixed(2), wide: +wide.toFixed(2),
+ gapV: +gapV.toFixed(3), wideV: +wideV.toFixed(3),
+ gapBrk: +gapBrk.toFixed(3), wideBrk: +wideBrk.toFixed(3),
+}));
+""", _LIBS)
+ assert out["gap"] < out["wide"] * 0.7, out
+ assert out["gapV"] > out["wideV"] * 1.4, out
+ assert out["gapBrk"] > 0.5 and out["wideBrk"] < 0.05, out
+
+
+def test_two_rivers_with_one_seed_are_identical():
+ """Determinism is the contract for every shipped factory: a re-run
+ that re-wanders the banks is a re-run nobody can compare against."""
+ out = measure("""
+import { makeRiver } from './lib/river.js';
+const dump = (s) => {
+ const g = makeRiver({ points: [[-8, 0, 0], [0, 0, 3], [8, 0, 0]],
+ width: 5, seed: s });
+ const a = g.getObjectByName('Channel').geometry.attributes;
+ return JSON.stringify([...a.position.array, ...a.aChan.array]);
+};
+const a = dump(5), b = dump(5), c = dump(9);
+console.log(JSON.stringify({ same: a === b, differs: a !== c }));
+""", _LIBS)
+ assert out["same"] and out["differs"]
+
+
+def test_tick_advances_the_material():
+ """An un-advanced uTime is a frozen river, and the flow map resets
+ every period — so the clock is not optional dressing."""
+ out = measure("""
+import { makeRiver } from './lib/river.js';
+const g = makeRiver({ width: 5 });
+const before = [], after = [];
+g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.uniforms && m.uniforms.uTime) {
+ before.push(m.uniforms.uTime.value);
+ }
+ }
+});
+g.userData.tick(2.5);
+g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.uniforms && m.uniforms.uTime) after.push(m.uniforms.uTime.value);
+ }
+});
+console.log(JSON.stringify({ before, after }));
+""", _LIBS)
+ assert out["before"] == [0] and out["after"] == [2.5]
+
+
+def test_the_stated_depth_actually_changes_how_deep_the_water_looks():
+ """The depth ramp must be absolute, not relative to the river's own
+ depth. The geometry writes `aChan.y = depth * (1 - q*q)`, so a ramp
+ normalised by that same `depth` divides it straight back out and
+ every river — a 0.25 m brook and a 3 m channel alike — saturates to
+ the deep colour mid-stream behind a constant-width shallow rim. The
+ metre is the thing that decides how much light comes back up."""
+ out = measure("""
+import { makeRiver } from './lib/river.js';
+const mid = (r) => {
+ const g = r.getObjectByName('Channel').geometry;
+ const c = g.getAttribute('aChan');
+ let best = 0;
+ for (let i = 0; i < c.count; i++) best = Math.max(best, c.getY(i));
+ return best;
+};
+const pts = [[-8, 0, -8], [0, 0, 0], [8, 0, 8]];
+const brook = makeRiver({ points: pts, width: 3, depth: 0.25, seed: 4 });
+const deepR = makeRiver({ points: pts, width: 3, depth: 3.0, seed: 4 });
+const src = brook.getObjectByName('Channel').material.fragmentShader;
+console.log(JSON.stringify({
+ brookDepth: mid(brook),
+ riverDepth: mid(deepR),
+ dividesItOut: /vChan\\.y\\s*\\/\\s*uDepthM/.test(src),
+}));
+""", _LIBS)
+ assert out["brookDepth"] < 0.3 and out["riverDepth"] > 2.5, out
+ assert not out["dividesItOut"], (
+ "the shader divides the measured depth by the depth it was built "
+ "from, so `depth` cannot reach the eye")
+
+
+def test_a_river_at_the_depth_people_actually_pass_is_not_pale():
+ """The ramp is absolute, which is right, but the metre it was set to
+ was picked from plausibility rather than from what callers pass. At
+ uOpaqueM 2.4 a river 1 m deep reached dep 0.42 at its deepest point
+ and the smoothstep floor kept nearly all of an 18 m channel in the
+ SHALLOW colour — a pale sage ribbon bank to bank. A river is 1-2 m
+ deep; the scale has to be near that, and the deep end of the ramp
+ has to sit inside where a real river ever gets."""
+ out = measure("""
+import { makeRiver } from './lib/river.js';
+const mid = (r) => {
+ const g = r.getObjectByName('Channel').geometry;
+ const c = g.getAttribute('aChan');
+ let best = 0;
+ for (let i = 0; i < c.count; i++) best = Math.max(best, c.getY(i));
+ return best;
+};
+const m = makeRiver({ width: 18, depth: 1.0, flow: 0.45, seed: 3 });
+const mat = m.getObjectByName('Channel').material;
+const edges = /mix\\(uShallow, uDeep, smoothstep\\(([0-9.]+), ([0-9.]+), dep\\)\\)/
+ .exec(mat.fragmentShader);
+console.log(JSON.stringify({
+ deepest: mid(m),
+ opaque: mat.uniforms.uOpaqueM.value,
+ lo: edges ? parseFloat(edges[1]) : null,
+ hi: edges ? parseFloat(edges[2]) : null,
+}));
+""", _LIBS)
+ dep = out["deepest"] / out["opaque"]
+ assert dep >= 0.85, (
+ f"a 1 m river only reaches dep {dep:.2f}; it will render as its "
+ "shallow colour nearly everywhere")
+ assert out["hi"] is not None and out["hi"] <= dep, (
+ f"the deep end of the ramp ({out['hi']}) sits past where a real "
+ f"river ever gets ({dep:.2f})")
+ # ...and it is a RAMP: at 0.34 the colour saturated the moment the
+ # bed dropped away and the whole channel became one flat value.
+ assert out["hi"] - out["lo"] > 0.4, out
+
+
+def test_the_surface_takes_its_light_from_the_scene():
+ """OURS. The surface is unlit — it writes its own light out — so a
+ daylight constant baked into the factory is a river that glows under
+ a moon. Measured on this harness's night rig with the reference
+ defaults, the channel came back at luminance 0.40/0.54 over a frame
+ whose mean was 0.21/0.31. It now reads the key light's direction,
+ colour and STRENGTH and the sky half of the hemisphere fill at the
+ first render, so a night scene darkens the water with it."""
+ out = measure(_LIT_SCENE + """
+import * as THREE from 'three';
+import { makeRiver } from './lib/river.js';
+const day = makeRiver({ width: 6, seed: 3 });
+const dayU = adopt(day, litScene(THREE, {}));
+// The same river in the night rig's own numbers: a 2.2 moon and a 1.0
+// fill, both cool.
+const night = makeRiver({ width: 6, seed: 3 });
+const nightU = adopt(night, litScene(THREE, {
+ sunHex: 0xb5c7e8, sunI: 2.2, skyHex: 0x3f5378, fillI: 1.0 }));
+const lum = (c) => 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
+console.log(JSON.stringify({
+ sun: [+dayU.uSun.value.x.toFixed(3), +dayU.uSun.value.y.toFixed(3),
+ +dayU.uSun.value.z.toFixed(3)],
+ daySunLum: +lum(dayU.uSunCol.value).toFixed(4),
+ nightSunLum: +lum(nightU.uSunCol.value).toFixed(4),
+ daySkyLum: +lum(dayU.uSky.value).toFixed(4),
+ nightSkyLum: +lum(nightU.uSky.value).toFixed(4),
+ nightSkyBlue: nightU.uSky.value.b > nightU.uSky.value.r,
+ dayAmbLum: +lum(dayU.uAmb.value).toFixed(4),
+ nightAmbLum: +lum(nightU.uAmb.value).toFixed(4),
+}));
+""", _LIBS)
+ # The light at (30, 40, -10) shines DOWN; uSun points back up at it.
+ d = out["sun"]
+ n = (d[0] ** 2 + d[1] ** 2 + d[2] ** 2) ** 0.5
+ assert abs(n - 1) < 1e-3, out
+ assert abs(d[0] / n - 0.588) < 0.01 and abs(d[1] / n - 0.784) < 0.01, out
+ # Strength, not just hue: the moon rig has to arrive dimmer than the
+ # sun rig in every one of the three terms the body colour is built
+ # from, or "night" is a colour swap and nothing else.
+ assert out["nightSunLum"] < out["daySunLum"] * 0.55, out
+ assert out["nightSkyLum"] < out["daySkyLum"] * 0.35, out
+ assert out["nightAmbLum"] < out["dayAmbLum"] * 0.35, out
+ # ...and the night sky it reflects is BLUE, not grey: dark but lit.
+ assert out["nightSkyBlue"], out
+
+
+def test_a_colour_the_caller_pinned_survives_the_scene():
+ """Reading the scene is a DEFAULT, not a seizure: a caller who wrote
+ a sunset river down in hex has to get that river in a scene lit any
+ way at all, or the option is decoration."""
+ out = measure(_LIT_SCENE + """
+import * as THREE from 'three';
+import { makeRiver } from './lib/river.js';
+const dir = new THREE.Vector3(0, 1, 0);
+const g = makeRiver({ width: 6, seed: 3, sky: 0xff0000,
+ sunColor: 0x00ff00, ambient: 0x0000ff,
+ sunDir: dir });
+const u = adopt(g, litScene(THREE, {}));
+// Nothing pinned: only these move.
+const g2 = makeRiver({ width: 6, seed: 3 });
+const u2 = adopt(g2, litScene(THREE, {}));
+console.log(JSON.stringify({
+ sky: hex(u.uSky.value), sun: hex(u.uSunCol.value),
+ amb: hex(u.uAmb.value),
+ dir: [u.uSun.value.x, u.uSun.value.y, u.uSun.value.z],
+ freeSkyIsRed: u2.uSky.value.r > u2.uSky.value.b,
+}));
+""", _LIBS)
+ assert out["sky"] == [1, 0, 0] and out["sun"] == [0, 1, 0], out
+ assert out["amb"] == [0, 0, 1], out
+ assert out["dir"] == [0, 1, 0], out
+ # The control: with nothing pinned the scene's own pale-blue sky is
+ # what lands, so the assertions above are not passing vacuously.
+ assert not out["freeSkyIsRed"], out
+
+
+_SCENE = """
+import * as THREE from 'three';
+import { makeRiver } from './lib/river.js';
+import { tickShaders } from './lib/shader.js';
+
+export const BOUNDS = { min: [-20, -2, -20], max: [20, 6, 20] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ // Fogged, because the flow map is one custom shader on the raw route
+ // and the fog chunk is exactly what a hand-written shader forgets.
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.004);
+ const key = new THREE.DirectionalLight(0xfff0d8, 5.4);
+ key.position.set(30, 40, -10);
+ scene.add(key);
+ scene.add(new THREE.HemisphereLight(0x9db8e8, 0x8a7f6a, 1.4));
+ const river = makeRiver({
+ points: __POINTS__, width: (u) => 5.6 * (1 - 0.4 * Math.exp(
+ -Math.pow((u - 0.5) / 0.08, 2))),
+ depth: 1.4, flow: 1.4, seed: 4,
+ heightAt: (x, z) => Math.max(0, 1.5 - Math.hypot(x - 1.4, z - 2.2))
+ - 1.6,
+ });
+ scene.add(river);
+ // A camera, because the host reports a scene with none as not booted
+ // and never reaches the compile stage at all.
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [9, 3, 11], lookAt: [0, 0, 0],
+ fov: 45 }],
+ update(t) { tickShaders(scene, t); river.userData.tick(t); },
+ };
+}
+""".replace("__POINTS__", _POINTS)
+
+
+def test_the_river_compiles_on_the_real_renderer():
+ """The flow map is one custom shader on the raw route, so the depth
+ and fog chunks are the difference between a river and nothing at
+ all — and only the GPU can say whether it compiled."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "every program compiled" in out
+ assert "WARN" not in out, out
diff --git a/harness/tests/scene_runtime/lib/test_roadway.py b/harness/tests/scene_runtime/lib/test_roadway.py
new file mode 100644
index 00000000..076be477
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_roadway.py
@@ -0,0 +1,936 @@
+"""roadway.js: the road's own frame, and the chain it lands in.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_roadway_lib.py). Their claims are kept as they stood — one road
+frame shared by three patches, ruts along the ROAD's own axis and not a world
+one, whole lanes so the wheel strips land on the road, a seam band bounded by
+the width it was given, a track count and kind that are uniforms, nobody
+assigning over the albedo they landed on, one seed one road, and every field
+finer than its pixel faded out before it can alias.
+
+THE PORT'S OWN LAW, and the regression this file exists to stop:
+
+A ROAD MAY NOT BE POLISHED INTO A SKY MIRROR. `fragmentBody` lands after
+<color_fragment> and therefore before <roughnessmap_fragment> declares
+roughnessFactor, so the one gloss move these patches have is the MATERIAL's —
+which makes it an area-weighted average, not the polished rut's own value.
+The reference spent the rut's full polish on the whole surface (-0.26 * wear,
+-0.18 * gutter, -0.22 * depth). On our renderer that is not a wet look, it is
+a white card: no post chain, a bright sky environment as the specular source,
+and a road is nearly always seen at a grazing angle where a smooth dielectric
+is almost all Fresnel. Measured on the showcase host (fx/out/roadway,
+2026-09-01, tarmac authored at roughness 0.85): the old factors composed it to
+0.63 and the carriageway read (171,172,175) with mean luminance 0.68 — every
+repair, wheel strip and drip line the patch drew was washed out of it. The
+area-weighted factors here compose the same material to 0.86 and it reads
+(136,138,144) at 0.54, with the repairs, the pale wheel strips and the dark
+drip line all back. Half this file's new assertions are that bound.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from collections import Counter
+
+import pytest
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "noise.js", "materials.js", "terrain_shade.js",
+ "surface_wear.js", "aging.js", "accumulation.js", "strata.js",
+ "roadway.js")
+
+_LIB_SRC = (LIB_DIR / "roadway.js").read_text(encoding="utf-8")
+
+# The patch only exists inside onBeforeCompile, so every probe hands it the
+# two chunks patchStandard replaces and reads back what it wrote.
+_PRELUDE = """
+import * as THREE from 'three';
+import { patchRoadSurface, patchSeamBand, patchTracks }
+ from './lib/roadway.js';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+import { patchDripStains, patchRust, patchDust } from './lib/aging.js';
+import { patchSnow, patchSand } from './lib/accumulation.js';
+import { patchRockStrata, patchErosionStreaks } from './lib/strata.js';
+
+const std = (o = {}) => new THREE.MeshStandardMaterial(
+ Object.assign({ color: 0x8b8478, roughness: 0.7 }, o));
+
+function compile(mat) {
+ const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+ };
+ mat.onBeforeCompile(shader);
+ return shader;
+}
+
+const count = (src, needle) => src.split(needle).length - 1;
+"""
+
+# The showcase scene, as a compile fixture: a two-lane road TURNED off the
+# world axes (a rut that ran down +Z would still look right on a road laid
+# along +Z), its kerb stones INSTANCED on the road's own material — the only
+# thing that compiles the USE_INSTANCING branch of the frame — and a mud verge
+# and a footpath beside it that share one program because `kind` and `offset`
+# are uniforms.
+_SCENE = """
+import * as THREE from 'three';
+import { patchTriplanar } from './lib/terrain_shade.js';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+import { patchRoadSurface, patchSeamBand, patchTracks }
+ from './lib/roadway.js';
+
+const HALF = 3.5;
+const LEN = 110;
+
+function roadGeo() {
+ const g = new THREE.PlaneGeometry(HALF * 2, LEN, 40, 200);
+ g.rotateX(-Math.PI / 2);
+ const p = g.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ const t = p.getX(i) / HALF;
+ p.setY(i, 0.26 - 0.085 * t * t + Math.sin(p.getZ(i) * 0.13) * 0.02);
+ }
+ g.computeVertexNormals();
+ return g;
+}
+
+function slab(x0, x1, top) {
+ const g = new THREE.BoxGeometry(x1 - x0, top, LEN);
+ g.translate((x0 + x1) / 2, top / 2, 0);
+ return g;
+}
+
+function build() {
+ const root = new THREE.Group();
+ const g = new THREE.Group();
+ g.rotation.y = 38 * Math.PI / 180;
+ root.add(g);
+
+ const tar = new THREE.MeshStandardMaterial(
+ { color: 0x585856, roughness: 0.85, name: 'Tarmac' });
+ const verge = new THREE.MeshStandardMaterial(
+ { color: 0x5d6b34, roughness: 0.95, name: 'Verge' });
+ const mud = new THREE.MeshStandardMaterial(
+ { color: 0x5b4a35, roughness: 0.92, name: 'Mud' });
+ const path = new THREE.MeshStandardMaterial(
+ { color: 0x6b5a42, roughness: 0.93, name: 'Path' });
+
+ const add = (geo, mat) => { g.add(new THREE.Mesh(geo, mat)); };
+ add(roadGeo(), tar);
+ add(slab(-HALF, HALF, 0.17), tar);
+ add(slab(-15, -HALF - 0.04, 0.30), verge);
+ add(slab(HALF + 0.02, 6.4, 0.20), mud);
+ add(slab(6.4, 15, 0.28), verge);
+ add(slab(7.2, 8.6, 0.30), path);
+
+ const kerb = new THREE.InstancedMesh(
+ new THREE.BoxGeometry(0.16, 0.40, 0.88), tar, 40);
+ const mx = new THREE.Matrix4();
+ for (let i = 0; i < 40; i++) {
+ mx.makeTranslation(-HALF - 0.10, 0.19, -18 + i * 0.92);
+ kerb.setMatrixAt(i, mx);
+ }
+ kerb.instanceMatrix.needsUpdate = true;
+ kerb.frustumCulled = false;
+ g.add(kerb);
+
+ patchTriplanar(tar, { scale: 1.4, colorA: 0x44443f, colorB: 0x6a6a63 });
+ patchMicroBreakup(tar, { seed: 3, strength: 0.10 });
+ patchEdgeWear(tar, { seed: 3, strength: 0.25, width: 0.30 });
+ patchRoadSurface(tar, {
+ aggregate: 0.30, wear: 0.75, patches: 0.35, gutter: 0.70,
+ color: 0x4c4c4e, halfWidth: HALF, lane: 3.4, center: [0, 0, 0], seed: 4,
+ });
+ patchSeamBand(tar, { width: 0.75, weeds: 0.5, seed: 4 });
+ patchTracks(tar, { count: 2, depth: 0.32, kind: 'tyre', seed: 4 });
+ patchSeamBand(verge, {
+ width: 1.1, weeds: 0.85, halfWidth: HALF + 0.14, center: [0, 0, 0],
+ seed: 6,
+ });
+ patchTracks(mud, {
+ count: 2, depth: 0.85, kind: 'tyre', gauge: 1.55, offset: 4.9,
+ halfWidth: HALF, center: [0, 0, 0], seed: 8,
+ });
+ patchTracks(path, {
+ count: 1, depth: 0.8, kind: 'foot', offset: 7.9,
+ halfWidth: HALF, center: [0, 0, 0], seed: 9,
+ });
+ return root;
+}
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ const sun = new THREE.DirectionalLight(0xfff0d8, 3.0);
+ sun.position.set(-6, 9, -4);
+ scene.add(sun);
+ scene.add(new THREE.HemisphereLight(0xbfd4ee, 0x6a5a44, 0.6));
+ scene.add(build());
+ const cameras = [
+ { name: 'road', position: [14, 6, 18], lookAt: [0, 2, 0], fov: 45 },
+ ];
+ return { scene, cameras, update() {} };
+}
+"""
+
+
+def _probe(body: str) -> dict:
+ return measure(_PRELUDE + body, _LIBS)
+
+
+def _find(pattern: str, src: str) -> re.Match:
+ m = re.search(pattern, src)
+ assert m, f"{pattern} not in\n{src}"
+ return m
+
+
+def _main_body(src: str) -> str:
+ return src[src.index("void main"):]
+
+
+def _unguarded(src: str) -> str:
+ """Drop `#ifndef X ... #endif` blocks, which may repeat verbatim.
+
+ terrain_shade ships astraFbmUnit from two patches behind one guard, so the
+ TEXT carries it twice and the preprocessor keeps one. Only an unguarded
+ repeat is a redefinition.
+ """
+ return re.sub(r"#ifndef\b.*?#endif", "", src, flags=re.S)
+
+
+def test_the_whole_road_stack_compiles_on_our_gpu():
+ """The stack this library exists to join, on a real GPU: the road surface,
+ its seam band and its tracks on the SAME material that already carries a
+ triplanar, a micro breakup and an edge wear, in a scene that also puts
+ that material on an InstancedMesh. Only a real instanced draw compiles
+ the USE_INSTANCING branch of the frame, and only a real compile proves
+ three libraries' varyings, helpers and main() locals survive being
+ concatenated into one program."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out
+ report = json.loads(out.strip().splitlines()[-1])
+ assert report["errors"] == [], report
+ assert report["compile"]["gpu"], "this claim is only worth a real GPU"
+ # The mud and the path differ only by `kind` and `offset`, so they SHARE
+ # one cache key and one program — the whole reason those are uniforms.
+ # The extra program is the instanced kerb on the road's own material.
+ assert report["compile"]["custom_materials"] >= 4, report
+ assert report["compile"]["programs"] >= 4, report
+
+
+def test_the_three_patches_chain_without_losing_each_other():
+ """A road wears all three at once — the surface, the gravel where it
+ stops, and what drove over it — and patchStandard repeats whatever it is
+ handed: the shared frame and its three helpers must be emitted ONCE (a
+ second function body throws), the frame must run FIRST or every fragment
+ body reads a varying nobody wrote, and re-applying a patch has to retune
+ its uniforms rather than inject a second copy of its code."""
+ out = _probe("""
+const m = std();
+patchRoadSurface(m, { wear: 0.2 });
+patchSeamBand(m, { width: 0.4 });
+patchTracks(m, { count: 3 });
+patchRoadSurface(m, { wear: 0.9 });
+const s = compile(m);
+const seamOnly = std();
+patchSeamBand(seamOnly);
+console.log(JSON.stringify({
+ key: m.customProgramCacheKey(), seamKey: seamOnly.customProgramCacheKey(),
+ road: s.fragmentShader.includes('diffuseColor.rgb = roCol;'),
+ seam: s.fragmentShader.includes('diffuseColor.rgb = mix(diffuseColor.rgb,'
+ + ' smCol, smK * 0.88);'),
+ track: s.fragmentShader.includes('diffuseColor.rgb = mix(diffuseColor.rgb,'
+ + ' tkCol,'),
+ wear: m.userData.uniforms.uRoadWear.value,
+ frameBody: count(s.vertexShader, 'vec4 rwP ='),
+ axesFn: count(s.fragmentShader, 'vec3 astraRoadAxes(vec3 n) {'),
+ noiseFn: count(s.fragmentShader, 'float astraRoadNoise('),
+ fadeFn: count(s.fragmentShader, 'float astraRoadFade('),
+ roadLine: count(s.fragmentShader, 'float roRut ='),
+ varyVs: count(s.vertexShader, 'varying vec4 vAstraRoad;'),
+ varyFs: count(s.fragmentShader, 'varying vec4 vAstraRoad;'),
+ frameFirst: s.fragmentShader.indexOf('vec3 astraRoadAxes')
+ < s.fragmentShader.indexOf('float roU ='),
+}));
+""")
+ assert out["road"] and out["seam"] and out["track"], "a patch was lost"
+ assert out["frameBody"] == 1 and out["axesFn"] == 1
+ assert out["noiseFn"] == 1 and out["fadeFn"] == 1
+ assert out["varyVs"] == 1 and out["varyFs"] == 1
+ assert out["frameFirst"], "a fragment body runs before the frame helpers"
+ # Every option is a uniform, so re-applying retunes in place.
+ assert out["roadLine"] == 1 and out["wear"] == 0.9
+ assert out["key"] == ("astra:road:frame+road:surface+road:seam"
+ "+road:tracks"), out["key"]
+ # A longer chain must not collide with a shorter one's program.
+ assert out["seamKey"] == "astra:road:frame+road:seam"
+
+
+def test_the_ruts_run_along_the_roads_own_direction_not_a_world_axis():
+ """The one claim that makes this a roadway library. A rut is a line of
+ constant ACROSS, so ruts drawn on a world axis stay put while the road
+ turns away from them — and every road in these scenes is laid at some
+ angle, or curves. So the direction is the mesh's OWN axis carried through
+ modelMatrix (and instanceMatrix, or every copy of a segment kit takes the
+ mesh origin's road), across is the horizontal perpendicular measured from
+ the mesh's own origin, and NOTHING in the fragment stage reads world .x or
+ .z. `dir` is a uniform, so two roads at two angles still share one
+ compiled program."""
+ out = _probe("""
+const a = std();
+patchRoadSurface(a, { wear: 0.8 });
+const b = std();
+patchRoadSurface(b, { wear: 0.8, dir: [1, 0, 0] });
+const arr = std();
+patchRoadSurface(arr, { dir: new THREE.Vector3(0, 0, 9) });
+const dead = std();
+patchRoadSurface(dead, { dir: [0, 0, 0] });
+const sa = compile(a), sb = compile(b);
+const u = (m, n) => m.userData.uniforms[n].value.toArray();
+console.log(JSON.stringify({
+ sameKey: a.customProgramCacheKey() === b.customProgramCacheKey(),
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ sameVs: sa.vertexShader === sb.vertexShader,
+ dirA: u(a, 'uRoadDir'), dirB: u(b, 'uRoadDir'),
+ unit: u(arr, 'uRoadDir'), dead: u(dead, 'uRoadDir'),
+ vs: sa.vertexShader, fs: sa.fragmentShader,
+}));
+""")
+ assert out["sameKey"] and out["sameFs"] and out["sameVs"], \
+ "the direction was baked into the source"
+ assert out["dirA"] == [0, 0, 1] and out["dirB"] == [1, 0, 0]
+ assert out["unit"] == [0, 0, 1], "an unnormalised dir must be normalised"
+ assert out["dead"] == [0, 0, 1], "a zero dir must fall back, not NaN"
+ vbody = _main_body(out["vs"])
+ _find(r"vec4 rwD = vec4\(uRoadDir, 0\.0\);", vbody)
+ _find(r"vec3 rwA = normalize\(\(modelMatrix \* rwD\)\.xyz\);", vbody)
+ _find(r"rwD = mix\(instanceMatrix \* rwD, rwD, uRoadCenter\.w\);", vbody)
+ _find(r"rwO = mix\(instanceMatrix \* rwO, rwO, uRoadCenter\.w\);", vbody)
+ assert "#ifdef USE_INSTANCING" in vbody
+ assert "attribute mat4 instanceMatrix" not in out["vs"]
+ _find(r"vec3 rwX = cross\(vec3\(0\.0, 1\.0, 0\.0\), rwA\);", vbody)
+ _find(r"vAstraRoad = vec4\(rwA, dot\(vAstraWorld - rwC, rwX\)\);", vbody)
+ body = _main_body(out["fs"])
+ # THE CLAIM: along is a projection on that axis and the rut is a line of
+ # constant across. Neither is a world coordinate.
+ _find(r"float roU = dot\(vAstraWorld, vAstraRoad\.xyz\);", body)
+ _find(r"float roRut = \(1\.0 - smoothstep\([\d.]+, [\d.]+,\s*"
+ r"abs\(abs\(vAstraRoad\.w - roCen\) - roTr \+ roWob\)\)\)\s*"
+ r"\* uRoadWear;", body)
+ # The wheel lines wander along the road, or the pair reads as rails.
+ _find(r"float roWob = \(astraNoise2\(vec2\(roU \* [\d.]+, [\d.]+\)"
+ r" \+ uRoadSeed\.yz\)\s*- 0\.5\) \* [\d.]+;", body)
+ for axis in ("vAstraWorld.x", "vAstraWorld.z", "vAstraWorld.y"):
+ assert axis not in body, f"{axis} — the frame is not the world axes"
+ assert "vUv" not in body
+
+
+def test_the_road_is_divided_into_whole_lanes_so_the_ruts_land_inside():
+ """A road is worn in TWO STRIPS PER LANE — that asymmetry is the whole cue
+ — so the wheel lines have to land where wheels go: a single-track lane
+ keeps ONE pair near its middle, a two-lane road gets four strips, and no
+ rut may sit off the edge of the surface."""
+ out = _probe("""
+const m = std();
+patchRoadSurface(m, { halfWidth: 2.1, lane: 2.2, wear: 0.9 });
+console.log(JSON.stringify({ fs: compile(m).fragmentShader,
+ half: m.userData.uniforms.uRoadHalf.value,
+ lane: m.userData.uniforms.uRoadLane.value }));
+""")
+ body = _main_body(out["fs"])
+ _find(r"float roN = max\(floor\(2\.0 \* uRoadHalf"
+ r" / max\(uRoadLane, [\d.]+\)\), 1\.0\);", body)
+ _find(r"float roLw = 2\.0 \* uRoadHalf / roN;", body)
+ _find(r"float roK = clamp\(floor\(\(vAstraRoad\.w \+ uRoadHalf\)"
+ r" / roLw\),\s*0\.0, roN - 1\.0\);", body)
+ _find(r"float roCen = \(roK \+ 0\.5\) \* roLw - uRoadHalf;", body)
+ track = _find(r"float roTr = min\(([\d.]+), roLw \* ([\d.]+)\);", body)
+ assert 0.6 <= float(track.group(1)) <= 0.9, "a car's half-track is ~0.75 m"
+ assert float(track.group(2)) < 0.5, "both wheels must fit in the lane"
+
+ # The same arithmetic, run here: every rut inside the road, and a narrow
+ # lane keeping one pair rather than a phantom second one.
+ def ruts(half, lane):
+ n = max(1.0, (2 * half) // max(lane, 0.5))
+ width = 2 * half / n
+ tr = min(0.75, width * 0.32)
+ out_ = []
+ for k in range(int(n)):
+ c = (k + 0.5) * width - half
+ out_ += [round(c - tr, 3), round(c + tr, 3)]
+ return out_
+ assert ruts(2.1, 2.2) == [-0.75, 0.75], "a single lane keeps one pair"
+ assert ruts(3.5, 3.4) == [-2.5, -1.0, 1.0, 2.5], "two lanes, four strips"
+ for half, lane in ((2.1, 2.2), (3.5, 3.4), (5.4, 3.4), (1.2, 3.4)):
+ assert all(abs(r) < half for r in ruts(half, lane)), (half, lane)
+
+
+def test_the_seam_band_is_bounded_by_the_width_it_was_given():
+ """A gravel band that wanders is right and one that wanders OUT of the
+ width it was given is not: a scene that placed a kerb, a verge or a puddle
+ against it needs the number it passed to mean something. So the
+ raggedness is in the band's HALF-WIDTH, never in its position, and the
+ hairline of shadow in the joint fades out by its own pixel size."""
+ out = _probe("""
+const m = std();
+patchSeamBand(m, { width: 0.8, weeds: 0.6, halfWidth: 3.0 });
+const thin = std();
+patchSeamBand(thin, { width: 0 });
+console.log(JSON.stringify({
+ fs: compile(m).fragmentShader,
+ width: m.userData.uniforms.uSeamWidth.value,
+ degenerate: thin.userData.uniforms.uSeamWidth.value,
+}));
+""")
+ assert out["width"] == 0.8
+ assert out["degenerate"] > 0, "a zero width must not divide by zero"
+ body = _main_body(out["fs"])
+ _find(r"float smD = abs\(vAstraRoad\.w\) - uRoadHalf;", body)
+ _find(r"float smH = uSeamWidth \* 0\.5;", body)
+ rag = _find(r"float smR = mix\(([\d.]+), ([\d.]+), astraNoise2\(", body)
+ lo, hi = float(rag.group(1)), float(rag.group(2))
+ assert 0 < lo < hi <= 1.0, "the wander must not widen the band"
+ mask = _find(r"float smK = 1\.0 - smoothstep\(smR \* smH \* ([\d.]+),"
+ r" smR \* smH,\s*abs\(smD\)\);", body)
+ assert float(mask.group(1)) < 1, "the band needs a soft inner edge"
+ # THE BOUND: the outer smoothstep edge is smR * smH <= smH, so the mask is
+ # 0 for |smD| >= width / 2 for every value the noise takes.
+ assert "smoothstep(smR * smH * " in body
+ # Weeds take the joint and the ground side of it, never the tarmac.
+ _find(r"float smOut = smoothstep\(-smH \* [\d.]+, smH \* [\d.]+,"
+ r" smD\);", body)
+ _find(r"\* mix\([\d.]+, 1\.0, smOut\) \* uSeamWeeds;", body)
+ _find(r"float smJt = \(1\.0 - smoothstep\(0\.0, smH \* [\d.]+,"
+ r" abs\(smD\)\)\)\s*\* astraRoadFade\(vAstraWorld,"
+ r" smH \* [\d.]+\);", body)
+
+
+def test_tracks_follow_the_direction_and_the_count_they_were_given():
+ """`count` tracks means count tracks: one walker leaves one trail, a
+ vehicle leaves two, a twin-axle rig four — and they run along the road
+ frame's direction, spaced by a gauge, so a pair is a vehicle rather than a
+ railway. The count and the gauge are UNIFORMS (the loop is bounded by a
+ constant and breaks on the count), the count is clamped to what the loop
+ can reach, and `offset` moves the whole group across the frame so tracks
+ and a seam band can share one material."""
+ out = _probe("""
+const mk = (o) => { const m = std(); patchTracks(m, o); return m; };
+const two = mk({ count: 2 });
+const four = mk({ count: 4, gauge: 0.9 });
+const many = mk({ count: 40 });
+const none = mk({ count: 0 });
+const half = mk({ count: 2.6 });
+const foot = mk({ kind: 'foot' });
+const off = mk({ count: 2, offset: 4.85 });
+const u = (m, n) => m.userData.uniforms[n].value;
+console.log(JSON.stringify({
+ sameKey: two.customProgramCacheKey() === four.customProgramCacheKey(),
+ sameFs: compile(two).fragmentShader === compile(four).fragmentShader,
+ counts: [u(two, 'uTrkCount'), u(four, 'uTrkCount'), u(many, 'uTrkCount'),
+ u(none, 'uTrkCount'), u(half, 'uTrkCount')],
+ gauges: [u(two, 'uTrkGauge'), u(four, 'uTrkGauge'), u(foot, 'uTrkGauge')],
+ offsets: [u(two, 'uTrkOffset'), u(off, 'uTrkOffset')],
+ fs: compile(two).fragmentShader,
+}));
+""")
+ assert out["sameKey"] and out["sameFs"], "the count was baked in"
+ assert out["counts"] == [2, 4, 8, 1, 3], out["counts"]
+ # A walker's feet are 30 cm apart and a car's wheels 1.6 m: the default
+ # follows the KIND, and both are uniforms.
+ assert out["gauges"] == [1.6, 0.9, 0.3]
+ assert out["offsets"] == [0, 4.85]
+ body = _main_body(out["fs"])
+ loop = _find(r"for \(int i = 0; i < (\d+); i\+\+\) \{\s*"
+ r"if \(float\(i\) >= uTrkCount\) break;", body)
+ assert int(loop.group(1)) == 8, "the clamp must match the loop bound"
+ _find(r"float tkO = \(float\(i\) - \(uTrkCount - 1\.0\) \* 0\.5\)"
+ r" \* uTrkGauge\s*\+ uTrkOffset;", body)
+ _find(r"float tkU = dot\(vAstraWorld, vAstraRoad\.xyz\);", body)
+ _find(r"float tkWob = \(astraNoise2\(vec2\(tkU \* [\d.]+,"
+ r" float\(i\) \* [\d.]+\)\s*\+ uTrkSeed\.xy\) - 0\.5\)"
+ r" \* [\d.]+;", body)
+ _find(r"float tkX = vAstraRoad\.w - tkO - tkWob;", body)
+ assert "vAstraWorld.x" not in body and "vAstraWorld.z" not in body
+
+
+def test_kind_is_a_uniform_and_both_kinds_are_one_shader():
+ """'tyre' and 'foot' are two different marks, and baking either into the
+ GLSL would hand the first material to compile the cache key its own kind
+ for every material that shares it. So the kind is a uniform the shader
+ mixes on, the tyre's tread rides `astraStroke` (which kills itself once a
+ pixel spans a rib), the foot's prints step to alternating sides of their
+ line, and neither survives past the distance it can be resolved."""
+ out = _probe("""
+const tyre = std();
+patchTracks(tyre, { kind: 'tyre', depth: 0.6 });
+const foot = std();
+patchTracks(foot, { kind: 'foot', depth: 0.6 });
+const odd = std();
+patchTracks(odd, { kind: 'hovercraft' });
+const st = compile(tyre), sf = compile(foot);
+console.log(JSON.stringify({
+ sameKey: tyre.customProgramCacheKey() === foot.customProgramCacheKey(),
+ sameFs: st.fragmentShader === sf.fragmentShader,
+ kinds: [tyre.userData.uniforms.uTrkKind.value,
+ foot.userData.uniforms.uTrkKind.value,
+ odd.userData.uniforms.uTrkKind.value],
+ fs: st.fragmentShader,
+}));
+""")
+ assert out["sameKey"] and out["sameFs"], "the kind was baked in"
+ assert out["kinds"] == [0, 1, 0], "an unknown kind must fall back to tyre"
+ body = _main_body(out["fs"])
+ _find(r"float tkHw = mix\(([\d.]+), ([\d.]+), uTrkKind\);", body)
+ rib = _find(r"float tkRb = astraStroke\(tkU / ([\d.]+)"
+ r" \+ abs\(tkX\) \* [\d.]+,\s*([\d.]+)\);", body)
+ # astraStroke clamps its own antialias width at 0.30 and only kills itself
+ # past w * 1.5, so a rib wider than 0.20 would grey out and stay there.
+ assert float(rib.group(2)) < 0.20, rib.group(2)
+ _find(r"float tkC = floor\(tkU / ([\d.]+)\);", body)
+ _find(r"float tkAc = \(tkX - \(mod\(tkC, 2\.0\) - 0\.5\) \* [\d.]+\)"
+ r" / [\d.]+;", body)
+ _find(r"float tkFd = astraRoadFade\(vAstraWorld, [\d.]+\);", body)
+ _find(r"float tkPr = mix\(tkTr, 1\.0 - smoothstep\([\d.]+, 1\.0, tkE\),"
+ r" tkFd\);", body)
+ for line in ("tkPress = max(tkPress, mix(tkB, tkPr, uTrkKind));",
+ "tkWide = max(tkWide, mix(tkBw, tkPw, uTrkKind));"):
+ assert line in body, line
+ assert "if (uTrkKind" not in body
+
+
+def test_no_patch_assigns_over_the_colour_it_landed_on():
+ """These three land on materials that already carry a triplanar, a
+ breakup, an edge wear, rust or snow — every one of which wrote the albedo
+ first. So each must READ what is there before it writes: the seam and the
+ tracks mix over it by their own mask, and the road, which does rule the
+ hue of a made surface, carries the incoming albedo through as its
+ light/dark variation."""
+ out = _probe("""
+const m = std();
+patchTriplanar(m);
+patchMicroBreakup(m);
+patchRoadSurface(m);
+patchSeamBand(m);
+patchTracks(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ body = _main_body(out["fs"])
+ # Every write THIS library makes either mixes with the albedo, scales it,
+ # or assigns a local that was built from it.
+ writes = re.findall(r"diffuseColor\.rgb\s*([*+]?=)\s*(.+?);",
+ _LIB_SRC, re.S)
+ assert len(writes) >= 5, writes
+ for op, rhs in writes:
+ ok = op != "=" or "diffuseColor" in rhs or rhs.strip() == "roCol"
+ assert ok, f"assigns over what it landed on: {op} {rhs}"
+ keep = body.index("float roKeep = dot(diffuseColor.rgb")
+ assert body.index("diffuseColor.rgb = tpC;") < keep
+ assert keep < body.index("diffuseColor.rgb = roCol;")
+ _find(r"vec3 roCol = uRoadColor\s*"
+ r"\* mix\([\d.]+, [\d.]+, clamp\(roKeep \* [\d.]+,"
+ r" 0\.0, 1\.0\)\);", body)
+ # The tracks are made OF the surface they are pressed into, so their
+ # colour is that same albedo darkened — never a colour of their own.
+ _find(r"vec3 tkCol = diffuseColor\.rgb \* mix\(1\.0, [\d.]+,"
+ r" uTrkDepth\)", body)
+ _find(r"diffuseColor\.rgb = mix\(diffuseColor\.rgb, smCol,"
+ r" smK \* [\d.]+\);", body)
+ _find(r"diffuseColor\.rgb = mix\(diffuseColor\.rgb, tkCol,\s*"
+ r"clamp\(tkPress \* uTrkDepth, 0\.0, 1\.0\)\);", body)
+ # Nothing here displaces geometry: albedo and gloss only, because the
+ # vertex hook cannot reach a per-pixel depth and a displacement would tear
+ # a hard-edged kerb open at its rim.
+ vs = _main_body(_probe("""
+const m = std();
+patchRoadSurface(m); patchTracks(m);
+console.log(JSON.stringify({ fs: compile(m).vertexShader }));
+""")["fs"])
+ assert "transformed +=" not in vs and "transformed *=" not in vs
+
+
+def test_no_patch_declares_a_name_its_neighbours_own():
+ """The silent failure this library is most exposed to: a road rides the
+ same materials as surface_wear, terrain_shade, aging, accumulation and
+ strata, and patchStandard DROPS a repeated uniform or varying and keeps
+ the first — so a shared name would leave one patch reading the other's
+ value with nothing reported. A repeated main() local is a compile error
+ instead, and a repeated helper throws."""
+ out = _probe("""
+const road = std();
+patchRoadSurface(road);
+patchSeamBand(road);
+patchTracks(road);
+const nbr = std();
+patchTriplanar(nbr);
+patchSlopeSplat(nbr, { snowLine: 30 });
+patchMicroBreakup(nbr);
+patchEdgeWear(nbr);
+patchDripStains(nbr);
+patchRust(nbr);
+patchDust(nbr);
+patchSnow(nbr);
+patchSand(nbr);
+patchRockStrata(nbr);
+patchErosionStreaks(nbr);
+const all = std();
+patchTriplanar(all);
+patchSlopeSplat(all, { snowLine: 30 });
+patchMicroBreakup(all);
+patchEdgeWear(all);
+patchDripStains(all);
+patchRust(all);
+patchDust(all);
+patchSnow(all);
+patchSand(all);
+patchRockStrata(all);
+patchErosionStreaks(all);
+patchRoadSurface(all);
+patchSeamBand(all);
+patchTracks(all);
+const s = compile(all);
+console.log(JSON.stringify({
+ roadU: Object.keys(road.userData.uniforms),
+ nbrU: Object.keys(nbr.userData.uniforms),
+ vs: s.vertexShader, fs: s.fragmentShader,
+}));
+""")
+ shared = set(out["roadU"]) & set(out["nbrU"])
+ assert shared == {"uTime"}, shared
+ for stage in ("vs", "fs"):
+ src = out[stage]
+ decls = re.findall(
+ r"^\s*(?:uniform|varying)\s+(?:lowp |mediump |highp )?"
+ r"[a-z0-9]+\s+(\w+)\s*;", src, re.M)
+ dupes = [n for n, c in Counter(decls).items() if c > 1]
+ assert not dupes, f"{stage} declares {dupes} twice"
+ fns = re.findall(r"^(?:float|vec[234]|int|mat[234])\s+(\w+)\s*\(",
+ _unguarded(src), re.M)
+ assert not [n for n, c in Counter(fns).items() if c > 1]
+ locals_ = re.findall(
+ r"^\s*(?:float|vec[234]|int|mat[234])\s+(\w+)\s*=",
+ _main_body(src), re.M)
+ clash = [n for n, c in Counter(locals_).items() if c > 1]
+ assert not clash, f"{stage} main() declares {clash} twice"
+ assert "vAstraWorld" in out["vs"] and "vAstraRoad" in out["fs"]
+ # fwidth, dFdx and astraStroke are fragment-only, and the util block ships
+ # in both stages: they may be DEFINED in the vertex shader, never called.
+ vbody = _main_body(out["vs"])
+ assert "fwidth(" not in vbody and "dFdx(" not in vbody
+ assert "astraStroke(" not in vbody
+ # Every helper this library adds is astraRoad-prefixed, so a neighbour's
+ # astraWear/astraAge/astraAcc/astraStrata body survives.
+ mine = re.findall(r"'(?:float|vec[234])\s+(astra\w+)\s*\(", _LIB_SRC)
+ assert mine and all(n.startswith("astraRoad") for n in mine), mine
+
+
+def test_an_option_is_a_uniform_and_never_baked_into_the_source():
+ """three caches programs by key and the FIRST material to compile a key
+ decides the GLSL every material sharing it gets. Two materials that
+ differ only in options must therefore compile to the same source, or the
+ second silently wears the first's road — one lane width, one gutter, one
+ seam colour and one track kind imposed on every other surface."""
+ out = _probe("""
+const a = std();
+patchRoadSurface(a, { aggregate: 0.25, wear: 0.5, seed: 1 });
+patchSeamBand(a, { width: 0.5, seed: 1 });
+patchTracks(a, { count: 2, seed: 1 });
+const b = std();
+patchRoadSurface(b, { aggregate: 1, wear: 0.05, patches: 0.9, gutter: 1,
+ color: 0x112233, lane: 6.2, halfWidth: 9,
+ dir: [1, 0, 0], center: [4, 0, 2], seed: 99 });
+patchSeamBand(b, { width: 2.5, weeds: 1, color: 0x445566, seed: 99 });
+patchTracks(b, { count: 5, depth: 1, kind: 'foot', gauge: 0.44,
+ offset: -3.1, seed: 99 });
+const sa = compile(a), sb = compile(b);
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ sameKey: a.customProgramCacheKey() === b.customProgramCacheKey(),
+ sameVs: sa.vertexShader === sb.vertexShader,
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ aRoad: [u(a).uRoadAgg.value, u(a).uRoadWear.value, u(a).uRoadLane.value,
+ u(a).uRoadHalf.value, u(a).uRoadCenter.value.toArray()],
+ bRoad: [u(b).uRoadAgg.value, u(b).uRoadWear.value, u(b).uRoadLane.value,
+ u(b).uRoadHalf.value, u(b).uRoadCenter.value.toArray()],
+ bSeam: [u(b).uSeamWidth.value, u(b).uSeamWeeds.value],
+ bTrk: [u(b).uTrkCount.value, u(b).uTrkDepth.value, u(b).uTrkKind.value,
+ u(b).uTrkGauge.value, u(b).uTrkOffset.value],
+ colors: [u(b).uRoadColor.value.getHex(), u(b).uSeamColor.value.getHex()],
+ clamped: [(() => { const m = std();
+ patchRoadSurface(m, { wear: 4, gutter: -2 });
+ return [m.userData.uniforms.uRoadWear.value,
+ m.userData.uniforms.uRoadGutter.value]; })()],
+}));
+""")
+ assert out["sameKey"] and out["sameVs"] and out["sameFs"]
+ assert out["aRoad"] == [0.25, 0.5, 3.4, 3.5, [0, 0, 0, 0]]
+ # The centreline carries an ENABLE in its w, so "the mesh's own origin"
+ # needs no second uniform and no second program.
+ assert out["bRoad"] == [1, 0.05, 6.2, 9, [4, 0, 2, 1]]
+ assert out["bSeam"] == [2.5, 1]
+ assert out["bTrk"] == [5, 1, 1, 0.44, -3.1]
+ assert out["colors"] == [0x112233, 0x445566]
+ assert out["clamped"] == [[1, 0]], "an option out of range must clamp"
+
+
+def test_the_frame_is_the_roads_and_an_omitted_option_inherits_it():
+ """`dir`, `halfWidth` and `center` describe the ROAD, not one patch, so a
+ seam band applied after a road surface must not silently reset the road to
+ a 3.5 m default along +Z, which would move the ruts, the gutter and the
+ band all at once."""
+ out = _probe("""
+const m = std();
+patchRoadSurface(m, { halfWidth: 2.4, dir: [1, 0, 0], center: [3, 0, 0] });
+const after = () => [m.userData.uniforms.uRoadHalf.value,
+ m.userData.uniforms.uRoadDir.value.toArray(),
+ m.userData.uniforms.uRoadCenter.value.toArray()];
+const first = after();
+patchSeamBand(m, { width: 0.6 });
+const inherited = after();
+patchTracks(m, { count: 2, halfWidth: 8 });
+const overridden = after();
+console.log(JSON.stringify({ first, inherited, overridden,
+ frames: m.userData.astraPatches.filter((p) => p.name === 'road:frame').length,
+ names: m.userData.astraPatches.map((p) => p.name),
+}));
+""")
+ assert out["first"] == [2.4, [1, 0, 0], [3, 0, 0, 1]]
+ assert out["inherited"] == out["first"], "the seam band reset the road"
+ assert out["overridden"][0] == 8, "a stated option must win"
+ assert out["overridden"][1] == [1, 0, 0], "and only that option moves"
+ assert out["frames"] == 1, "the frame must be applied once"
+ assert out["names"] == ["road:frame", "road:surface", "road:seam",
+ "road:tracks"]
+
+
+def test_a_made_road_is_never_polished_into_a_sky_mirror():
+ """THE PORT'S OWN LAW. `fragmentBody` lands after <color_fragment> and
+ therefore before <roughnessmap_fragment> declares roughnessFactor, so the
+ one gloss move here is the MATERIAL's — which makes it the area-weighted
+ average of the surface, not the polished rut's own value. Wheel strips
+ cover about a quarter of a lane and the gutter a twelfth of the width.
+
+ Our renderer has no post chain, takes its specular from a bright sky
+ environment, and shows a road at a grazing angle where a smooth dielectric
+ is almost all Fresnel: measured on the showcase host 2026-09-01, tarmac
+ authored at 0.85 and composed down to 0.63 by the reference's factors read
+ (171,172,175) — a white card with every mark washed off it — where the
+ same albedo at 0.86 reads (136,138,144). So the bound is on the FACTOR: a
+ fully worn, fully wet road may not lose more than a sixth of the roughness
+ it was authored with, and a track may not lose more than a tenth."""
+ out = _probe("""
+const worn = std({ roughness: 0.8 });
+patchRoadSurface(worn, { wear: 1, gutter: 1, aggregate: 0 });
+const wornR = worn.roughness;
+patchRoadSurface(worn, { wear: 1, gutter: 1, aggregate: 0 });
+const twice = worn.roughness;
+const gravel = std({ roughness: 0.8 });
+patchRoadSurface(gravel, { wear: 0, gutter: 0, aggregate: 1 });
+const seam = std({ roughness: 0.8 });
+patchSeamBand(seam, { weeds: 1 });
+const rutted = std({ roughness: 0.8 });
+patchTracks(rutted, { depth: 1 });
+const all = std({ roughness: 0.8 });
+patchRoadSurface(all, { wear: 1, gutter: 1 });
+patchSeamBand(all);
+patchTracks(all, { depth: 1 });
+const rough = std({ roughness: 0.98 });
+patchSeamBand(rough, { weeds: 1 });
+const basic = new THREE.MeshBasicMaterial({ color: 0x445566 });
+patchRoadSurface(basic);
+patchSeamBand(basic);
+patchTracks(basic);
+console.log(JSON.stringify({
+ wornR, twice, gravel: gravel.roughness, seam: seam.roughness,
+ rutted: rutted.roughness, all: all.roughness, rough: rough.roughness,
+ base: all.userData.astraRoughness.base,
+ factors: all.userData.astraRoughness.factors,
+ basicRough: basic.roughness === undefined,
+ basicPatched: basic.userData.astraPatches.map((p) => p.name),
+}));
+""")
+ assert out["base"] == 0.8, "the authored value is the one to compose on"
+ assert sorted(out["factors"]) == ["road:seam", "road:surface",
+ "road:tracks"]
+ # A polished, wet road is glossier than the mix it was laid from; a loose
+ # gravel one is matter; a pressed track packs smooth.
+ assert out["wornR"] < 0.8, out["wornR"]
+ assert out["gravel"] > 0.8, out["gravel"]
+ assert out["seam"] > 0.8 and out["rutted"] < 0.8
+ assert out["twice"] == out["wornR"], "re-applying compounded the gloss"
+ # THE BOUND, on the worst case each patch can be asked for.
+ assert out["factors"]["road:surface"] >= 0.84, out["factors"]
+ assert out["factors"]["road:tracks"] >= 0.90, out["factors"]
+ # One factor each, so the material is exactly their product.
+ product = 0.8
+ for f in out["factors"].values():
+ product *= f
+ assert abs(out["all"] - product) < 1e-9, (out["all"], product)
+ assert out["all"] < 0.8, "three factors, one product, still a road"
+ # Roughness only means anything up to 1, and a matte patch on an already
+ # rough material must not run off the top of the range.
+ assert 0.9 <= out["rough"] <= 1.0, out["rough"]
+ # A material with no roughness at all still takes the albedo patch.
+ assert out["basicRough"]
+ assert out["basicPatched"] == ["road:frame", "road:surface", "road:seam",
+ "road:tracks"]
+
+
+def test_the_road_keeps_a_colour_after_its_grain_has_faded_out():
+ """The other half of the port. Every fine field on this surface is
+ faded out by its own pixel size a few metres from the camera — which is
+ right, and left the carriageway ONE flat value past that: a grey card with
+ a repair grid on it, at exactly the distance most of the road lives. So
+ the road also carries a metre-scale field, in its own (along, across)
+ frame so it turns with the road, and that field moves the HUE as well as
+ the level — warm dust and bleached binder against cool fresh bitumen — for
+ the variance the brief asks for inside every effect. The tint mix is
+ centred on neutral, so a road still renders the tone it was given, and a
+ sub-LSB dither rides it because a smooth gradient over a near-neutral grey
+ bands at eight bits once the grain that hid it has gone."""
+ out = _probe("""
+const m = std();
+patchRoadSurface(m, { aggregate: 0.3 });
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ body = _main_body(out["fs"])
+ # In the ROAD's frame, not the world's, and slow enough to survive: the
+ # two octaves are ~9 m and ~29 m cycles.
+ _find(r"vec2 roMq = vec2\(roU, vAstraRoad\.w\) \+ uRoadSeed\.yx;", body)
+ blot = _find(r"float roBlot = \(astraNoise2\(roMq \* ([\d.]+)\) - 0\.5\)"
+ r" \* ([\d.]+)\s*\+ \(astraNoise2\(roMq \* ([\d.]+)"
+ r" \+ [\d.]+\) - 0\.5\) \* ([\d.]+);", body)
+ for freq in (float(blot.group(1)), float(blot.group(3))):
+ assert 0.02 <= freq <= 0.2, f"1/{freq} m is not a metre-scale cycle"
+ # A hue that walks WITH the field, and a mix centred on neutral so the
+ # road's mean tone is still the one it was given.
+ tint = _find(r"\* mix\(vec3\((0\.9\d+), (0\.9\d+), (1\.0\d+)\),\s*"
+ r"vec3\((1\.0\d+), (1\.0\d+), (0\.9\d+)\), roHue\);", body)
+ cool = [float(tint.group(i)) for i in (1, 2, 3)]
+ warm = [float(tint.group(i)) for i in (4, 5, 6)]
+ for c, w in zip(cool, warm, strict=True):
+ assert abs((c + w) / 2 - 1.0) < 0.02, (cool, warm)
+ assert cool[2] > cool[0] and warm[0] > warm[2], "the hue must actually turn"
+ _find(r"float roHue = clamp\(0\.5 \+ roBlot \* [\d.]+, 0\.0, 1\.0\);",
+ body)
+ # The dither is sub-LSB at 8 bits (1/255 = 0.0039 of a mid grey) and per
+ # pixel, so it breaks a band without reading as noise.
+ dither = _find(r"roCol \*= 1\.0 \+ \(astraHash21\(gl_FragCoord\.xy\)"
+ r" - 0\.5\) \* ([\d.]+);", body)
+ assert 0.004 <= float(dither.group(1)) <= 0.02, dither.group(1)
+ # The aggregate is stone, and a road is not mixed from one stone.
+ _find(r"roStone \*= mix\(vec3\([\d.]+, [\d.]+, [\d.]+\),\s*"
+ r"vec3\([\d.]+, [\d.]+, [\d.]+\), roG2\);", body)
+ # The gutter is two bands: a cool damp strip, and the silt washed to the
+ # kerb line ON TOP of it, in patches along the road — a flat pale line at
+ # the kerb is road marking, not dirt.
+ _find(r"float roSilt = smoothstep\(uRoadHalf - roGw \* [\d.]+ \+ roGj,"
+ r"\s*uRoadHalf \+ roGj, roA\) \* uRoadGutter\s*"
+ r"\* smoothstep\([\d.]+, [\d.]+,\s*astraNoise2\(", body)
+ _find(r"roCol = mix\(roCol, roCol \* vec3\([\d.]+, [\d.]+, [\d.]+\),\s*"
+ r"roGut \* \(1\.0 - roSilt \* [\d.]+\)\);", body)
+ # And the seam's gravel and weeds carry a hue spread of their own.
+ seam = _probe("""
+const m = std();
+patchSeamBand(m, { weeds: 0.6 });
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ sbody = _main_body(seam["fs"])
+ _find(r"float smHue = astraNoise2\(vec2\(smU, vAstraRoad\.w\)"
+ r" \* [\d.]+\s*\+ uSeamSeed\.zx\);", sbody)
+ _find(r"smCol \*= mix\(vec3\([\d.]+, [\d.]+, [\d.]+\),"
+ r" vec3\([\d.]+, [\d.]+, [\d.]+\), smHue\);", sbody)
+ _find(r"vec3 smWc = uSeamWeed \* mix\([\d.]+, [\d.]+, smG\)\s*"
+ r"\* mix\(vec3\([\d.]+, [\d.]+, [\d.]+\),\s*"
+ r"vec3\([\d.]+, [\d.]+, [\d.]+\), smHue\);", sbody)
+
+
+def test_one_seed_lays_the_same_road_every_time():
+ """A render is re-run — for a fix round, for a video, for the judge — and
+ the repairs must not move between takes. The seed reaches the GPU only as
+ a noise-space OFFSET (a uniform, because baking it would hand material
+ one's seed to every material sharing the key), the three patches are
+ decorrelated from each other, and all three differ from surface_wear's,
+ aging's and accumulation's for the same seed."""
+ out = _probe("""
+const mk = (seed) => {
+ const m = std();
+ patchRoadSurface(m, { seed });
+ patchSeamBand(m, { seed });
+ patchTracks(m, { seed });
+ patchMicroBreakup(m, { seed });
+ patchDust(m, { seed });
+ patchSnow(m, { seed });
+ return m;
+};
+const a = mk(7), b = mk(7), c = mk(8);
+const u = (m, n) => m.userData.uniforms[n].value.toArray();
+console.log(JSON.stringify({
+ aRoad: u(a, 'uRoadSeed'), bRoad: u(b, 'uRoadSeed'), cRoad: u(c, 'uRoadSeed'),
+ aSeam: u(a, 'uSeamSeed'), cSeam: u(c, 'uSeamSeed'),
+ aTrk: u(a, 'uTrkSeed'), cTrk: u(c, 'uTrkSeed'),
+ aMicro: u(a, 'uMicroSeed'), aDust: u(a, 'uDustSeed'),
+ aSnow: u(a, 'uSnowSeed'),
+ sameSrc: compile(a).fragmentShader === compile(c).fragmentShader,
+}));
+""")
+ assert out["aRoad"] == out["bRoad"], "the same seed moved the repairs"
+ assert out["aRoad"] != out["cRoad"] and out["aSeam"] != out["cSeam"]
+ assert out["aTrk"] != out["cTrk"]
+ assert len({tuple(out[k]) for k in ("aRoad", "aSeam", "aTrk")}) == 3
+ for other in ("aMicro", "aDust", "aSnow"):
+ assert out["aRoad"] != out[other] and out["aSeam"] != out[other]
+ assert out["aTrk"] != out[other]
+ assert all(0 <= v <= 40 for v in out["aRoad"] + out["aTrk"])
+ assert out["sameSrc"], "the seed is a uniform, not source"
+ assert "Math.random" not in _LIB_SRC
+
+
+def test_every_fine_field_dies_before_it_can_alias():
+ """Detail that reads at three metres and turns to a shimmering mess at
+ forty is worse than no detail: it is the one way a surface reads as an
+ EFFECT rather than as a surface, and it moves with the camera. Every
+ field here finer than the pixel that will read it is therefore faded by
+ the WORLD size of that pixel, and what remains converges to the average
+ tone rather than to nothing."""
+ out = _probe("""
+const m = std();
+patchRoadSurface(m, { aggregate: 0.5 });
+patchSeamBand(m);
+patchTracks(m, { kind: 'foot' });
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ body = _main_body(fs)
+ _find(r"float astraRoadFade\(vec3 p, float cycle\) \{\s*"
+ r"return 1\.0 - smoothstep\(([\d.]+), ([\d.]+),\s*"
+ r"length\(fwidth\(p\)\) / max\(cycle, 1e-4\)\);", fs)
+ _find(r"float roGs = mix\([\d.]+, [\d.]+, uRoadAgg\);", body)
+ _find(r"float roFd = astraRoadFade\(vAstraWorld, roGs\)"
+ r" \* \(1\.0 - roRut \* [\d.]+\);", body)
+ assert "roGrain" in body and "* roFd;" in body
+ # The third, finest octave of the aggregate rides roFd TWICE, so it is the
+ # first thing to go: two octaves at one stone size read as soft blobs.
+ _find(r"\+ \(roG3 - 0\.5\) \* [\d.]+ \* roFd\) \* roFd;", body)
+ # The seam's two fields converge to their AVERAGE, not to nothing.
+ _find(r"float smFd = astraRoadFade\(vAstraWorld, [\d.]+\);", body)
+ _find(r"float smFc = astraRoadFade\(vAstraWorld, [\d.]+\);", body)
+ _find(r"vec3 smCol = uSeamColor \* mix\(1\.0, mix\([\d.]+, [\d.]+, smC\),"
+ r" smFc\)\s*\* \(1\.0 \+ \(smG - 0\.5\) \* [\d.]+ \* smFd\);", body)
+ _find(r"float smWd = mix\([\d.]+, smoothstep\([\d.]+, [\d.]+, smTf\),"
+ r" smFc\)", body)
+ # The tracks: the rim and the tread go with the fade, and the prints
+ # become the trail.
+ _find(r"float tkRim = clamp\(tkWide - tkPress, 0\.0, 1\.0\) \* tkFd;",
+ body)
+ _find(r"\* \(1\.0 - tkTread \* [\d.]+ \* tkFd\);", body)
+ # Every fade argument is a real feature size in metres, not a magic
+ # screen-space number.
+ for cycle in re.findall(r"astraRoadFade\(vAstraWorld, ([\d.]+)\)", body):
+ assert 0.01 <= float(cycle) <= 1.0, cycle
diff --git a/harness/tests/scene_runtime/lib/test_scatter.py b/harness/tests/scene_runtime/lib/test_scatter.py
new file mode 100644
index 00000000..677b0e66
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_scatter.py
@@ -0,0 +1,405 @@
+"""scatter.js: instances ON the surface, exact count, deterministic, GRADED.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_scatter_lib.py). Their scaffolding is dropped; the placement
+claims are kept verbatim in spirit — MeshSurfaceSampler's two traps
+(LOCAL-space samples used raw, and its `Math.random` default) plus slope
+gating on TRUE face normals rather than the smoothed vertex normals that
+under-report a slope.
+
+What this port ADDED, and the reason each assertion exists:
+
+`colorJitter` shipped as `setScalar(1 - colorJitter * rand())` — a
+one-sided GREY multiplier. Measured on 600 instances of a 0x537a36
+tuft at colorJitter 0.45: mean multiplier 0.7783 (the authored albedo
+was silently 22 % darker than the colour the author picked, and the
+field's mean is never recoverable by choosing a brighter one, because
+the bias scales with the jitter) and hue spread 0.000 degrees across
+the whole field. A thousand copies varying only in brightness is the
+wallpaper read the option exists to break. So the multiplier is now
+CENTRED on the authored albedo and carries a warm/cool hue axis, and
+the three properties that keeps it honest are pinned here:
+
+ * centred — the field mean returns the colour that was authored;
+ * hue actually moves, and the axis is capped by the albedo's own
+ chroma: a near-neutral colour has no hue to nudge, so an unbounded
+ push INVENTS one and a grey field comes back half orange and half
+ blue (measured on 0x808080 at full jitter: peak saturation 0.888
+ with the cap removed, 0.113 with it);
+ * the product stays inside the scene contract's 0.02..0.82 albedo
+ band at any jitter, so a pale prototype cannot blow out under ACES
+ and a dark one cannot punch a black hole in the field.
+
+And one workflow law: colour must not move the FIELD. Hue rides its
+own PRNG stream and the value draw is taken whether or not it is used,
+so turning colorJitter on to break a wallpaper read cannot also re-roll
+every position out from under a layout that was already approved.
+
+`alignToNormal` also takes a NUMBER now: real grass on a bank leans
+downhill without lying flat on it, and true/false still mean 1/0.
+"""
+
+from __future__ import annotations
+
+import pytest
+from _probe import measure
+
+pytestmark = pytest.mark.node
+
+
+def _measure(script: str) -> dict:
+ return measure(script, ("scatter.js",))
+
+
+_PLACEMENT = """
+import * as THREE from 'three';
+import { displaceY } from './lib/noise.js';
+import { scatter } from './lib/scatter.js';
+
+const makeTerrain = () => {
+ const g = new THREE.PlaneGeometry(160, 160, 96, 96);
+ g.rotateX(-Math.PI / 2);
+ displaceY(g, 12, 0.03, 7);
+ return new THREE.Mesh(g, new THREE.MeshStandardMaterial());
+};
+
+// Terrain nested in a transformed parent: scatter must bake the FULL
+// world transform, not hand back local-space sample points.
+const setup = () => {
+ const terrain = makeTerrain();
+ terrain.position.set(40, 5, -20);
+ terrain.rotation.y = 0.4;
+ const parent = new THREE.Group();
+ parent.position.set(-10, 2, 3);
+ parent.add(terrain);
+ new THREE.Group().add(parent);
+ parent.parent.updateMatrixWorld(true);
+ return terrain;
+};
+
+const cone = new THREE.ConeGeometry(0.3, 1.2, 6);
+cone.translate(0, 0.6, 0);
+const mat = new THREE.MeshStandardMaterial();
+
+const t1 = setup();
+const im = scatter(t1, cone, mat, 300, { seed: 11 });
+const countExact = im.count === 300 && im.isInstancedMesh === true;
+
+// On-surface: the vertical ray through each instance origin must hit
+// the terrain at the origin's own height.
+const ray = new THREE.Raycaster();
+const down = new THREE.Vector3(0, -1, 0);
+const p = new THREE.Vector3();
+const q = new THREE.Quaternion();
+const s = new THREE.Vector3();
+const M = new THREE.Matrix4();
+let maxGap = 0;
+let sMin = 1e9, sMax = -1e9, nonUniform = 0;
+for (let i = 0; i < im.count; i++) {
+ im.getMatrixAt(i, M);
+ M.decompose(p, q, s);
+ ray.set(new THREE.Vector3(p.x, p.y + 80, p.z), down);
+ const hits = ray.intersectObject(t1, false);
+ if (!hits.length) { maxGap = 1e9; break; }
+ maxGap = Math.max(maxGap, Math.abs(hits[0].point.y - p.y));
+ sMin = Math.min(sMin, s.x);
+ sMax = Math.max(sMax, s.x);
+ if (Math.abs(s.x - s.y) > 1e-6 || Math.abs(s.x - s.z) > 1e-6) nonUniform++;
+}
+
+// Determinism: fresh identical setup, same seed -> identical matrices;
+// different seed -> a different field.
+const im2 = scatter(setup(), cone, mat, 300, { seed: 11 });
+const im3 = scatter(setup(), cone, mat, 300, { seed: 12 });
+let maxSame = 0, maxOther = 0;
+const a1 = im.instanceMatrix.array, a2 = im2.instanceMatrix.array,
+ a3 = im3.instanceMatrix.array;
+for (let i = 0; i < a1.length; i++) {
+ maxSame = Math.max(maxSame, Math.abs(a1[i] - a2[i]));
+ maxOther = Math.max(maxOther, Math.abs(a1[i] - a3[i]));
+}
+
+// Colour must not move the FIELD: same seed, jitter off vs on.
+const imPlain = scatter(setup(), cone, mat, 300, { seed: 11 });
+const imTinted = scatter(setup(), cone, mat, 300,
+ { seed: 11, colorJitter: 0.6 });
+let maxShift = 0;
+const b1 = imPlain.instanceMatrix.array, b2 = imTinted.instanceMatrix.array;
+for (let i = 0; i < b1.length; i++) {
+ maxShift = Math.max(maxShift, Math.abs(b1[i] - b2[i]));
+}
+
+// alignToNormal on a tilted plane: instance +Y must match the plane's
+// world normal; without the flag it must stay world-up despite the
+// tilt; a NUMBER must land part way between the two.
+const TILT = 0.5;
+const tilt = () => {
+ const g = new THREE.PlaneGeometry(40, 40, 4, 4);
+ g.rotateX(-Math.PI / 2);
+ const mSlope = new THREE.Mesh(g, new THREE.MeshStandardMaterial());
+ mSlope.rotation.z = TILT;
+ mSlope.updateMatrixWorld(true);
+ return mSlope;
+};
+const expectN = new THREE.Vector3(0, 1, 0).applyEuler(tilt().rotation);
+const imA = scatter(tilt(), cone, mat, 60, { alignToNormal: true, seed: 2 });
+const imU = scatter(tilt(), cone, mat, 60, { seed: 2 });
+const imH = scatter(tilt(), cone, mat, 60, { alignToNormal: 0.5, seed: 2 });
+const basisY = new THREE.Vector3();
+let minDotAligned = 1, minDotUpright = 1;
+let halfMin = Math.PI, halfMax = -Math.PI;
+for (let i = 0; i < 60; i++) {
+ imA.getMatrixAt(i, M);
+ basisY.setFromMatrixColumn(M, 1).normalize();
+ minDotAligned = Math.min(minDotAligned, basisY.dot(expectN));
+ imU.getMatrixAt(i, M);
+ basisY.setFromMatrixColumn(M, 1).normalize();
+ minDotUpright = Math.min(minDotUpright, basisY.y);
+ imH.getMatrixAt(i, M);
+ basisY.setFromMatrixColumn(M, 1).normalize();
+ const ang = Math.acos(Math.min(1, basisY.y)); // lean from world up
+ halfMin = Math.min(halfMin, ang);
+ halfMax = Math.max(halfMax, ang);
+}
+
+// maxSlopeDeg against MEASURED face normals on steep fBm terrain
+// (identity transform so raycast face normals are world-space).
+const steepG = new THREE.PlaneGeometry(160, 160, 96, 96);
+steepG.rotateX(-Math.PI / 2);
+displaceY(steepG, 26, 0.05, 7);
+const steepT = new THREE.Mesh(steepG, new THREE.MeshStandardMaterial());
+steepT.updateMatrixWorld(true);
+const measureMinNy = (mesh) => {
+ let minNy = 1;
+ for (let i = 0; i < mesh.count; i++) {
+ mesh.getMatrixAt(i, M);
+ M.decompose(p, q, s);
+ ray.set(new THREE.Vector3(p.x, p.y + 80, p.z), down);
+ const hits = ray.intersectObject(steepT, false);
+ if (!hits.length) return -1;
+ minNy = Math.min(minNy, hits[0].face.normal.y);
+ }
+ return minNy;
+};
+const imAll = scatter(steepT, cone, mat, 400, { seed: 5 });
+const imFlat = scatter(steepT, cone, mat, 400, { seed: 5, maxSlopeDeg: 25 });
+
+// Cap, zero jitter.
+const imCap = scatter(makeTerrain(), cone, mat, 5000, { seed: 1 });
+const imCap2 = scatter(makeTerrain(), cone, mat, 5000,
+ { seed: 1, maxCount: 50 });
+const imRigid = scatter(makeTerrain(), cone, mat, 20,
+ { seed: 1, scaleJitter: 0 });
+let rigidOk = true;
+for (let i = 0; i < 20; i++) {
+ imRigid.getMatrixAt(i, M);
+ M.decompose(p, q, s);
+ if (Math.abs(s.x - 1) > 1e-6) rigidOk = false;
+}
+
+console.log(JSON.stringify({
+ countExact, maxGap, sMin, sMax, nonUniform,
+ maxSame, maxOther, maxShift,
+ minDotAligned, minDotUpright,
+ halfMinDeg: halfMin * 180 / Math.PI, halfMaxDeg: halfMax * 180 / Math.PI,
+ tiltDeg: TILT * 180 / Math.PI,
+ minNyAll: measureMinNy(imAll), minNyFlat: measureMinNy(imFlat),
+ flatCount: imFlat.count,
+ capCount: imCap.count, cap2Count: imCap2.count, rigidOk,
+ cos25: Math.cos(25 * Math.PI / 180),
+}));
+"""
+
+
+_GRADE = """
+import * as THREE from 'three';
+import { scatter } from './lib/scatter.js';
+
+const g = new THREE.PlaneGeometry(80, 80, 24, 24);
+g.rotateX(-Math.PI / 2);
+const surf = new THREE.Mesh(g, new THREE.MeshStandardMaterial());
+surf.updateMatrixWorld(true);
+const proto = new THREE.ConeGeometry(0.2, 0.5, 5);
+proto.translate(0, 0.25, 0);
+
+const N = 600;
+const circStd = (hs) => {
+ const c = hs.reduce((s, h) => s + Math.cos(h), 0) / hs.length;
+ const s = hs.reduce((s2, h) => s2 + Math.sin(h), 0) / hs.length;
+ const R = Math.max(Math.hypot(c, s), 1e-9);
+ return Math.sqrt(-2 * Math.log(R)) * 180 / Math.PI;
+};
+
+// `hex` is a hue-carrying albedo (foliage) or a near-neutral one (stone).
+const field = (hex, jitter, opts = {}) => {
+ const mat = new THREE.MeshStandardMaterial({ color: hex });
+ const im = scatter(surf, proto, mat, N, Object.assign(
+ { seed: 3, colorJitter: jitter }, opts));
+ if (!im.instanceColor) return { hasTint: false };
+ const a = im.instanceColor.array, col = new THREE.Color(), hsl = {};
+ const hs = [];
+ let lumSum = 0, peak = 0, floor = 1e9, satMax = 0;
+ for (let i = 0; i < N; i++) {
+ const R = a[i * 3] * mat.color.r;
+ const G = a[i * 3 + 1] * mat.color.g;
+ const B = a[i * 3 + 2] * mat.color.b;
+ col.setRGB(R, G, B);
+ col.getHSL(hsl);
+ hs.push(hsl.h * Math.PI * 2);
+ satMax = Math.max(satMax, (Math.max(R, G, B) - Math.min(R, G, B))
+ / Math.max(Math.max(R, G, B), 1e-9));
+ lumSum += 0.2126 * R + 0.7152 * G + 0.0722 * B;
+ peak = Math.max(peak, R, G, B);
+ floor = Math.min(floor, Math.max(R, G, B));
+ }
+ const baseLum = 0.2126 * mat.color.r + 0.7152 * mat.color.g
+ + 0.0722 * mat.color.b;
+ return {
+ hasTint: true,
+ lumRatio: (lumSum / N) / baseLum, // 1.0 == the authored albedo
+ hueStd: circStd(hs),
+ satMax, peak, floor,
+ };
+};
+
+console.log(JSON.stringify({
+ leaf: field(0x537a36, 0.45),
+ stone: field(0x7d786f, 0.45),
+ leafNoHue: field(0x537a36, 0.45, { hueJitter: 0 }),
+ // extremes: the albedo band must hold at the loudest legal jitter,
+ // and a flat grey at full jitter must not invent a hue wheel
+ pale: field(0xf2f2f2, 1.0),
+ dark: field(0x0a0a0a, 1.0),
+ greyLoud: field(0x808080, 1.0),
+ off: field(0x537a36, 0),
+}));
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch of the placement probe, shared by its tests."""
+ return _measure(_PLACEMENT)
+
+
[email protected](scope="module")
+def grade() -> dict:
+ """One node launch of the colour-grading probe."""
+ return _measure(_GRADE)
+
+
+def test_instances_sit_on_the_surface_in_world_space(probe):
+ """Every instance origin lies ON the surface even under a
+ transformed parent — raw sampler points are LOCAL-space, and used
+ raw they are the floating/buried cover the census red-flags."""
+ assert probe["countExact"], "count wrong or not an InstancedMesh"
+ assert probe["maxGap"] < 1e-3, f"instances off the surface: {probe['maxGap']}"
+
+
+def test_same_seed_is_bit_identical_and_seed_moves_the_field(probe):
+ """Same seed must reproduce exact matrices (fix rounds re-render
+ untouched zones pixel-identically; Math.random would break this
+ silently) — and a different seed must actually move instances."""
+ assert probe["maxSame"] == 0, f"same seed diverged by {probe['maxSame']}"
+ assert probe["maxOther"] > 1, f"seed changes nothing: {probe['maxOther']}"
+
+
+def test_colour_jitter_does_not_move_the_field(probe):
+ """Grading is not layout. Turning colorJitter on to break a
+ wallpaper read must leave every matrix bit-identical, or every
+ colour tweak silently re-rolls a field that was already approved."""
+ assert probe["maxShift"] == 0, (
+ f"colorJitter moved the instances by {probe['maxShift']}")
+
+
+def test_align_to_normal_tilts_leans_or_stays_upright(probe):
+ """alignToNormal:true lays grass/rocks onto the slope; the default
+ keeps trees/posts world-vertical (each mode's +Y exposes the other's
+ failure). A NUMBER leans part way — 0.5 on a 28.6 deg bank must
+ land near half of it, not at either end."""
+ m = probe
+ assert m["minDotAligned"] > 0.999, f"not aligned: {m['minDotAligned']}"
+ assert m["minDotUpright"] > 0.999, f"not upright: {m['minDotUpright']}"
+ half = m["tiltDeg"] * 0.5
+ assert abs(m["halfMinDeg"] - half) < 1.0, m
+ assert abs(m["halfMaxDeg"] - half) < 1.0, m
+
+
+def test_max_slope_deg_gates_on_true_face_normals(probe):
+ """maxSlopeDeg must gate on the TRUE face normal: interpolated
+ vertex normals let 60-degree faces through a 25-degree filter (the
+ measured bug this pins)."""
+ m = probe
+ assert m["minNyAll"] < 0.5, f"terrain not steep, test is void: {m}"
+ assert m["minNyFlat"] >= m["cos25"] - 1e-3, (
+ f"steep faces passed the filter: {m['minNyFlat']}")
+ assert m["flatCount"] >= 350, f"rejection starved: {m['flatCount']}"
+
+
+def test_count_cap_and_scale_jitter(probe):
+ """The overdraw cap (1000 default, the one measured scatter
+ footgun) must clamp, maxCount must override it, scaleJitter must
+ spread uniformly inside 1 +- jitter and 0 must mean rigid."""
+ m = probe
+ assert m["capCount"] == 1000, f"default cap: {m['capCount']}"
+ assert m["cap2Count"] == 50, f"maxCount override: {m['cap2Count']}"
+ assert m["sMin"] >= 0.699 and m["sMax"] <= 1.301, m
+ assert m["sMax"] - m["sMin"] > 0.3, f"no scale spread: {m}"
+ assert m["nonUniform"] == 0, "scale jitter is non-uniform"
+ assert m["rigidOk"], "scaleJitter 0 still scaled"
+
+
+def test_colour_jitter_is_centred_on_the_authored_albedo(grade):
+ """The shipped `1 - colorJitter * rand()` could only darken: at
+ jitter 0.45 the field's mean luminance measured 0.778 of the colour
+ the author picked, and the bias grows with the jitter. A field's
+ mean must BE the authored albedo."""
+ for name in ("leaf", "stone", "leafNoHue"):
+ assert grade[name]["hasTint"], f"{name}: no instanceColor written"
+ assert abs(grade[name]["lumRatio"] - 1.0) < 0.03, (
+ f"{name} field mean is {grade[name]['lumRatio']:.3f} of the "
+ "authored albedo")
+ assert not grade["off"]["hasTint"], "colorJitter 0 still wrote colours"
+
+
+def test_colour_jitter_varies_hue_not_only_brightness(grade):
+ """Measured on the shipped version: 0.000 degrees of hue across 600
+ copies. A thousand leaves at one hue IS the wallpaper read the
+ option exists to break, so the axis must actually move."""
+ assert grade["leaf"]["hueStd"] > 3.5, (
+ f"foliage hue is flat: {grade['leaf']['hueStd']:.3f} deg")
+ assert grade["stone"]["hueStd"] > 1.0, (
+ f"stone hue is flat: {grade['stone']['hueStd']:.3f} deg")
+ assert grade["leafNoHue"]["hueStd"] < 0.01, (
+ f"hueJitter 0 still moved hue: {grade['leafNoHue']['hueStd']}")
+
+
+def test_hue_axis_is_capped_by_the_albedos_own_saturation(grade):
+ """A near-neutral albedo has no hue to nudge — the axis INVENTS one,
+ and hue angle stops meaning anything (a pure grey at full jitter
+ measures 193 deg of hue spread while being, correctly, still grey).
+ So the guard is on CHROMA: whatever the jitter, a grey prototype may
+ come back a warm or cool grey, never an orange one."""
+ assert grade["greyLoud"]["satMax"] < 0.16, (
+ "flat grey at full jitter turned chromatic: peak saturation "
+ f"{grade['greyLoud']['satMax']:.3f}")
+ # 0x7d786f carries 0.225 of chroma; the warm tail measures 0.453,
+ # so the axis roughly doubles it at the extreme and no further.
+ assert grade["stone"]["satMax"] < 0.50, (
+ f"stone over-tinted: {grade['stone']['satMax']:.3f}")
+ assert grade["leaf"]["satMax"] > grade["stone"]["satMax"], (
+ "a saturated albedo must be allowed a WIDER axis than a neutral "
+ f"one: {grade['leaf']['satMax']:.3f} vs {grade['stone']['satMax']:.3f}")
+
+
+def test_jitter_holds_the_albedo_band_at_any_setting(grade):
+ """The scene contract's non-emissive band is 0.02..0.82. A pale
+ prototype at full jitter must not multiply past the ceiling (it
+ blows out under ACES before the sun lands on it) and a dark one
+ must not fall through the floor (a black hole in the field)."""
+ for name in ("leaf", "stone", "pale", "dark"):
+ assert grade[name]["peak"] <= 0.821, (
+ f"{name} peak albedo {grade[name]['peak']:.4f} over the ceiling")
+ assert grade[name]["floor"] >= 0.0199, (
+ f"{name} floor albedo {grade[name]['floor']:.4f} under the floor")
+ assert grade["pale"]["peak"] > 0.5, "pale test is void, nothing near the cap"
diff --git a/harness/tests/scene_runtime/lib/test_season.py b/harness/tests/scene_runtime/lib/test_season.py
new file mode 100644
index 00000000..0e5a17af
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_season.py
@@ -0,0 +1,382 @@
+"""season.js: the turn of the year, and the hour a scene is posed at.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_season_lib.py). Their renderer-contract assertions are dropped;
+the claims their JSDoc makes are kept — the spread is wider at the turn than
+in high summer, the tint BLENDS rather than assigns, season and kind are
+uniforms so one scene compiles one program, a low sun is warm and its fill is
+blue, the pose mutates nothing it was handed, and one seed turns the same
+canopy twice.
+
+THE PORT'S OWN LAWS, each one a defect this file exists to stop coming back:
+
+1. THE TURN MUST NOT GO FLAT ON A SHADER-BUILT CROWN. canopy.js and grass.js
+ draw a whole stand in one call and build every leaf card in the VERTEX
+ shader from instance attributes, so their ``position`` attribute is a
+ zeroed buffer. The reference celled the per-leaf random off exactly that
+ attribute: measured on our renderer 2026-09-01, a whole autumn crown came
+ back with a hue spread of 1.3 degrees — one sheet of chocolate, the single
+ failure the module's own doc says it exists to avoid. The grain now
+ carries a world fallback keyed on ``vAstraSeaD``, and an InstancedMesh
+ (which shares ONE geometry, so its model cell is the same card for every
+ copy) decorrelates on the instance.
+
+2. NOTHING MAY WRAP THE SMOOTH FIELD. For grass and ground the grain IS a
+ continuous world field; a ``fract`` anywhere downstream of it draws its own
+ sawtooth contour rings across the terrain — measured, six rings per unit of
+ field, a floor that read as plywood.
+
+3. THE PALETTE IS GRADED FOR THIS PIPELINE. Every anchor keeps a dielectric
+ floor in the channels it does not own (the reference's autumn red was
+ linear (0.274, 0.018, 0.005) — a red with no blue at all, whose shade side
+ could take nothing from the sky), and autumn's two anchors stay far enough
+ apart in hue to read as a PAIR rather than as one wash.
+
+4. THE LEVELS ARE OURS. environment.js measured this renderer (ACES,
+ exposure 1.0, no post chain) at day 5.4 key / 1.4 fill and night 2.2 / 1.0,
+ and sunRig clamps anything under 4.5 (day key) or 0.8 (night fill) UP. The
+ reference's pose asked for 3.3 at noon and 0.75 at night: every daylight
+ hour came back clamped to the same 4.5 — one flat key from breakfast to
+ dusk — and a posed night rendered at a third of the rig it replaced.
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "season.js")
+
+
+# The probe's stand-in for three's own compile: a fragment shader that owns a
+# `diffuseColor` the patch can land on, and a vertex shader that owns
+# `transformed`.
+_COMPILE = """
+const compiled = (o) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchSeasonTint(m, o);
+ const s = { uniforms: {},
+ vertexShader: 'void main() { #include <begin_vertex> }',
+ fragmentShader: '#include <color_fragment>' };
+ m.onBeforeCompile(s);
+ return { u: s.uniforms, vs: s.vertexShader, fs: s.fragmentShader,
+ key: m.customProgramCacheKey() };
+};
+"""
+
+
+def test_autumn_is_a_spread_of_hues_and_not_one_orange():
+ """A canopy turns unevenly — tree by tree and leaf by leaf — so the
+ claim is the SPREAD, not the mean. A single lerp toward one autumn
+ colour is the failure this library exists to avoid, and it is the one a
+ mean-only test would pass."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchSeasonTint } from './lib/season.js';
+""" + _COMPILE + """
+const autumn = compiled({ season: 0.5, kind: 'leaf' });
+const summer = compiled({ season: 0.25, kind: 'leaf' });
+console.log(JSON.stringify({
+ autumnSpread: autumn.u.uSeaSpread.value,
+ summerSpread: summer.u.uSeaSpread.value,
+ phase: autumn.u.uSeaPhase.value,
+ // the spread has to be carried per FRAGMENT, not just held per material
+ readsGrain: /uSeaGrain/.test(autumn.fs),
+ readsSeed: /uSeaSeed/.test(autumn.fs),
+}));
+""", _LIBS)
+ assert out["autumnSpread"] > out["summerSpread"] * 1.5, (
+ "autumn must vary more than summer, not merely differ in hue")
+ assert out["phase"] == 0.5
+ assert out["readsGrain"] and out["readsSeed"]
+
+
+def test_the_tint_blends_and_never_assigns_over_what_it_lands_on():
+ """A season tint lands on grass, leaves and ground that other patches have
+ already coloured, so it is the patch with the most to erase."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchSeasonTint } from './lib/season.js';
+""" + _COMPILE + """
+const c = compiled({});
+const body = c.fs.slice(c.fs.indexOf('#include <color_fragment>'));
+const writes = body.match(/diffuseColor\\.rgb\\s*=[^=]/g) || [];
+console.log(JSON.stringify({
+ writes: writes.length,
+ allBlend: writes.every(() =>
+ /diffuseColor\\.rgb\\s*=\\s*mix\\(\\s*diffuseColor\\.rgb/.test(body)
+ || /diffuseColor\\.rgb\\s*\\*=/.test(body)),
+ // and it must READ what was there, not only its brightness: an earlier
+ // patch's hue jitter is what keeps a crown from flattening to one colour
+ readsBaseHue: /uSeaKeep/.test(body),
+}));
+""", _LIBS)
+ assert out["writes"] >= 1
+ assert out["allBlend"], "a season tint must blend, not assign"
+ assert out["readsBaseHue"], (
+ "the turn must keep a share of the hue an earlier patch left here")
+
+
+def test_season_and_kind_are_uniforms_so_a_scene_shares_one_program():
+ """Four seasons on three kinds is twelve materials in one scene. If
+ either branched the SOURCE that is twelve programs, and the first material
+ to compile a cache key would decide the source for all of them."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchSeasonTint } from './lib/season.js';
+""" + _COMPILE + """
+const a = compiled({ season: 0.0, kind: 'leaf' });
+const b = compiled({ season: 0.75, kind: 'leaf' });
+const c = compiled({ season: 0.5, kind: 'grass' });
+console.log(JSON.stringify({
+ seasonSharesSource: a.fs === b.fs,
+ kindSharesSource: a.fs === c.fs,
+ oneKey: a.key === b.key && a.key === c.key,
+}));
+""", _LIBS)
+ assert out["seasonSharesSource"], "season must be a uniform"
+ assert out["kindSharesSource"], "kind must be a uniform"
+ assert out["oneKey"]
+
+
+def test_a_shader_built_crown_still_turns_unevenly():
+ """LAW 1. canopy.js ships `position` as a zeroed attribute, so the model
+ cell is one value for a whole draw call. The grain must fall back to the
+ world field there — and an InstancedMesh, which shares one geometry, must
+ decorrelate on the instance, or a stand of leaves picks one pigment and
+ only its DATE varies."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchSeasonTint } from './lib/season.js';
+""" + _COMPILE + """
+const c = compiled({ kind: 'leaf' });
+const grain = c.fs.slice(c.fs.indexOf('vec3 astraSeasonGrain()'));
+console.log(JSON.stringify({
+ // the flag is measured off the MODEL attribute, in the vertex stage
+ flagsDegenerate: /vAstraSeaD\\s*=[^;]*dot\\(\\s*position\\s*,\\s*position/
+ .test(c.vs),
+ // and it has to reach the field weight, not merely be declared
+ fallsBack: /vAstraSeaD/.test(grain.slice(0, grain.indexOf('return'))),
+ perInstance: /vAstraSeaI/.test(grain.slice(0, grain.indexOf('return'))),
+}));
+""", _LIBS)
+ assert out["flagsDegenerate"], (
+ "the vertex stage must flag an asset with no model position")
+ assert out["fallsBack"], (
+ "a crown whose leaves have no model position must fall back to the "
+ "world field, or its whole turn is one colour")
+ assert out["perInstance"], (
+ "an InstancedMesh shares one geometry: the pigment must decorrelate "
+ "on the instance")
+
+
+def test_nothing_wraps_the_smooth_world_field():
+ """LAW 2. For grass and ground the grain is a continuous field, and a
+ `fract` on anything derived from it draws contour rings across the whole
+ terrain. Only the hash cells (already discontinuous) and the date's own
+ ring position may wrap."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchSeasonTint } from './lib/season.js';
+""" + _COMPILE + """
+const c = compiled({ kind: 'ground' });
+const body = c.fs.slice(c.fs.indexOf('vec3 seG = astraSeasonGrain();'));
+const tail = body.slice(0, body.indexOf('diffuseColor.rgb = mix'));
+console.log(JSON.stringify({
+ wraps: (tail.match(/fract\\s*\\(/g) || []).length,
+ tail,
+}));
+""", _LIBS)
+ assert out["wraps"] == 0, (
+ "the twist and value randoms must be continuous combinations of the "
+ f"grain, not wrapped: {out['tail']}")
+
+
+def test_every_anchor_is_graded_for_this_pipeline():
+ """LAW 3. A channel at zero has nothing for the sky to fill, and two
+ autumn anchors a few degrees apart are one wash however they are picked."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchSeasonTint } from './lib/season.js';
+""" + _COMPILE + """
+const hueOf = (c) => { const o = {}; c.getHSL(o); return o.h * 360; };
+const rows = {};
+for (const kind of ['leaf', 'grass', 'ground']) {
+ const u = compiled({ kind }).u;
+ const anchors = ['uSeaSpring', 'uSeaSummer', 'uSeaGold', 'uSeaRed',
+ 'uSeaWinter'].map((n) => u[n].value);
+ rows[kind] = {
+ // working-space (linear) channels: the albedo the shader multiplies
+ minChannel: Math.min(...anchors.map((c) => Math.min(c.r, c.g, c.b))),
+ maxChannel: Math.max(...anchors.map((c) => Math.max(c.r, c.g, c.b))),
+ autumnGap: Math.abs(hueOf(u.uSeaGold.value) - hueOf(u.uSeaRed.value)),
+ twist: u.uSeaTwist.value,
+ keep: u.uSeaKeep.value,
+ };
+}
+console.log(JSON.stringify(rows));
+""", _LIBS)
+ for kind, row in out.items():
+ assert row["minChannel"] >= 0.012, (
+ f"{kind}: an anchor with a channel at zero takes nothing from the "
+ f"sky in shade ({row['minChannel']:.4f})")
+ assert row["maxChannel"] <= 0.8, f"{kind}: albedo over 0.8"
+ assert row["autumnGap"] >= 15, (
+ f"{kind}: gold and red are {row['autumnGap']:.1f} deg apart — one "
+ "wash, not a pair")
+ assert row["twist"] > 0 and row["keep"] > 0, (
+ f"{kind}: the hue variance knobs must not be switched off")
+
+
+def test_the_sun_is_warm_low_and_neutral_at_noon():
+ """Colour temperature is the cue that says what hour it is. A low sun is
+ warm and its fill turns blue; noon is neutral."""
+ out = measure("""
+import { dayCycle } from './lib/season.js';
+const at = (hour) => {
+ const d = dayCycle(null, { hour, latitude: 40 });
+ return { el: d.elevation, keyEl: d.keyElevation,
+ warmth: d.sunColor.r - d.sunColor.b,
+ fillCool: d.ambientColor.b - d.ambientColor.r,
+ night: d.night, intensity: d.intensity, fill: d.fill,
+ kelvin: d.kelvin, mood: d.mood };
+};
+console.log(JSON.stringify({
+ dawn: at(6.5), morning: at(9), noon: at(12), dusk: at(17.5),
+ late: at(18.6), night: at(20),
+}));
+""", _LIBS)
+ assert out["noon"]["el"] > out["dawn"]["el"], "noon must be highest"
+ assert out["noon"]["el"] > out["dusk"]["el"]
+ assert out["dawn"]["warmth"] > out["noon"]["warmth"], (
+ "a low sun must be warmer than a high one")
+ assert out["dusk"]["warmth"] > out["noon"]["warmth"]
+ assert out["dawn"]["fillCool"] > 0, "low-sun shadows go blue"
+ assert out["night"]["night"] is True
+ assert out["night"]["intensity"] < out["noon"]["intensity"]
+ # The sun goes DOWN at night; the key is lifted so a night scene still
+ # has somewhere to light from, and it says so by its name.
+ assert out["night"]["el"] < 0, "the sun must set"
+ assert out["night"]["keyEl"] > 0, "the moon key stays above the horizon"
+ assert out["dusk"]["mood"] == "golden" and out["noon"]["mood"] == "day"
+
+
+def test_the_pose_is_levelled_for_this_renderer():
+ """LAW 4. sunRig clamps a day key under 4.5 and a night fill under 0.8
+ UP, so a pose graded for a post chain at exposure 1.1 arrives as one flat
+ key across the whole working day and a night three times too dark."""
+ out = measure("""
+import { dayCycle } from './lib/season.js';
+const at = (hour) => {
+ const d = dayCycle(null, { hour, latitude: 40 });
+ return { intensity: d.intensity, fill: d.fill, el: d.elevation };
+};
+const day = [8, 9, 10, 11, 12, 13, 14, 15, 16].map(at);
+console.log(JSON.stringify({
+ dayMin: Math.min(...day.map((d) => d.intensity)),
+ dayMax: Math.max(...day.map((d) => d.intensity)),
+ fillMin: Math.min(...day.map((d) => d.fill)),
+ fillMax: Math.max(...day.map((d) => d.fill)),
+ night: at(23), setting: at(18.75),
+}));
+""", _LIBS)
+ # environment.js's own day rig is 5.4 over a 4.5 floor: the working day
+ # has to live ABOVE the floor or every hour of it renders identically.
+ assert out["dayMin"] >= 4.5, (
+ f"the day key falls under sunRig's floor ({out['dayMin']:.2f}) — "
+ "every hour clamped to the same light")
+ assert out["dayMax"] <= 6.0, "and never blows past the golden rig"
+ assert out["fillMin"] >= 1.0 and out["fillMax"] <= 1.45, (
+ "the fill tracks environment.js's 1.1 (golden) .. 1.4 (day)")
+ # night is a MOON rig, measured at 2.2 / 1.0 on this renderer
+ assert out["night"]["intensity"] >= 2.0
+ assert out["night"]["fill"] >= 0.9
+ # and the sun really does go out in its last degrees
+ assert out["setting"]["intensity"] < out["dayMin"]
+
+
+def test_the_day_cycle_does_not_mutate_what_it_was_handed():
+ """It returns a description a composer applies. A helper that reaches
+ into a rig it was given makes the pose impossible to re-derive, and two
+ calls at two hours would fight."""
+ out = measure("""
+import * as THREE from 'three';
+import { dayCycle } from './lib/season.js';
+const rig = { sunDir: new THREE.Vector3(0, 1, 0), intensity: 1,
+ marker: 'untouched' };
+const before = JSON.stringify(rig);
+const a = dayCycle(rig, { hour: 7 });
+const b = dayCycle(rig, { hour: 17 });
+console.log(JSON.stringify({
+ rigUnchanged: JSON.stringify(rig) === before,
+ independent: a.elevation !== b.elevation || a.azimuth !== b.azimuth,
+ bothFinite: [a.elevation, b.elevation, a.fogDensity, b.fogDensity,
+ a.intensity, b.intensity].every(Number.isFinite),
+ // fog stays in the sky's own hue family — it IS the horizon colour
+ fogIsHorizon: a.fogColor.getHex() === a.horizon.getHex(),
+ freshColours: a.fogColor !== a.horizon,
+}));
+""", _LIBS)
+ assert out["rigUnchanged"], "dayCycle must not mutate its argument"
+ assert out["independent"] and out["bothFinite"]
+ assert out["fogIsHorizon"] and out["freshColours"]
+
+
+def test_one_seed_turns_the_same_canopy_every_time():
+ out = measure("""
+import * as THREE from 'three';
+import { patchSeasonTint } from './lib/season.js';
+""" + _COMPILE + """
+const seedOf = (seed) => compiled({ seed }).u.uSeaSeed.value;
+console.log(JSON.stringify({
+ same: seedOf(4).x === seedOf(4).x && seedOf(4).y === seedOf(4).y,
+ differs: seedOf(4).x !== seedOf(9).x,
+}));
+""", _LIBS)
+ assert out["same"] and out["differs"]
+
+
+def test_the_tint_compiles_over_the_libraries_it_lands_on():
+ """A season tint goes on foliage that already carries leaf transmission,
+ wind and surface breakup — on an InstancedMesh, which is how a stand of
+ trees is drawn, and on a canopy.js crown, which is the asset whose model
+ position the fallback exists for."""
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import { patchSeasonTint, dayCycle } from './lib/season.js';
+import { patchLeafSSS, patchWind } from './lib/foliage_shade.js';
+import { patchMicroBreakup } from './lib/surface_wear.js';
+import { makeCanopy } from './lib/canopy.js';
+export function createScene() {
+ const scene = new THREE.Scene();
+ const pose = dayCycle(null, { hour: 16 });
+ const sun = new THREE.DirectionalLight(pose.sunColor, pose.intensity);
+ sun.position.copy(pose.sunDir).multiplyScalar(60);
+ scene.add(sun);
+ scene.add(new THREE.HemisphereLight(0xbfd4ee, 0x6a5a44, pose.fill));
+ const leaf = new THREE.MeshStandardMaterial({ color: 0x4a6b2a });
+ patchLeafSSS(leaf, {});
+ patchWind(leaf, { height: 4 });
+ patchMicroBreakup(leaf, {});
+ patchSeasonTint(leaf, { season: 0.5, kind: 'leaf' });
+ scene.add(new THREE.Mesh(new THREE.PlaneGeometry(1, 1), leaf));
+ scene.add(new THREE.InstancedMesh(
+ new THREE.ConeGeometry(1, 3, 8), leaf, 4));
+ const crown = makeCanopy({ position: [0, 4, 0], radius: 2.5, leaves: 200 });
+ patchSeasonTint(crown.children[0].material,
+ { season: 0.5, kind: 'leaf', seed: 3 });
+ scene.add(crown);
+ const ground = new THREE.MeshStandardMaterial({ color: 0x6b5d3c });
+ patchSeasonTint(ground, { season: 0.5, kind: 'ground' });
+ const mat = new THREE.Mesh(new THREE.PlaneGeometry(20, 20, 8, 8), ground);
+ mat.rotation.x = -Math.PI / 2;
+ scene.add(mat);
+ return { scene, update() {},
+ cameras: [{ name: 'wood', position: [9, 5, 11],
+ lookAt: [0, 2, 0], fov: 45 }] };
+}
+""", ("shader.js", "season.js", "foliage_shade.js", "surface_wear.js",
+ "canopy.js", "grass.js", "noise.js"))
+ assert code == 0, out
+ assert "WARN" not in out, out
diff --git a/harness/tests/scene_runtime/lib/test_shader.py b/harness/tests/scene_runtime/lib/test_shader.py
new file mode 100644
index 00000000..36a9f1b2
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_shader.py
@@ -0,0 +1,601 @@
+"""shader.js — the custom-shader hub must not be silently discarded by OUR renderer.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference (tests/test_shader_lib.py).
+Their renderer ran a log depth buffer; ours (runtime_js/lib/browser/renderer.js) does
+not by default, so the four logdepth chunks are no-ops here — kept because
+`--log-depth` is a host option and the chunks cost nothing. What matters on ours:
+fog chunks (every scene sets scene.fog), the tonemapping/colorspace tail (we have NO
+post chain, so a custom shader without it renders untonemapped), and that every
+construction path compiles on the headless GPU.
+"""
+from __future__ import annotations
+
+import re
+
+import pytest
+from _probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js",)
+_CHUNKS = ("logdepthbuf_pars_vertex", "logdepthbuf_vertex",
+ "logdepthbuf_pars_fragment", "logdepthbuf_fragment")
+
+
+def _measure(script: str) -> dict:
+ return measure(script, _LIBS)
+
+
+def compile_fixture(fixture_src: str, libs: tuple[str, ...] = _LIBS, *, timeout_s: float = 180.0) -> tuple[int, str]:
+ """GPU-compile every material a fixture's build() makes, through
+ `_probe.compile_scene`, wrapping the fixture in the lit, fogged scene
+ below — `check_shaders.mjs` boots a SCENE, not a module.
+
+ The static audit stays scoped to the wrapper: the fixtures below call
+ `patchStandard`, and the audit's per-file uTime rule cannot see that
+ shader.js declares and binds uTime at assembly time (`withTime`), so it
+ would report an undeclared/unbound pair on GLSL that is correct. (The
+ library itself is exempt for the same reason — `shader_report.mjs`.)"""
+ return compile_scene(_WRAPPER, libs, extra={"fixture.js": fixture_src},
+ audit_module="src/scene.js", timeout_s=timeout_s)
+
+
+_WRAPPER = """
+import * as THREE from 'three';
+import { build } from './fixture.js';
+import { tickShaders } from './lib/shader.js';
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 20, 20] };
+export function heightAt() { return 0; }
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.003);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 1.0));
+ const sun = new THREE.DirectionalLight(0xffffff, 3); sun.position.set(10, 20, 10); sun.castShadow = true; scene.add(sun);
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(60, 60), new THREE.MeshStandardMaterial({ color: 0x777766 }));
+ ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground);
+ const built = await build();
+ if (built && built.isObject3D) scene.add(built);
+ return { scene, cameras: [{ name: 'a', position: [6, 4, 8], lookAt: [0, 1, 0], fov: 45 }],
+ update(t) { tickShaders(scene, t); } };
+}
+"""
+
+
+# ------------------------------------------------------------ assembly
+
+
+def test_the_four_depth_chunks_are_injected_from_the_mains():
+ out = _measure("""
+import { makeShaderMaterial } from './lib/shader.js';
+const m = makeShaderMaterial({
+ varyings: 'varying vec2 vUv;',
+ vertexMain: ' vUv = uv;',
+ fragmentMain: ' gl_FragColor = vec4(vUv, 0.0, 1.0);',
+});
+console.log(JSON.stringify({ vs: m.vertexShader, fs: m.fragmentShader,
+ isShaderMaterial: !!m.isShaderMaterial, hasTime: !!m.uniforms.uTime,
+ glslVersionSet: m.glslVersion != null }));
+""")
+ src = out["vs"] + "\n" + out["fs"]
+ for chunk in _CHUNKS:
+ assert f"#include <{chunk}>" in src, chunk
+ assert out["isShaderMaterial"] and out["hasTime"]
+ assert not out["glslVersionSet"], "GLSL3 makes three stop defining gl_FragColor"
+
+
+def test_every_include_is_alone_on_its_line():
+ out = _measure("""
+import { makeShaderMaterial } from './lib/shader.js';
+const m = makeShaderMaterial({ vertexMain: ' transformed.y += 1.0;',
+ fragmentMain: ' gl_FragColor = vec4(1.0);' });
+console.log(JSON.stringify({ vs: m.vertexShader, fs: m.fragmentShader }));
+""")
+ for line in (out["vs"] + "\n" + out["fs"]).splitlines():
+ stripped = line.strip()
+ if "#include" in stripped:
+ assert re.fullmatch(r"#include\s*<[a-z0-9_]+>;?", stripped), line
+
+
+def test_raw_sources_are_repaired_not_trusted():
+ out = _measure("""
+import { makeShaderMaterial } from './lib/shader.js';
+const m = makeShaderMaterial({
+ vertexShader: 'void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: 'void main() { gl_FragColor = vec4(1.0); }',
+});
+console.log(JSON.stringify({ vs: m.vertexShader, fs: m.fragmentShader }));
+""")
+ for chunk in _CHUNKS:
+ assert f"#include <{chunk}>" in out["vs"] + out["fs"], chunk
+ fs = out["fs"]
+ main_body = fs[fs.index("void main"):]
+ assert main_body.index("logdepthbuf_fragment") < main_body.index("gl_FragColor")
+ assert out["vs"].rindex("logdepthbuf_vertex") > out["vs"].rindex("gl_Position")
+
+
+def test_interstage_declarations_are_normalised_to_varying():
+ out = _measure("""
+import { makeShaderMaterial } from './lib/shader.js';
+const m = makeShaderMaterial({ varyings: 'out vec3 vN;',
+ vertexMain: ' vN = normalize(normalMatrix * normal);',
+ fragmentMain: ' gl_FragColor = vec4(abs(vN), 1.0);' });
+console.log(JSON.stringify({ vs: m.vertexShader, fs: m.fragmentShader, glslVersionSet: m.glslVersion != null }));
+""")
+ assert "varying vec3 vN;" in out["vs"] and "varying vec3 vN;" in out["fs"]
+ assert "out vec3 vN;" not in out["fs"]
+ assert not out["glslVersionSet"]
+
+
+def test_utime_is_declared_wherever_it_is_read():
+ out = _measure("""
+import { makeShaderMaterial } from './lib/shader.js';
+const m = makeShaderMaterial({ varyings: 'varying vec2 vUv;',
+ vertexMain: ' vUv = uv;\\n transformed.y += sin(uTime);',
+ fragmentMain: ' gl_FragColor = vec4(vUv, sin(uTime), 1.0);' });
+const q = makeShaderMaterial({ fragmentMain: ' gl_FragColor = vec4(1.0);' });
+const count = (s) => (s.match(/uniform float uTime;/g) || []).length;
+console.log(JSON.stringify({ vs: count(m.vertexShader), fs: count(m.fragmentShader),
+ unusedVs: count(q.vertexShader), unusedFs: count(q.fragmentShader) }));
+""")
+ assert out["vs"] == 1 and out["fs"] == 1
+ assert out["unusedVs"] == 0 and out["unusedFs"] == 0
+
+
+def test_a_redeclared_varying_is_absorbed_not_a_compile_error():
+ out = _measure("""
+import { makeShaderMaterial } from './lib/shader.js';
+const m = makeShaderMaterial({ varyings: 'varying vec2 vUv;', vertexMain: ' vUv = uv;',
+ fragmentHead: 'varying vec2 vUv;\\nuniform float uScale;',
+ fragmentMain: ' gl_FragColor = vec4(vUv * uScale, 0.0, 1.0);' });
+const count = (s) => (s.match(/varying vec2 vUv;/g) || []).length;
+console.log(JSON.stringify({ vs: count(m.vertexShader), fs: count(m.fragmentShader),
+ keptUniform: m.fragmentShader.includes('uniform float uScale;') }));
+""")
+ assert out["vs"] == 1 and out["fs"] == 1 and out["keptUniform"]
+
+
+def test_a_custom_shader_recedes_into_the_scene_fog():
+ """Every scene here sets scene.fog; three delivers fog ONLY through the
+ chunks and their uniforms. Opting out (`fog: false`) leaves nothing
+ behind and writes the marker OUR static audit reads (`3dcv: no-fog`)."""
+ out = _measure("""
+import { makeShaderMaterial } from './lib/shader.js';
+const m = makeShaderMaterial({ fragmentMain: ' gl_FragColor = vec4(0.5, 0.6, 0.7, 1.0);' });
+const off = makeShaderMaterial({ fog: false, fragmentMain: ' gl_FragColor = vec4(0.5, 0.6, 0.7, 1.0);' });
+console.log(JSON.stringify({ vs: m.vertexShader, fs: m.fragmentShader, fogFlag: m.fog === true,
+ hasFogColor: !!m.uniforms.fogColor, hasFogDensity: !!m.uniforms.fogDensity,
+ offVs: off.vertexShader, offFs: off.fragmentShader, offFlag: off.fog === true,
+ offUniform: !!off.uniforms.fogColor }));
+""")
+ for chunk in ("fog_pars_vertex", "fog_vertex"):
+ assert f"#include <{chunk}>" in out["vs"], chunk
+ for chunk in ("fog_pars_fragment", "fog_fragment"):
+ assert f"#include <{chunk}>" in out["fs"], chunk
+ assert out["fogFlag"] and out["hasFogColor"] and out["hasFogDensity"]
+ assert "vec4 mvPosition = modelViewMatrix" in out["vs"]
+ body = out["fs"][out["fs"].index("void main"):]
+ assert body.index("gl_FragColor") < body.index("fog_fragment")
+ assert "fog_pars_vertex" not in out["offVs"] and "fog_fragment" not in out["offFs"]
+ assert not out["offFlag"] and not out["offUniform"]
+ assert "3dcv: no-fog" in out["offFs"], "the opt-out marker our audit reads"
+
+
+def test_a_custom_shader_ends_the_way_three_ends_its_own():
+ """No post chain on this renderer: tone map + sRGB happen in the fragment
+ tail, so a custom shader without three's two closing chunks renders dark
+ and untonemapped next to every built-in."""
+ out = _measure("""
+import { makeShaderMaterial } from './lib/shader.js';
+const m = makeShaderMaterial({ fragmentMain: ' gl_FragColor = vec4(1.0);' });
+const raw = makeShaderMaterial({ fragmentShader: 'void main() { gl_FragColor = vec4(1.0); }' });
+const tail = (s) => s.slice(s.lastIndexOf('gl_FragColor'));
+console.log(JSON.stringify({
+ assembledTone: /tonemapping_fragment/.test(m.fragmentShader),
+ assembledSpace: /colorspace_fragment/.test(m.fragmentShader),
+ rawGetsThemToo: /colorspace_fragment/.test(raw.fragmentShader),
+ afterFog: m.fragmentShader.indexOf('colorspace_fragment') > m.fragmentShader.indexOf('fog_fragment'),
+ aloneOnTheirLines: tail(m.fragmentShader).split('\\n').filter((l) => l.includes('#include'))
+ .every((l) => l.trim().startsWith('#include')) }));
+""")
+ assert out["assembledTone"] and out["assembledSpace"] and out["rawGetsThemToo"]
+ assert out["afterFog"] and out["aloneOnTheirLines"]
+
+
+def test_added_light_fades_into_distance_instead_of_gaining_haze():
+ out = _measure("""
+import * as THREE from 'three';
+import { makeShaderMaterial } from './lib/shader.js';
+const add = makeShaderMaterial({ additive: true, fragmentMain: ' gl_FragColor = vec4(1.0, 0.95, 0.8, 0.4);' });
+const solid = makeShaderMaterial({ fragmentMain: ' gl_FragColor = vec4(0.5);' });
+console.log(JSON.stringify({ blending: add.blending === THREE.AdditiveBlending,
+ transparent: add.transparent === true, depthWrite: add.depthWrite === false,
+ fadesAlpha: add.fragmentShader.includes('gl_FragColor.a *= 1.0 - clamp('),
+ noMix: !add.fragmentShader.includes('#include <fog_fragment>'),
+ solidMixes: solid.fragmentShader.includes('#include <fog_fragment>'),
+ hasPars: add.fragmentShader.includes('#include <fog_pars_fragment>') }));
+""")
+ assert all(out[k] for k in ("blending", "transparent", "depthWrite", "fadesAlpha", "noMix", "solidMixes", "hasPars")), out
+
+
+def test_the_craft_helpers_are_in_the_util_block_and_guarded():
+ out = _measure("""
+import * as THREE from 'three';
+import { GLSL_UTIL, makeShaderMaterial, patchStandard } from './lib/shader.js';
+const m = makeShaderMaterial({ fragmentMain: ' gl_FragColor = vec4(1.0);' });
+const p = patchStandard(new THREE.MeshStandardMaterial(), { name: 'x' });
+const shader = { vertexShader: 'void main() { #include <begin_vertex> }',
+ fragmentShader: 'void main() { #include <color_fragment> }', uniforms: {} };
+p.onBeforeCompile(shader);
+console.log(JSON.stringify({ util: GLSL_UTIL, inShader: m.fragmentShader.includes('astraStroke'),
+ vsGuard: m.vertexShader.includes('#ifdef ASTRA_FRAG'), vsDefine: m.vertexShader.includes('#define ASTRA_FRAG'),
+ fsDefine: m.fragmentShader.includes('#define ASTRA_FRAG'),
+ patchedFsDefine: shader.fragmentShader.includes('#define ASTRA_FRAG'),
+ patchedVsDefine: shader.vertexShader.includes('#define ASTRA_FRAG') }));
+""")
+ for fn in ("astraStroke", "astraFacing", "astraFallAge", "astraStagger", "astraHueBreak", "astraFresnel"):
+ assert f"{fn}(" in out["util"], fn
+ assert "fwidth(v)" in out["util"] and out["inShader"]
+ # fwidth is fragment-only and the util block ships in BOTH stages.
+ assert out["vsGuard"] and not out["vsDefine"]
+ assert out["fsDefine"] and out["patchedFsDefine"] and not out["patchedVsDefine"]
+
+
+# ------------------------------------------------------------ patching
+
+
+def test_patched_builtins_do_not_share_one_program():
+ out = _measure("""
+import * as THREE from 'three';
+import { patchStandard } from './lib/shader.js';
+const a = patchStandard(new THREE.MeshStandardMaterial(), { name: 'wet', fragmentBody: ' diffuseColor.rgb *= 0.5;' });
+const b = patchStandard(new THREE.MeshStandardMaterial(), { name: 'dusty', fragmentBody: ' diffuseColor.rgb += 0.1;' });
+const shaderA = { vertexShader: 'void main() { #include <begin_vertex> }',
+ fragmentShader: 'void main() { #include <color_fragment> }', uniforms: {} };
+a.onBeforeCompile(shaderA);
+console.log(JSON.stringify({ keyA: a.customProgramCacheKey(), keyB: b.customProgramCacheKey(),
+ injected: shaderA.fragmentShader.includes('diffuseColor.rgb *= 0.5'), gotUniform: !!shaderA.uniforms.uTime }));
+""")
+ assert out["keyA"] != out["keyB"] and out["injected"] and out["gotUniform"]
+
+
+def test_two_patches_on_one_material_both_survive_in_call_order():
+ out = _measure("""
+import * as THREE from 'three';
+import { patchStandard } from './lib/shader.js';
+const m = new THREE.MeshStandardMaterial();
+patchStandard(m, { name: 'wet', uniforms: { uWet: { value: 0.5 } }, fragmentBody: ' diffuseColor.rgb *= 0.5; // FIRST' });
+patchStandard(m, { name: 'dusty', uniforms: { uDust: { value: 0.2 } }, vertexBody: ' transformed.y += 0.01;',
+ fragmentBody: ' diffuseColor.rgb += 0.1; // SECOND' });
+patchStandard(m, { name: 'wet', uniforms: { uWet: { value: 0.5 } }, fragmentBody: ' diffuseColor.rgb *= 0.5; // FIRST' });
+const shader = { vertexShader: 'void main() { #include <begin_vertex> }',
+ fragmentShader: 'void main() { #include <color_fragment> }', uniforms: {} };
+m.onBeforeCompile(shader);
+const fs = shader.fragmentShader;
+console.log(JSON.stringify({ key: m.customProgramCacheKey(),
+ order: fs.indexOf('// FIRST') < fs.indexOf('// SECOND'), onceEach: (fs.match(/\\/\\/ FIRST/g) || []).length,
+ vertex: shader.vertexShader.includes('transformed.y += 0.01'),
+ uWet: !!shader.uniforms.uWet, uDust: !!shader.uniforms.uDust,
+ utilOnce: (fs.match(/float astraFbm2/g) || []).length }));
+""")
+ assert out["order"] and out["onceEach"] == 1 and out["vertex"]
+ assert out["uWet"] and out["uDust"]
+ assert out["key"] == "astra:wet+dusty", out["key"]
+ assert out["utilOnce"] == 1
+
+
+def test_patch_declarations_are_deduped_and_utime_declared():
+ out = _measure("""
+import * as THREE from 'three';
+import { patchStandard } from './lib/shader.js';
+const m = new THREE.MeshStandardMaterial();
+const head = 'varying float vK;\\nuniform float uTime;\\nuniform vec3 uShared[8];';
+patchStandard(m, { name: 'a', vertexHead: head, fragmentHead: head,
+ vertexBody: ' vK = sin(uTime);', fragmentBody: ' diffuseColor.rgb += uShared[0] * vK;' });
+patchStandard(m, { name: 'b', vertexHead: head, fragmentHead: head, vertexBody: ' transformed.x += cos(uTime);' });
+const sway = patchStandard(new THREE.MeshStandardMaterial(), { name: 'sway',
+ vertexBody: ' transformed.x += sin(uTime) * 0.1;', fragmentBody: ' diffuseColor.rgb *= 0.9 + 0.1 * sin(uTime);' });
+const s1 = { vertexShader: 'void main() { #include <begin_vertex> }', fragmentShader: 'void main() { #include <color_fragment> }', uniforms: {} };
+const s2 = { vertexShader: 'void main() { #include <begin_vertex> }', fragmentShader: 'void main() { #include <color_fragment> }', uniforms: {} };
+m.onBeforeCompile(s1); sway.onBeforeCompile(s2);
+const count = (s, re) => (s.match(re) || []).length;
+console.log(JSON.stringify({
+ vK: count(s1.vertexShader, /varying float vK;/g) + count(s1.fragmentShader, /varying float vK;/g),
+ time: count(s1.vertexShader, /uniform float uTime;/g), arr: count(s1.fragmentShader, /uniform vec3 uShared\\[8\\];/g),
+ both: s1.vertexShader.includes('sin(uTime)') && s1.vertexShader.includes('cos(uTime)'),
+ swayVs: count(s2.vertexShader, /uniform float uTime;/g), swayFs: count(s2.fragmentShader, /uniform float uTime;/g) }));
+""")
+ assert out["vK"] == 2 and out["time"] == 1 and out["arr"] == 1 and out["both"]
+ assert out["swayVs"] == 1 and out["swayFs"] == 1
+
+
+def test_two_patches_defining_one_function_name_say_so():
+ out = _measure("""
+import * as THREE from 'three';
+import { patchStandard } from './lib/shader.js';
+const compile = (type, a, b) => {
+ const fn = (body) => `${type} astraShared(vec2 p) {\\n return ${body};\\n}`;
+ const m = new THREE.MeshStandardMaterial();
+ patchStandard(m, { name: 'first', fragmentHead: fn(a), fragmentBody: ' diffuseColor.rgb *= 1.0;' });
+ patchStandard(m, { name: 'second', fragmentHead: ' ' + fn(b) });
+ const s = { uniforms: {}, vertexShader: 'void main() {}', fragmentShader: '#include <color_fragment>' };
+ try { m.onBeforeCompile(s); return { ok: true, copies: (s.fragmentShader.match(/astraShared\\(vec2/g) || []).length }; }
+ catch (e) { return { ok: false, msg: e.message }; }
+};
+const same = compile('float', 'p.x', 'p.x'), differ = compile('float', 'p.x', 'p.y');
+console.log(JSON.stringify({ sameOk: same.ok, sameCopies: same.copies, differThrew: !differ.ok,
+ namesBoth: !differ.ok && /first/.test(differ.msg) && /second/.test(differ.msg) && /astraShared/.test(differ.msg),
+ ivec: !compile('ivec3', 'ivec3(0)', 'ivec3(1)').ok, bvec: !compile('bvec2', 'bvec2(true)', 'bvec2(false)').ok,
+ matNxM: !compile('mat2x3', 'mat2x3(0.0)', 'mat2x3(1.0)').ok }));
+""")
+ assert out["sameOk"] and out["sameCopies"] == 1
+ assert out["differThrew"] and out["namesBoth"]
+ assert out["ivec"] and out["bvec"] and out["matNxM"]
+
+
+def test_roughness_composes_across_libraries_in_any_order_within_range():
+ out = _measure("""
+import * as THREE from 'three';
+import { composeRoughness } from './lib/shader.js';
+const a = new THREE.MeshStandardMaterial({ roughness: 0.8 });
+composeRoughness(a, 'wet', 0.5); composeRoughness(a, 'wear', 0.9);
+const b = new THREE.MeshStandardMaterial({ roughness: 0.8 });
+composeRoughness(b, 'wear', 0.9); composeRoughness(b, 'wet', 0.5); composeRoughness(b, 'wet', 0.5);
+const c = new THREE.MeshStandardMaterial({ roughness: 0.9 });
+composeRoughness(c, 'rust', 1.3); const capped = composeRoughness(c, 'dust', 1.2);
+console.log(JSON.stringify({ a: a.roughness, b: b.roughness, base: a.userData.astraRoughness.base, capped,
+ floor: composeRoughness(new THREE.MeshStandardMaterial({ roughness: 0.5 }), 'x', 0.0),
+ basic: Number.isNaN(composeRoughness(new THREE.MeshBasicMaterial(), 'x', 0.5)) }));
+""")
+ assert abs(out["a"] - 0.36) < 1e-6 and abs(out["b"] - out["a"]) < 1e-9
+ assert out["base"] == 0.8 and out["capped"] == 1
+ assert out["floor"] == 0.04 and out["basic"]
+
+
+# ------------------------------------------------------------ tick / instancing / veils
+
+
+def test_tick_drives_every_shader_from_one_call():
+ out = _measure("""
+import * as THREE from 'three';
+import { makeShaderMaterial, patchStandard, tickShaders } from './lib/shader.js';
+const scene = new THREE.Scene();
+const a = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), makeShaderMaterial({ fragmentMain: ' gl_FragColor = vec4(uTime);' }));
+const b = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), patchStandard(new THREE.MeshStandardMaterial(), { name: 'x' }));
+const c = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial());
+scene.add(a, b, c);
+const n = tickShaders(scene, 4.25);
+console.log(JSON.stringify({ n, a: a.material.uniforms.uTime.value, b: b.material.userData.uniforms.uTime.value }));
+""")
+ assert out["n"] == 2 and out["a"] == 4.25 and out["b"] == 4.25
+
+
+def test_instance_variation_is_deterministic_and_per_instance():
+ out = _measure("""
+import * as THREE from 'three';
+import { instanceVariation } from './lib/shader.js';
+const mk = (seed) => instanceVariation(new THREE.InstancedMesh(new THREE.BoxGeometry(1, 1, 1),
+ new THREE.MeshStandardMaterial(), 40), { seed }).geometry.attributes.aVar;
+const a = mk(1), b = mk(1), c = mk(7);
+const arr = (x) => Array.from(x.array);
+console.log(JSON.stringify({ same: JSON.stringify(arr(a)) === JSON.stringify(arr(b)),
+ differs: JSON.stringify(arr(a)) !== JSON.stringify(arr(c)), count: a.count, itemSize: a.itemSize,
+ distinctHues: new Set(arr(a).filter((_, i) => i % 3 === 0)).size,
+ scaleMin: Math.min(...arr(a).filter((_, i) => i % 3 === 1)), scaleMax: Math.max(...arr(a).filter((_, i) => i % 3 === 1)) }));
+""")
+ assert out["same"] and out["differs"] and out["count"] == 40 and out["itemSize"] == 3
+ assert out["distinctHues"] > 30
+ assert 0.85 < out["scaleMin"] < 1.0 < out["scaleMax"] < 1.15
+
+
+def test_instanced_quad_is_gtao_safe_and_states_its_volume():
+ out = _measure("""
+import { instancedQuad } from './lib/shader.js';
+const g = instancedQuad(120, 2, 3, 25);
+const d = instancedQuad(40, 0.5, 0.5);
+const n = g.getAttribute('normal');
+console.log(JSON.stringify({ posAllZero: Array.from(g.attributes.position.array).every((v) => v === 0),
+ cornerSpread: Math.max(...g.attributes.aCorner.array) - Math.min(...g.attributes.aCorner.array),
+ instanceCount: g.instanceCount, hasUv: !!g.attributes.uv, r: g.boundingSphere.radius,
+ box: g.boundingBox ? 1 : null, defaultR: d.boundingSphere.radius > 1000,
+ unitNormal: Math.abs(Math.hypot(n.getX(0), n.getY(0), n.getZ(0)) - 1) < 1e-6 }));
+""")
+ assert out["posAllZero"] and out["cornerSpread"] > 0 and out["instanceCount"] == 120 and out["hasUv"]
+ assert out["r"] == 25 and out["box"] is None and out["defaultR"] and out["unitNormal"]
+
+
+def test_a_veil_does_not_occlude_in_depth_or_shadow_passes():
+ out = _measure("""
+import * as THREE from 'three';
+import { keepOutOfDepthPasses } from './lib/shader.js';
+const own = new THREE.MeshBasicMaterial({ transparent: true });
+const mesh = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), own);
+const g = new THREE.Group(); g.add(mesh); keepOutOfDepthPasses(g);
+const geo = mesh.geometry, range = () => geo.drawRange.count;
+mesh.onBeforeRender(null, null, null, geo, own); const withOwn = range(); mesh.onAfterRender(null, null, null, geo);
+mesh.onBeforeRender(null, null, null, geo, new THREE.MeshNormalMaterial()); const withOverride = range(); mesh.onAfterRender(null, null, null, geo);
+keepOutOfDepthPasses(g);
+mesh.onBeforeRender(null, null, null, geo, own); const again = range(); mesh.onAfterRender(null, null, null, geo);
+console.log(JSON.stringify({ withOwn: withOwn > 0, noShadow: mesh.castShadow === false,
+ withOverride: withOverride === 0, restored: range() > 0, idempotent: again > 0 }));
+""")
+ assert all(out.values()), out
+
+
+def test_a_swept_profile_is_one_closed_body():
+ out = _measure("""
+import { sweepProfile } from './lib/shader.js';
+const g = sweepProfile((t) => ({ x: 0, y: 8 - 8 * t * t, z: t * 6 }),
+ (a, t) => ({ x: Math.cos(a) * 2, y: 0, z: Math.sin(a) * (0.4 + 2 * t) }), { nu: 24, nv: 32 });
+const pos = g.attributes.position.array;
+let minY = 1e9, maxY = -1e9, minZ = 1e9, maxZ = -1e9;
+for (let i = 0; i < pos.length; i += 3) { minY = Math.min(minY, pos[i + 1]); maxY = Math.max(maxY, pos[i + 1]);
+ minZ = Math.min(minZ, pos[i + 2]); maxZ = Math.max(maxZ, pos[i + 2]); }
+console.log(JSON.stringify({ verts: g.attributes.position.count, hasUv: !!g.attributes.uv, hasNormal: !!g.attributes.normal,
+ tris: g.index.count / 3, dropY: Math.round(maxY - minY), depthZ: Math.round((maxZ - minZ) * 10) / 10 }));
+""")
+ assert out["verts"] == 25 * 33 and out["tris"] == 24 * 32 * 2
+ assert out["hasUv"] and out["hasNormal"] and out["dropY"] == 8 and out["depthZ"] > 6
+
+
+# ------------------------------------------------------------ the GPU says so
+
+
+def test_every_construction_path_compiles_on_our_gpu():
+ """Assembled mains, raw sources, an additive veil, a billboard field, two
+ chained patches with shadowLike, and instanceVariation on a built-in — all
+ through renderer.js (no log depth, PCFSoft shadows, ACES) on headless Chrome."""
+ code, out = compile_fixture("""
+import * as THREE from 'three';
+import { makeShaderMaterial, patchStandard, shadowLike, instanceVariation, instancedQuad, keepOutOfDepthPasses } from './lib/shader.js';
+export function build() {
+ const g = new THREE.Group();
+ g.add(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), makeShaderMaterial({
+ name: 'Assembled', uniforms: { uColor: { value: new THREE.Color(0xff8844) } },
+ varyings: 'varying vec2 vUv;', fragmentHead: 'uniform vec3 uColor;',
+ vertexMain: ' vUv = uv;\\n transformed.y += 0.1 * sin(uTime + position.x);',
+ fragmentMain: ' float n = astraFbm2(vUv * 8.0, 3);\\n gl_FragColor = vec4(uColor * n * astraStroke(vUv.y * 10.0, 0.05), 1.0);',
+ })));
+ g.add(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), makeShaderMaterial({ name: 'Raw',
+ vertexShader: 'varying vec2 vUv;\\nvoid main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: 'varying vec2 vUv;\\nvoid main() { gl_FragColor = vec4(vUv, 0.5, 1.0); }' })));
+ g.add(keepOutOfDepthPasses(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), makeShaderMaterial({ name: 'Additive', additive: true,
+ fragmentMain: ' gl_FragColor = vec4(1.0, 0.9, 0.7, 0.3 * (0.5 + 0.5 * sin(uTime)));' }))));
+ g.add(new THREE.Mesh(instancedQuad(50, 0.3, 0.3, 20), makeShaderMaterial({ name: 'Quads', vertexHead: 'attribute vec3 aCorner;',
+ vertexMain: ' transformed = aCorner + vec3(float(gl_InstanceID) * 0.1, 1.0, 0.0);',
+ fragmentMain: ' gl_FragColor = vec4(0.9, 0.9, 0.5, 1.0);' })));
+ const mat = new THREE.MeshStandardMaterial({ color: 0x668844 });
+ // A map-less built-in has no vUv: carry a world-space varying instead.
+ const head = 'varying float vSway;\\nvarying vec3 vAstraW;';
+ const body = ' vSway = sin(uTime + position.x * 3.0);\\n transformed.x += 0.05 * vSway;\\n vAstraW = (modelMatrix * vec4(transformed, 1.0)).xyz;';
+ patchStandard(mat, { name: 'sway', vertexHead: head, vertexBody: body, fragmentHead: head,
+ fragmentBody: ' diffuseColor.rgb = astraHueBreak(diffuseColor.rgb, vAstraW.xz, 6.0, 0.6) * (0.9 + 0.1 * vSway);' });
+ patchStandard(mat, { name: 'wet', uniforms: { uWet: { value: 0.4 } }, fragmentHead: 'uniform float uWet;',
+ fragmentBody: ' diffuseColor.rgb *= 1.0 - 0.3 * uWet;' });
+ const leaf = new THREE.Mesh(new THREE.PlaneGeometry(1, 1, 8, 8), mat);
+ shadowLike(leaf, 'sway-depth', head, body); g.add(leaf);
+ const inst = new THREE.InstancedMesh(new THREE.BoxGeometry(0.3, 0.3, 0.3), new THREE.MeshStandardMaterial({ color: 0x884422, name: 'boxes' }), 30);
+ const m = new THREE.Matrix4();
+ for (let i = 0; i < 30; i++) inst.setMatrixAt(i, m.makeTranslation(i * 0.4 - 6, 0.5, 2));
+ instanceVariation(inst, { seed: 3 }); g.add(inst);
+ return g;
+}
+""")
+ assert code == 0, out
+ assert "ERROR" not in out, out
+
+
+# --------------------------------------------- the three later hooks
+
+
+def test_the_later_hooks_land_after_their_own_chunks_in_order():
+ """`<color_fragment>` reaches the ALBEDO and nothing else, which is why a
+ partial crust (rust, dust) could only be sold by retuning the whole
+ material's roughness, and why airlight could only lift reflectance. The
+ three later hooks are opt-in and each lands after the chunk that puts its
+ variable in scope: roughnessFactor, metalnessFactor, and gl_FragColor
+ while it is still LINEAR (tonemapping and the colourspace convert come
+ after `<opaque_fragment>`, fog after those). Bodies from several patches
+ join in CALL order, as the albedo hook already does."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchStandard } from './lib/shader.js';
+const m = new THREE.MeshStandardMaterial({ color: 0x8b8478, roughness: 0.4 });
+patchStandard(m, { name: 'rust',
+ roughnessBody: ' roughnessFactor = mix(roughnessFactor, 0.95, 0.5);',
+ metalnessBody: ' metalnessFactor *= 0.4;',
+ outputBody: ' gl_FragColor.rgb += vec3(0.02, 0.01, 0.0);' });
+patchStandard(m, { name: 'dust',
+ roughnessBody: ' roughnessFactor = min(1.0, roughnessFactor + 0.2);',
+ outputBody: ' gl_FragColor.rgb *= 0.98;' });
+const shader = { vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: ['void main() {', '#include <color_fragment>',
+ '#include <roughnessmap_fragment>', '#include <metalnessmap_fragment>',
+ '#include <opaque_fragment>', '}'].join('\\n'), uniforms: {} };
+m.onBeforeCompile(shader);
+console.log(JSON.stringify({ fs: shader.fragmentShader }));
+""")
+ fs = out["fs"]
+ for chunk, body in (
+ ("roughnessmap_fragment", "roughnessFactor = mix(roughnessFactor, 0.95, 0.5);"),
+ ("metalnessmap_fragment", "metalnessFactor *= 0.4;"),
+ ("opaque_fragment", "gl_FragColor.rgb += vec3(0.02, 0.01, 0.0);"),
+ ):
+ inc, at = f"#include <{chunk}>", fs.index(body)
+ assert fs.index(inc) < at, f"{body} landed before {inc}"
+ # Call order, both hooks that two patches wrote into.
+ assert fs.index("roughnessFactor = mix(") < fs.index("roughnessFactor = min("), fs
+ assert fs.index("gl_FragColor.rgb +=") < fs.index("gl_FragColor.rgb *="), fs
+ # A patch that asks for none of them injects none of them.
+ assert fs.count("#include <opaque_fragment>") == 1, fs
+
+
+def test_a_material_with_no_later_hooks_is_byte_for_byte_unchanged():
+ """The hooks are additive: every patch shipped before them asks for none,
+ so their chunks must come back untouched — no stray blank line, nothing
+ for a later `.replace()` in this chain to land on twice."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchStandard } from './lib/shader.js';
+const m = new THREE.MeshStandardMaterial({ color: 0x8b8478 });
+patchStandard(m, { name: 'albedo',
+ fragmentBody: ' diffuseColor.rgb *= 0.9;' });
+const src = ['void main() {', '#include <color_fragment>',
+ '#include <roughnessmap_fragment>', '#include <metalnessmap_fragment>',
+ '#include <opaque_fragment>', '}'].join('\\n');
+const shader = { vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: src, uniforms: {} };
+m.onBeforeCompile(shader);
+const tail = shader.fragmentShader.slice(
+ shader.fragmentShader.indexOf('#include <roughnessmap_fragment>'));
+console.log(JSON.stringify({ tail }));
+""")
+ assert out["tail"] == ("#include <roughnessmap_fragment>\n"
+ "#include <metalnessmap_fragment>\n"
+ "#include <opaque_fragment>\n}")
+
+
+def test_the_later_hooks_compile_on_the_real_renderer():
+ """Only the GPU can say that `roughnessFactor` and `metalnessFactor` are
+ really in scope where the hooks inject, and that gl_FragColor is writable
+ after `<opaque_fragment>` — three's chunk names and contents are its own
+ business and change between releases."""
+ code, out = compile_fixture("""
+import * as THREE from 'three';
+import { patchStandard } from './lib/shader.js';
+
+export function build() {
+ const g = new THREE.Group();
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0x9a6b3f, roughness: 0.35, metalness: 0.8 });
+ patchStandard(mat, {
+ name: 'crust',
+ uniforms: { uCrust: { value: 0.6 } },
+ fragmentHead: 'uniform float uCrust;\\nvarying vec3 vCrustW;',
+ vertexHead: 'varying vec3 vCrustW;',
+ vertexBody: ' vCrustW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ fragmentBody:
+ ' float crust = uCrust * astraFbm2(vCrustW.xz * 1.5, 3);\\n'
+ + ' diffuseColor.rgb = mix(diffuseColor.rgb,'
+ + ' vec3(0.42, 0.20, 0.09), crust);',
+ // the point of the hook: kill the specular ONLY where the crust is
+ roughnessBody: ' roughnessFactor = mix(roughnessFactor, 0.98, crust);',
+ metalnessBody: ' metalnessFactor *= 1.0 - crust;',
+ outputBody: ' gl_FragColor.rgb += vec3(0.03, 0.02, 0.01) * crust;',
+ });
+ const tank = new THREE.Mesh(new THREE.CylinderGeometry(1, 1, 3, 24), mat);
+ tank.position.y = 1.5; tank.castShadow = true; g.add(tank);
+ // the same material on an InstancedMesh: a second permutation, and the
+ // one place USE_INSTANCING inside the world-space helper is compiled.
+ const inst = new THREE.InstancedMesh(
+ new THREE.BoxGeometry(0.4, 0.4, 0.4), mat, 8);
+ const m4 = new THREE.Matrix4();
+ for (let i = 0; i < 8; i++) {
+ inst.setMatrixAt(i, m4.makeTranslation(i * 0.7 - 2.5, 0.2, 2.5));
+ }
+ inst.instanceMatrix.needsUpdate = true;
+ g.add(inst);
+ return g;
+}
+""")
+ assert code == 0, out
+ assert "ERROR" not in out, out
diff --git a/harness/tests/scene_runtime/lib/test_signage.py b/harness/tests/scene_runtime/lib/test_signage.py
new file mode 100644
index 00000000..8f769ff6
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_signage.py
@@ -0,0 +1,320 @@
+"""signage.js: real extruded lettering, loadable under BOTH runtimes.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_signage_lib.py). Its four laws are kept as they stood — real
+glyph geometry from the shipped helvetiker face, centred on X/Z with the
+baseline at y = 0, a deterministic rebuild, and every documented option
+alive — because the census still imports scene modules under plain node
+and a broken load path still kills it.
+
+THE PORT'S OWN LAWS, each one measured on this host (frames under
+fx/out/signage/):
+
+1. THE FONT COMES FROM WHEREVER `three` CAME FROM. Both halves of the
+ dual-runtime loader assumed a `node_modules` next to the app and both
+ were dead here. Under node a bare workspace / temp probe has no parent
+ `node_modules`, so `createRequire().resolve('three/examples/fonts/…')`
+ threw MODULE_NOT_FOUND — every census-side `makeText` died. In the
+ browser our host serves the workspace at `/` and three at
+ `/__runtime/node_modules/`, so `../../node_modules/…` 404d twice per
+ render (console errors, run not-ok) and the module only survived by
+ falling through to its unpkg pin — i.e. it needed the internet. Both
+ now ask `import.meta.resolve`, which answers from the page's import map
+ in Chrome and from the module resolver (our `resolve_three.mjs` hook
+ included) under node. Rendered: `fx/out/signage/before` carried two
+ 404 console errors, `after` carries none.
+
+2. A LETTER IS NOT A CUTOUT. A sign faces the viewer, so the sun almost
+ never does: in the showcase base scene (sun az 215, both cameras at
+ az ~37) every glyph face is lit by sky + environment only, and one flat
+ albedo over the whole line rendered as a pasted-on shape. The glyphs
+ now carry a deterministic paint variance in a vertex colour — mottle,
+ grime at the baseline, extrusion WALLS down to ~0.63 and the bevel rim
+ as the brightest thing on the letter — read off |n.z|, so it needs no
+ material groups and survives any bevel setting. Measured over the
+ headline's own pixels (close view): lum_std 0.0683 -> 0.0837, hue_std
+ 0.0768 -> 0.0891.
+
+3. THE VERTEX COLOUR MAY ONLY DARKEN. It is normalised to a ceiling of
+ 1.0 so `color` stays the true albedo — a rim that multiplied a 0.80
+ linear paint by 1.14 would have quietly broken the 0.02-0.8 band the
+ default was moved into (0xf2f2f2, 0.887 linear, -> 0xe7e3da, 0.799).
+
+4. A SIGN THAT LIGHTS NOTHING IS A DECAL. An emissive line now carries a
+ practical whose candela is derived from its own radiance x inked area.
+ Measured at night on the board just above a 0.42 m OPEN sign: red
+ channel 0.174 -> 0.265, warmth (r-b) +0.023 -> +0.108.
+
+5. LETTERING IS MOUNTED, NEVER SEATED. `userData.placement = 'free'`, or
+ the host's settle pass (runtime_js/lib/host_placement.mjs) drops a line
+ of letters off its facade onto the terrain. Asserted against the real
+ settleScene, with an unmarked crate as the control.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import HARNESS, compile_scene, measure
+
+_HOST_PLACEMENT = (HARNESS / "runtime_js" / "lib" / "host_placement.mjs").as_uri()
+
+_PROBE = """
+import * as THREE from 'three';
+import { makeText, loadHelvetiker } from './lib/signage.js';
+import { settleScene } from '__PLACEMENT__';
+
+// Default load path: no opts.font escape hatch, no NODE_PATH, and this
+// probe dir has no node_modules of its own.
+const a = await makeText('OPEN', { size: 1 });
+const b = await makeText('OPEN', { size: 1 });
+const wide = await makeText('OPEN WIDE', { size: 1 });
+const bold = await makeText('OPEN', { size: 1, bold: true });
+const neon = await makeText('X', { size: 1, emissive: 0xff2244 });
+const dark = await makeText('X', { size: 1, emissive: 0xff2244, light: false });
+const flat = await makeText('OPEN', { size: 1, bevel: false });
+const plain = await makeText('OPEN', { size: 1, variation: 0 });
+const bare = await makeText('OPEN', { size: 1, shadow: false });
+
+a.geometry.computeBoundingBox();
+const bb = a.geometry.boundingBox;
+
+const pa = a.geometry.attributes.position.array;
+const pb = b.geometry.attributes.position.array;
+const ca = a.geometry.attributes.color.array;
+const cb = b.geometry.attributes.color.array;
+let identical = pa.length === pb.length && ca.length === cb.length;
+for (let i = 0; identical && i < pa.length; i++) {
+ if (pa[i] !== pb[i]) identical = false;
+}
+for (let i = 0; identical && i < ca.length; i++) {
+ if (ca[i] !== cb[i]) identical = false;
+}
+
+// vertex colour, split by |n.z|: caps face front/back, walls are the
+// extrusion sides, the bevel ring is everything between.
+const col = a.geometry.attributes.color;
+const nrm = a.geometry.attributes.normal;
+let capSum = 0, capN = 0, wallSum = 0, wallN = 0;
+let minC = 9, maxC = -9, hueSum = 0, hueMax = 0;
+for (let i = 0; i < col.count; i++) {
+ const r = col.array[i * 3], g = col.array[i * 3 + 1], bl = col.array[i * 3 + 2];
+ const nz = Math.abs(nrm.array[i * 3 + 2]);
+ const l = (r + g + bl) / 3;
+ if (nz > 0.98) { capSum += l; capN++; } else if (nz < 0.05) { wallSum += l; wallN++; }
+ minC = Math.min(minC, r, g, bl);
+ maxC = Math.max(maxC, r, g, bl);
+ hueSum += Math.abs(r - bl);
+ hueMax = Math.max(hueMax, Math.abs(r - bl));
+}
+
+// the settle pass must skip lettering and seat an unmarked object
+const scene = new THREE.Scene();
+const grd = new THREE.Mesh(new THREE.PlaneGeometry(60, 60),
+ new THREE.MeshStandardMaterial());
+grd.name = 'Ground';
+grd.rotation.x = -Math.PI / 2;
+scene.add(grd);
+const sign = await makeText('HOTEL', { size: 0.6 });
+sign.position.set(0, 3, 0);
+scene.add(sign);
+const crate = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),
+ new THREE.MeshStandardMaterial());
+crate.name = 'Crate';
+crate.position.set(6, 3, 0);
+scene.add(crate);
+const settled = settleScene(scene, THREE, { groundY: 0 });
+
+const f1 = await loadHelvetiker();
+const f2 = await loadHelvetiker();
+
+console.log(JSON.stringify({
+ w: bb.max.x - bb.min.x,
+ h: bb.max.y - bb.min.y,
+ d: bb.max.z - bb.min.z,
+ minY: bb.min.y,
+ cx: 0.5 * (bb.min.x + bb.max.x),
+ cz: 0.5 * (bb.min.z + bb.max.z),
+ userW: a.userData.size.w,
+ verts: a.geometry.attributes.position.count,
+ flatVerts: flat.geometry.attributes.position.count,
+ identical,
+ wideW: wide.userData.size.w,
+ boldW: bold.userData.size.w,
+ emissiveHex: neon.material.emissive.getHex(),
+ emissiveI: neon.material.emissiveIntensity,
+ plainEmissive: a.material.emissive.getHex(),
+ cached: f1 === f2,
+ name: a.name,
+ // --- the port's own numbers
+ colorHex: a.material.color.getHex(),
+ colorLinear: [a.material.color.r, a.material.color.g, a.material.color.b],
+ vertexColors: a.material.vertexColors,
+ hasColorAttr: !!a.geometry.attributes.color,
+ plainHasColorAttr: !!plain.geometry.attributes.color,
+ plainVertexColors: plain.material.vertexColors,
+ capMean: capSum / capN, wallMean: wallSum / wallN, capN, wallN,
+ minC, maxC, hueMean: hueSum / col.count, hueMax,
+ cast: a.castShadow, recv: a.receiveShadow,
+ bareCast: bare.castShadow, bareRecv: bare.receiveShadow,
+ placement: a.userData.placement,
+ lightCd: neon.userData.light ? neon.userData.light.intensity : null,
+ lightHex: neon.userData.light ? neon.userData.light.color.getHex() : null,
+ lightZ: neon.userData.light ? neon.userData.light.position.z : null,
+ lightShadow: neon.userData.light ? neon.userData.light.castShadow : null,
+ neonChildren: neon.children.length,
+ plainHasLight: a.userData.light !== undefined,
+ darkHasLight: dark.userData.light !== undefined,
+ darkChildren: dark.children.length,
+ settledCount: settled.count,
+ signY: sign.position.y,
+ crateY: crate.position.y,
+}));
+""".replace("__PLACEMENT__", _HOST_PLACEMENT)
+
+
+# The scene our check_shaders.mjs boots: a camera (a scene with none is
+# reported as not booted and never reaches the compile stage) and both
+# material variants, because a vertex-coloured standard material and an
+# emissive one are two different programs.
+_SCENE = """
+import * as THREE from 'three';
+import { makeText } from './lib/signage.js';
+
+export const BOUNDS = { min: [-8, 0, -8], max: [8, 8, 8] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xc9d6e0, 0.02);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ const paint = await makeText('MARKET', { size: 0.8, bold: true });
+ paint.position.set(0, 1.4, 0);
+ scene.add(paint);
+ const neon = await makeText('OPEN', { size: 0.4, emissive: 0xff3a4e });
+ neon.position.set(0, 0.6, 0.3);
+ scene.add(neon);
+ const flatpaint = await makeText('EST 1897', { size: 0.2, variation: 0 });
+ flatpaint.position.set(0, 0.2, 0.6);
+ scene.add(flatpaint);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [3, 2, 5], lookAt: [0, 1.2, 0], fov: 45 }],
+ update() {},
+ };
+}
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch of _PROBE, shared by every test that reads it."""
+ return measure(_PROBE, ("signage.js",))
+
+
+def test_default_font_path_yields_real_glyph_geometry(probe):
+ """End to end under node, in a bare temp dir with no node_modules and
+ no NODE_PATH — the case that threw MODULE_NOT_FOUND before the port.
+ 'OPEN' at size 1 must return substantial extruded geometry: wider than
+ tall, cap height near size, real depth."""
+ m = probe
+ assert m["w"] > m["h"] > 0, m
+ assert 0.5 < m["h"] <= 1.1, f"cap height off: {m['h']}"
+ assert 0.1 < m["d"] < 0.3, f"extrusion depth off: {m['d']}"
+ assert m["verts"] > 500, f"too few vertices for glyphs: {m['verts']}"
+
+
+def test_mesh_is_centered_with_baseline_at_zero(probe):
+ """Placement contract: centered on X and Z, baseline at y = 0, and
+ userData.size carries the measured bbox — sign boards and asset
+ seating are sized from these numbers."""
+ m = probe
+ assert abs(m["cx"]) < 1e-6 and abs(m["cz"]) < 1e-6, m
+ assert abs(m["minY"]) < 0.05, f"baseline drifted: {m['minY']}"
+ assert abs(m["userW"] - m["w"]) < 1e-6, "userData.size is stale"
+ assert m["name"] == "SignText"
+
+
+def test_same_input_rebuilds_identical_and_options_are_alive(probe):
+ """Determinism (fix rounds re-render untouched assets identically),
+ now including the baked paint variance, and each documented option
+ must actually change the output."""
+ m = probe
+ assert m["identical"], "same text+opts rebuilt differently"
+ assert m["wideW"] > m["userW"] * 1.5, "longer string not wider"
+ assert abs(m["boldW"] - m["userW"]) > 0.01, "bold face is dead"
+ assert m["verts"] > m["flatVerts"], "bevel:false changed nothing"
+ assert m["emissiveHex"] == 0xFF2244 and m["emissiveI"] == 1.6, m
+ assert m["plainEmissive"] == 0x000000, "default must not glow"
+ assert m["cached"], "font loaded twice — cache broken"
+
+
+def test_paint_variance_gives_the_face_hue_and_the_walls_form(probe):
+ """Law 2. Every glyph carries a vertex colour: the extrusion walls,
+ which see far less sky than the face, sit well below the caps, and the
+ warm/cool swing is real rather than a uniform grey ramp."""
+ m = probe
+ assert m["hasColorAttr"] and m["vertexColors"] is True, m
+ assert m["capN"] > 100 and m["wallN"] > 100, m
+ assert m["wallMean"] < 0.85 * m["capMean"], (
+ f"walls not shaded: cap {m['capMean']:.3f} wall {m['wallMean']:.3f}")
+ assert m["wallMean"] > 0.45 * m["capMean"], (
+ f"walls crushed to soot: {m['wallMean']:.3f}")
+ assert m["maxC"] - m["minC"] > 0.15, f"variance is flat: {m}"
+ assert m["hueMean"] > 0.004 and m["hueMax"] > 0.02, (
+ f"no warm/cool spread: mean {m['hueMean']:.4f} max {m['hueMax']:.4f}")
+
+
+def test_the_vertex_colour_can_only_darken_the_stated_albedo(probe):
+ """Law 3. `color` is the ceiling, and the default paint sits inside
+ the 0.02-0.8 linear band (0xf2f2f2 was 0.887 — a white slab under ACES
+ at exposure 1.0 with no post chain)."""
+ m = probe
+ assert m["colorHex"] == 0xE7E3DA, hex(m["colorHex"])
+ assert min(m["colorLinear"]) >= 0.02, m["colorLinear"]
+ assert max(m["colorLinear"]) <= 0.8 + 1e-6, m["colorLinear"]
+ assert m["maxC"] <= 1.0 + 1e-6, f"vertex colour brightens albedo: {m['maxC']}"
+
+
+def test_variation_zero_is_a_clean_opt_out(probe):
+ """`variation: 0` drops the attribute AND the material flag — a caller
+ who wants flat studio lettering pays nothing for the variance."""
+ m = probe
+ assert m["plainHasColorAttr"] is False, "attribute written anyway"
+ assert m["plainVertexColors"] is False, "material still reads colours"
+
+
+def test_letters_cast_shadows_and_are_never_re_seated(probe):
+ """Laws 4-5 of placement. Shadows are on by default (the glyph shadow
+ is what says "extruded" — see fx/out/signage/ground_before vs
+ ground_after, where the same letters go from pasted-on to standing on
+ the dirt) and opt-out-able; and the host's own settleScene must leave
+ a mounted line alone while it seats an unmarked crate beside it."""
+ m = probe
+ assert m["cast"] and m["recv"], m
+ assert not m["bareCast"] and not m["bareRecv"], "shadow:false ignored"
+ assert m["placement"] == "free", m["placement"]
+ assert m["signY"] == 3, f"settle dropped the lettering to {m['signY']}"
+ assert m["crateY"] < 1.0, f"control crate was not seated: {m['crateY']}"
+ assert m["settledCount"] == 1, m["settledCount"]
+
+
+def test_an_emissive_sign_carries_its_own_practical(probe):
+ """Law 4. Emissive text lights what it is bolted to; plain text adds
+ no light at all, and `light: false` is the opt-out for a facade
+ carrying dozens of signs."""
+ m = probe
+ assert m["neonChildren"] == 1 and m["lightHex"] == 0xFF2244, m
+ assert 0.05 < m["lightCd"] < 6.0, f"practical out of range: {m['lightCd']}"
+ assert m["lightZ"] > 0, "practical sits behind the glyph faces"
+ assert m["lightShadow"] is False, "a sign practical must not cast shadows"
+ assert m["plainHasLight"] is False, "non-emissive text lit something"
+ assert m["darkHasLight"] is False and m["darkChildren"] == 0, m
+
+
+def test_every_signage_material_compiles_on_the_real_renderer():
+ """Paint (vertex-coloured standard), neon (emissive + a point light)
+ and the flat opt-out are three different programs; all three must
+ build on the headless GPU."""
+ code, out = compile_scene(_SCENE, ("signage.js",))
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_sky.py b/harness/tests/scene_runtime/lib/test_sky.py
new file mode 100644
index 00000000..396f1b37
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_sky.py
@@ -0,0 +1,168 @@
+"""sky.js — the graded Preetham dome: sun-coherent, non-competing, graded for OUR renderer.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference (tests/test_sky_lib.py); the
+render-wrapper assertions are theirs. Added: the grade itself (three's Sky.js gamma-encodes
+before the tone map and rendered (240,244,246) on ACES/exposure 1.0 — measured), the night
+blend, and the CPU radiance model the environment bake shares.
+"""
+from __future__ import annotations
+
+import math
+
+import pytest
+from _probe import measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "noise.js", "sky.js", "environment.js")
+
+_PROBE = """
+import * as THREE from 'three';
+import { makeSky, skyRadiance, SKY_GRADE, nightAmount, afterglowAmount, lowSunAmount } from './lib/sky.js';
+import { sunRig, worldShell } from './lib/environment.js';
+const out = {};
+
+const s1 = new THREE.Scene();
+s1.background = new THREE.Color(0x88aacc);
+const r1 = makeSky(s1);
+const u = r1.sky.material.uniforms;
+const el = 15 * Math.PI / 180, az = 135 * Math.PI / 180;
+const expect = new THREE.Vector3(Math.cos(el) * Math.cos(az), Math.sin(el), Math.cos(el) * Math.sin(az));
+out.def = { inScene: s1.children.includes(r1.sky), bgNull: s1.background === null, isSky: r1.sky.isSky === true,
+ len: r1.sunDir.length(), dotMath: r1.sunDir.dot(expect), sunY: r1.sunDir.y,
+ turbidity: u.turbidity.value, rayleigh: u.rayleigh.value, mieC: u.mieCoefficient.value, mieG: u.mieDirectionalG.value,
+ scale: r1.sky.scale.x, uniformDot: u.sunPosition.value.clone().normalize().dot(r1.sunDir), renderOrder: r1.sky.renderOrder,
+ gain: u.uSkyGain.value, gamma: u.uSkyGamma.value, night: u.uNight.value, clouds: u.cloudCoverage ? u.cloudCoverage.value : 0 };
+
+// The patch actually rewrites three's transfer line (fails loudly if Sky.js moves it).
+const shader = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: 'uniform float mieDirectionalG;\\nvoid main() {\\n\\t\\t\\tvec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) );\\n}' };
+r1.sky.material.onBeforeCompile(shader);
+out.patch = { gainIn: /uSkyGain \\* pow\\( texColor/.test(shader.fragmentShader),
+ nightIn: /mix\\( retColor, astraNight, uNight \\)/.test(shader.fragmentShader),
+ dither: /gl_FragCoord/.test(shader.fragmentShader), uniformsBound: !!shader.uniforms.uNightZenith,
+ key: r1.sky.material.customProgramCacheKey() };
+
+const s2 = new THREE.Scene();
+const m2 = makeSky(s2, { elevationDeg: 8, azimuthDeg: 35 });
+const rig2 = sunRig({ elevation: 8, azimuth: 35, bounds: 100 });
+out.convention = { dot: m2.sunDir.dot(rig2.sun.position.clone().normalize()),
+ rigSunDirDot: rig2.sunDir.dot(rig2.sun.position.clone().normalize()), rigSunDirLen: rig2.sunDir.length() };
+
+const s3 = new THREE.Scene();
+const rig3 = sunRig({ mood: 'golden', bounds: 100 });
+const m3 = makeSky(s3, { rig: rig3 });
+out.rig = { dot: m3.sunDir.dot(rig3.sunDir), uniformDot: m3.sky.material.uniforms.sunPosition.value.clone().normalize().dot(rig3.sunDir),
+ discHidden: rig3.sunDisc.visible === false };
+
+const s4 = new THREE.Scene();
+const v = new THREE.Vector3(3, 4, 0);
+const m4 = makeSky(s4, { sunDir: v });
+out.vec = { len: m4.sunDir.length(), dot: m4.sunDir.dot(v.clone().normalize()), inputKept: v.length() === 5 };
+
+const s5 = new THREE.Scene();
+const shell = worldShell({ rand: () => 0.5 });
+s5.add(shell.group);
+const m5 = makeSky(s5, { elevationDeg: 20 });
+out.layer = { gradient: shell.group.getObjectByName('SkyGradient').renderOrder, sky: m5.sky.renderOrder,
+ ridge: shell.group.getObjectByName('HorizonRidge').renderOrder };
+
+// NIGHT: a rig with the sun set keeps its moon disc and blends the night gradient in.
+const s6 = new THREE.Scene();
+const rig6 = sunRig({ azimuth: 215, elevation: -20 });
+const m6 = makeSky(s6, { rig: rig6 });
+out.night = { amount: m6.sky.material.uniforms.uNight.value, moonKept: rig6.sunDisc.visible !== false,
+ sunBelow: m6.sunDir.y < 0, exposureOpt: makeSky(new THREE.Scene(), { exposure: 1, contrast: 1 }).sky.material.uniforms.uSkyGain.value };
+
+// Radiance model: the numbers the environment bake shares with the dome.
+const sun = new THREE.Vector3(Math.cos(38 * Math.PI / 180) * Math.cos(215 * Math.PI / 180), Math.sin(38 * Math.PI / 180), Math.cos(38 * Math.PI / 180) * Math.sin(215 * Math.PI / 180));
+const dir = (elDeg, azDeg) => new THREE.Vector3(Math.cos(elDeg * Math.PI / 180) * Math.cos(azDeg * Math.PI / 180), Math.sin(elDeg * Math.PI / 180), Math.cos(elDeg * Math.PI / 180) * Math.sin(azDeg * Math.PI / 180));
+const zen = skyRadiance(dir(89.9, 0), sun), hor = skyRadiance(dir(2, 0), sun);
+const sunSide = skyRadiance(dir(10, 215), sun), antiSide = skyRadiance(dir(10, 35), sun);
+const nightSun = dir(-20, 215);
+const nz = skyRadiance(dir(89.9, 0), nightSun), nh = skyRadiance(dir(2, 0), nightSun);
+const goldSun = dir(6, 215);
+const goldSunSide = skyRadiance(dir(8, 215), goldSun), goldAnti = skyRadiance(dir(8, 35), goldSun);
+out.model = { zen, hor, sunSide, antiSide, nz, nh, goldSunSide, goldAnti,
+ amounts: { n0: nightAmount(0.2), n1: nightAmount(-0.3), g: afterglowAmount(-0.06), gDeep: afterglowAmount(-0.4), low: lowSunAmount(0.05), high: lowSunAmount(0.6) },
+ grade: { gain: SKY_GRADE.gain, gamma: SKY_GRADE.gamma } };
+console.log(JSON.stringify(out));
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ return measure(_PROBE, _LIBS)
+
+
+def test_defaults_are_the_battery_graded_atmosphere_plus_our_grade(probe):
+ m = probe["def"]
+ assert m["isSky"]
+ assert abs(m["turbidity"] - 4.5) < 1e-9 and abs(m["rayleigh"] - 1.6) < 1e-9
+ assert abs(m["mieC"] - 0.0035) < 1e-12 and abs(m["mieG"] - 0.8) < 1e-9
+ assert m["scale"] == 4500 and m["clouds"] == 0
+ # The renderer grade: three's Sky at gain 1 is a white card on ACES/exposure 1.0.
+ assert m["gain"] == probe["model"]["grade"]["gain"] < 0.6, m
+ assert m["gamma"] == probe["model"]["grade"]["gamma"] > 1.2, m
+ assert m["night"] == 0
+
+
+def test_the_grade_patch_rewrites_the_transfer_line(probe):
+ p = probe["patch"]
+ assert p["gainIn"] and p["nightIn"] and p["dither"] and p["uniformsBound"], p
+ assert p["key"] == "astra:sky-grade"
+
+
+def test_sun_dir_is_normalized_and_matches_the_az_el_math(probe):
+ m = probe["def"]
+ assert abs(m["len"] - 1) < 1e-9 and m["dotMath"] > 1 - 1e-9
+ assert abs(m["sunY"] - math.sin(math.radians(15))) < 1e-9
+ assert m["uniformDot"] > 1 - 1e-9
+
+
+def test_the_dome_owns_the_backdrop(probe):
+ assert probe["def"]["inScene"] and probe["def"]["bgNull"]
+
+
+def test_sky_and_sun_rig_share_one_direction_convention(probe):
+ m = probe["convention"]
+ assert m["dot"] > 1 - 1e-9 and m["rigSunDirDot"] > 1 - 1e-9 and abs(m["rigSunDirLen"] - 1) < 1e-9
+
+
+def test_rig_delegation_slaves_the_dome_and_hides_the_flat_disc(probe):
+ m = probe["rig"]
+ assert m["dot"] > 1 - 1e-9 and m["uniformDot"] > 1 - 1e-9 and m["discHidden"]
+
+
+def test_explicit_sun_dir_is_normalized_and_input_untouched(probe):
+ m = probe["vec"]
+ assert abs(m["len"] - 1) < 1e-9 and m["dot"] > 1 - 1e-9 and m["inputKept"]
+
+
+def test_the_dome_layers_between_world_shell_gradient_and_ridge(probe):
+ m = probe["layer"]
+ assert m["gradient"] < m["sky"] < m["ridge"], m
+
+
+def test_a_set_sun_blends_the_night_gradient_and_keeps_the_moon(probe):
+ m = probe["night"]
+ assert m["sunBelow"] and m["amount"] == 1.0 and m["moonKept"]
+ assert m["exposureOpt"] == 1, "the ungraded dome stays reachable"
+
+
+def test_the_radiance_model_is_a_blue_gradient_brighter_toward_the_sun(probe):
+ m = probe["model"]
+ zen, hor = m["zen"], m["hor"]
+ lum = lambda c: 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2] # noqa: E731
+ assert zen[2] > zen[0] * 2, "zenith is blue"
+ assert lum(hor) > lum(zen) * 2, "horizon brighter than zenith"
+ assert lum(hor) < 1.6, "horizon not blown (linear, pre-ACES)"
+ assert lum(m["sunSide"]) > lum(m["antiSide"]) * 1.3, "haze brightens toward the sun"
+ # Night: dark, blue, horizon above zenith; both in the fog family.
+ assert lum(m["nz"]) < 0.03 and lum(m["nh"]) < 0.1 and m["nz"][2] > m["nz"][0]
+ assert lum(m["nh"]) > lum(m["nz"])
+ # Golden hour warms toward the sun: red/blue ratio higher sun-side than opposite.
+ assert m["goldSunSide"][0] / m["goldSunSide"][2] > m["goldAnti"][0] / m["goldAnti"][2]
+ a = m["amounts"]
+ assert a["n0"] == 0 and a["n1"] == 1 and a["g"] > 0.5 and a["gDeep"] == 0
+ assert a["low"] > 0.9 and a["high"] == 0
diff --git a/harness/tests/scene_runtime/lib/test_smalllife.py b/harness/tests/scene_runtime/lib/test_smalllife.py
new file mode 100644
index 00000000..9d7569c7
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_smalllife.py
@@ -0,0 +1,687 @@
+"""smalllife.js — a swarm in the air and a stand of reeds in the water.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_smalllife_lib.py). Its properties are kept whole: each field is
+ONE instanced draw call with ``position`` pinned at the origin, the stated
+bounds are the ones a shader-animated field really occupies, a swarm stays
+inside the volume it advertises, the three kinds differ in HOW THEY MOVE, the
+reeds are rooted on the caller's bed and fringe the waterline, the bend breaks
+at that line, a seed is a promise, one ``tick`` drives every material, and an
+insect at the lens fades instead of becoming the subject.
+
+Their two compile cases run through ``_probe.compile_scene``, as
+test_godrays.py's and test_flock.py's do: it stages the fixture as a
+workspace ``src/scene.js``, the shape ``runtime_js/check_shaders.mjs``
+boots.
+
+THE PORT'S OWN LAWS — each one a pair of frames rendered on this host at
+fx/out/smalllife/{before,after}{,_night}/, looked at, and measured:
+
+1. A STEM DOES NOT CAST A 12 CM SHADOW. ``shadowLike`` was applied
+ unconditionally, and a stem is 4-10 mm across while this rig's shadow map
+ is ~0.05 m/texel: a shadow that cannot be narrower than a texel is 10-30x
+ too wide. Measured on the showcase bank, 4.16% of the mud was covered in
+ hard navy dashes at luminance 0.180 against mud at 0.375, and the bank's
+ fifth percentile sat at 0.245. Casting is now opt-in exactly as grass.js's
+ blades are: 0.11% and p05 0.320 by default, the depth material still built
+ for a caller who asks.
+
+2. AN UNLIT BILLBOARD THAT IGNORES THE RIG IS A LAMP AT MIDNIGHT. The midge's
+ wing blur was a hardcoded 0.5 grey — an albedo brighter than a moonlit sky
+ — so on the night rig a midge swarm came back as a knot of pale cream
+ flecks hanging over the water (sky band, fraction over 110/255: 0.00088,
+ mean bright pixel (191, 172, 126)), and a butterfly swarm glowed orange at
+ midnight. The swarm now reads the scene's OWN lights through ``uLight``
+ (1.077/0.978/0.861 under the library's day rig, so a daylight swarm is
+ unchanged; 0.190/0.237/0.346 under its night rig), and the blur is the
+ body's own colour scattered rather than a grey card.
+
+3. A FIREFLY IS A LANTERN ON A DARK BEETLE. ``color`` was used as body albedo
+ AND glow, so 0xc8ff7a made every firefly a chartreuse dot in daylight, and
+ the flash mixed to pure white — a hard speck that reads as a dead pixel.
+ The lamp is emitted (it keeps its hue whatever the rig does), peaks at 2.6
+ rather than 1.0 so the ACES shoulder leaves it a COLOURED core, carries a
+ second wide lobe so it has a falloff, and is damped by the scene's own
+ light level; the body under it is dark and scene-lit.
+
+4. THE WATERLINE IS THE WHOLE POINT, SO IT HAS TO BE VISIBLE. The drowned
+ part faded linearly to 0.55 m, which on a fringe stand left no underwater
+ at all: measured over the close frame, stem pixels below the surface were
+ 41% darker than the emergent ones and MORE saturated (0.131 against 0.150).
+ Exponential extinction, a wider wet skin and a meniscus that reads the
+ water's own colour take that to 49% darker and 0.117 against 0.186.
+
+5. A STAND IS NOT ONE GREEN. Last year's bleached stems are mixed in per stem
+ (a minority — ``pow(rand(), 2.4)``), each stem carries its own hue and
+ value, the seed head has its own hue, value and grain instead of three
+ thousand identical chocolate cigars, the metre-scale field is grass.js's
+ own ``astraHueBreak`` on the ROOT position so a stand and the meadow it
+ fringes patch together, and a backlit stem passes light like the straw it
+ is (the term grass.js's port added, read off the scene's key light) —
+ everywhere except the seed head, which is packed felt and lit up as a
+ brick-red ember the first time it was left in.
+"""
+
+from __future__ import annotations
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure # noqa: F401
+
+# smalllife shares grass.js's wind reader, so one `wind` option moves a
+# meadow and its shallows as one.
+_LIBS = ("shader.js", "noise.js", "grass.js", "smalllife.js")
+
+# Run a patched built-in's compile chain the way three does, and hand back
+# the GLSL — the structure of a patch is readable without a GPU.
+_COMPILE = """
+const compile = (mat) => {
+ const shader = {
+ uniforms: {},
+ vertexShader: '#include <begin_vertex>\\n',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}\\n',
+ };
+ mat.onBeforeCompile(shader, {});
+ return shader;
+};
+"""
+
+# The scene our check_shaders.mjs boots. Fog, so `USE_FOG` is defined and
+# every fog branch in three custom shaders is real GLSL rather than nothing;
+# a shadow-CASTING directional light, or the reeds' displaced depth material
+# is never compiled and `NUM_DIR_LIGHTS > 0` never opens; and a camera,
+# because a scene with none is reported as not booted.
+_SCENE = """
+import * as THREE from 'three';
+import { makeInsects, makeReeds } from './lib/smalllife.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 20, 20] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xc9d6e0, 0.02);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ const sun = new THREE.DirectionalLight(0xffffff, 2.0);
+ sun.position.set(6, 9, 4);
+ sun.castShadow = true;
+ scene.add(sun);
+ const bugs = [];
+ for (const kind of ['midge', 'butterfly', 'firefly']) {
+ const g = makeInsects({ kind, count: 40, extent: 3, height: 2, seed: 4 });
+ bugs.push(g);
+ scene.add(g);
+ }
+ // shadows on, or the depth patch this scene is here to prove is dead code
+ const reeds = makeReeds({ extent: 6, density: 20, height: 1.6,
+ waterY: 0.4, shadows: true,
+ heightAt: (x, z) => -0.3 + 0.04 * x, seed: 2 });
+ scene.add(reeds);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [8, 4, 10], lookAt: [0, 1, 0],
+ fov: 45 }],
+ update(t) {
+ for (const g of bugs) g.userData.tick(t);
+ reeds.userData.tick(t);
+ },
+ };
+}
+"""
+
+
+def test_every_shader_compiles_in_a_fogged_scene_that_casts():
+ """Three billboard shaders that build every position from a seed, plus a
+ patched built-in whose vertex body replaces `transformed`, rewrites
+ `vNormal` and adds to `totalEmissiveRadiance` — and the depth material
+ that has to run the same displacement. Only the GPU can say that GLSL
+ is legal. An UNFOGGED scene proves much less: `USE_FOG` undefined is how
+ rain.js shipped six compile errors for months."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert '"errors":[]' in out, out
+ # A WARN here is the fog trap or the GTAO trap: both ship an effect that
+ # looks wrong rather than one that errors.
+ assert "WARN" not in out and '"warnings":[]' in out, out
+ # The static half of the audit reads THIS FILE, not the string the
+ # wrapper assembles, and it only sees quoted GLSL of 40 characters or
+ # more: `uTime` used but "undeclared"/"unbound" was two hard errors
+ # against every shader in the module until the declaration and the
+ # binding were written where that audit can see them.
+ assert "undeclared_uniform" not in out and "unbound_uniform" not in out
+
+
+def test_each_field_is_one_draw_call_with_position_at_the_origin():
+ """The bet both libraries make: instances are free, meshes are not. And
+ GTAOPass redraws with an override material that ignores custom vertex
+ shaders, so a quad or a stem left in `position` would stack every copy at
+ the world origin and burn a black slab there."""
+ out = measure("""
+import { makeInsects, makeReeds } from './lib/smalllife.js';
+const shape = (g) => {
+ const drawn = [];
+ g.traverse((o) => { if (o.isMesh || o.isPoints) drawn.push(o); });
+ const m = drawn[0], geo = m.geometry;
+ return {
+ meshes: drawn.length,
+ instanced: !!geo.isInstancedBufferGeometry,
+ groups: geo.groups.length,
+ materials: [].concat(m.material).length,
+ instances: geo.instanceCount,
+ verts: geo.attributes.position.count,
+ posAllZero: Array.from(geo.attributes.position.array)
+ .every((v) => v === 0),
+ hasCorner: !!geo.attributes.aCorner,
+ };
+};
+console.log(JSON.stringify({
+ small: shape(makeInsects({ count: 100 })),
+ big: shape(makeInsects({ count: 20000 })),
+ reeds: shape(makeReeds({ extent: 8, density: 40 })),
+}));
+""", _LIBS)
+ for k in ("small", "big", "reeds"):
+ f = out[k]
+ assert f["meshes"] == 1, out
+ assert f["instanced"] and f["materials"] == 1, out
+ # Geometry groups are per-material sub-draws: one draw call means
+ # none of them.
+ assert f["groups"] == 0, out
+ assert f["posAllZero"] and f["hasCorner"], out
+ assert out["small"]["verts"] == out["big"]["verts"], out
+ assert out["small"]["instances"] == 100
+ assert out["big"]["instances"] == 20000
+ assert out["reeds"]["instances"] > 1000, out
+
+
+def test_the_stated_sphere_covers_the_whole_field():
+ """`position` is all zeros, so the bounds three would derive are a point
+ at the origin — and three CULLS on the sphere, so a swarm off to one side
+ would vanish the moment the origin left the frame."""
+ out = measure("""
+import { makeInsects, makeReeds } from './lib/smalllife.js';
+const cover = (geo, pts) => {
+ const b = geo.boundingBox, s = geo.boundingSphere;
+ let worstBox = -1e9, worstSphere = -1e9;
+ for (const p of pts) {
+ worstBox = Math.max(worstBox, b.min.x - p[0], p[0] - b.max.x,
+ b.min.y - p[1], p[1] - b.max.y,
+ b.min.z - p[2], p[2] - b.max.z);
+ const d = Math.hypot(p[0] - s.center.x, p[1] - s.center.y,
+ p[2] - s.center.z);
+ worstSphere = Math.max(worstSphere, d - s.radius);
+ }
+ return { worstBox, worstSphere, radius: s.radius,
+ center: s.center.toArray(), box: [b.min.toArray(),
+ b.max.toArray()] };
+};
+const g = makeInsects({ kind: 'midge', count: 300, extent: 5, height: 3,
+ center: [40, 9, -25], seed: 6 }).children[0];
+const ip = g.geometry.attributes.iPos.array;
+const bugs = [];
+for (let i = 0; i < g.geometry.instanceCount; i++) {
+ bugs.push([ip[i * 3], ip[i * 3 + 1], ip[i * 3 + 2]]);
+}
+const bed = (x, z) => -0.4 + 0.05 * x;
+const r = makeReeds({ extent: 10, density: 30, height: 2, waterY: 0.2,
+ heightAt: bed, seed: 3 }).children[0];
+const rp = r.geometry.attributes.iPos.array;
+const rs = r.geometry.attributes.iShape.array;
+const stems = [];
+for (let i = 0; i < r.geometry.instanceCount; i++) {
+ stems.push([rp[i * 3], rp[i * 3 + 1], rp[i * 3 + 2]]);
+ stems.push([rp[i * 3], rp[i * 3 + 1] + rs[i * 4], rp[i * 3 + 2]]);
+}
+console.log(JSON.stringify({
+ insects: cover(g.geometry, bugs), reeds: cover(r.geometry, stems),
+}));
+""", _LIBS)
+ for k in ("insects", "reeds"):
+ assert out[k]["worstBox"] <= 1e-6, out
+ assert out[k]["worstSphere"] <= 1e-6, out
+ # instancedQuad's 1e4 placeholder would "cover" anything and cull
+ # nothing; a stated sphere has to be the real one.
+ assert out[k]["radius"] < 100, out
+ # The swarm is 47 m from the group origin: the sphere has to travel with
+ # it, not sit at the origin hoping to reach.
+ assert out["insects"]["center"][0] > 35, out
+ assert out["reeds"]["box"][0][1] < 0, out
+
+
+def test_a_swarm_stays_inside_the_volume_it_advertises():
+ """Every position is computed in the shader from `uTime`, so the bounding
+ box is a PROMISE the CPU has to keep: base position, own wander, the
+ swarm's drift and the quad's own span all have to fit inside `center` +-
+ (extent, height/2, extent) at every t."""
+ out = measure("""
+import { makeInsects } from './lib/smalllife.js';
+const half = [5, 1.5, 5], c = [12, 7, -9];
+const check = (kind) => {
+ const m = makeInsects({ kind, count: 500, extent: half[0],
+ height: half[1] * 2, center: c, seed: 3 })
+ .children[0];
+ const geo = m.geometry, u = m.material.uniforms;
+ const p = geo.attributes.iPos.array, a = geo.attributes.iAmp.array;
+ const s = geo.attributes.iSeed.array;
+ const drift = [u.uDrift.value.x, u.uDrift.value.y, u.uDrift.value.z];
+ let worst = -1e9;
+ for (let i = 0; i < geo.instanceCount; i++) {
+ // The quad is camera-facing, so its half diagonal can point any way at
+ // all: sqrt(2) times the largest half edge.
+ const q = u.uSize.value * s[i * 4 + 2] * Math.SQRT2;
+ for (let k = 0; k < 3; k++) {
+ worst = Math.max(worst, Math.abs(p[i * 3 + k] - c[k])
+ + a[i * 3 + k] + drift[k] + q - half[k]);
+ }
+ }
+ const b = geo.boundingBox;
+ return { worst, box: [b.min.toArray(), b.max.toArray()] };
+};
+console.log(JSON.stringify({
+ midge: check('midge'), butterfly: check('butterfly'),
+ firefly: check('firefly'),
+}));
+""", _LIBS)
+ for kind in ("midge", "butterfly", "firefly"):
+ assert out[kind]["worst"] < 0, (kind, out)
+ assert out[kind]["box"] == [[7, 5.5, -14], [17, 8.5, -4]], out
+
+
+def test_the_three_kinds_actually_differ_in_motion():
+ """The only thing that separates them is HOW THEY MOVE — the mesh is one
+ quad in all three cases. A midge jitters a few centimetres inside a knot
+ that itself travels; a butterfly patrols half the field on its own and
+ never travels as a group; a firefly is the slow one, and its `beat` is a
+ blink rather than a wingbeat."""
+ out = measure("""
+import { makeInsects } from './lib/smalllife.js';
+const stats = (kind) => {
+ const m = makeInsects({ kind, count: 400, extent: 4, height: 2,
+ seed: 5 }).children[0];
+ const g = m.geometry, u = m.material.uniforms;
+ const p = g.attributes.iPos.array, a = g.attributes.iAmp.array;
+ let amp = 0, reach = 0;
+ for (let i = 0; i < g.instanceCount; i++) {
+ const w = Math.hypot(a[i * 3], a[i * 3 + 2]);
+ amp += w;
+ reach += Math.hypot(p[i * 3], p[i * 3 + 2]) + w;
+ }
+ return { kind: u.uKind.value, rate: u.uRate.value, beat: u.uBeat.value,
+ drift: u.uDrift.value.length(),
+ amp: amp / g.instanceCount, reach: reach / g.instanceCount };
+};
+console.log(JSON.stringify({
+ midge: stats('midge'), butterfly: stats('butterfly'),
+ firefly: stats('firefly'),
+}));
+""", _LIBS)
+ mi, bu, fi = out["midge"], out["butterfly"], out["firefly"]
+ assert {mi["kind"], bu["kind"], fi["kind"]} == {0, 1, 2}
+ # A midge: fast, tight, and carried by a knot that goes somewhere.
+ assert mi["rate"] > 4 * fi["rate"], out
+ assert mi["amp"] < 0.15 * 4 and mi["reach"] < 0.4 * 4, out
+ assert mi["drift"] > 0.3 * 4, out
+ # A butterfly: its own wide patrol, and no swarm to be carried by.
+ assert bu["amp"] > 0.4 * 4 and bu["reach"] > 0.7 * 4, out
+ assert bu["drift"] == 0 and fi["drift"] == 0, out
+ # A firefly: the slow one, blinking rather than beating.
+ assert fi["rate"] < 0.5 * bu["rate"] < mi["rate"], out
+ assert fi["beat"] < 3 < 10 < bu["beat"], out
+ for a, b in ((mi, bu), (mi, fi), (bu, fi)):
+ keys = ("rate", "beat", "drift", "amp")
+ assert sum(a[k] != b[k] for k in keys) >= 3, out
+
+
+def test_the_reeds_are_rooted_on_the_callers_bed():
+ """A reed that ignores `heightAt` floats over the bed or sinks into it —
+ and it is the bed, not the waterline, that a root sits on."""
+ out = measure("""
+import { makeReeds } from './lib/smalllife.js';
+// A ruled slope, so equal bands of height cover equal ground and the stem
+// counts in them can be compared straight across.
+const bed = (x, z) => 0.12 * x;
+const g = makeReeds({ extent: 12, density: 25, height: 1.6, waterY: 0,
+ heightAt: bed, seed: 8 }).children[0].geometry;
+const p = g.attributes.iPos.array, s = g.attributes.iShape.array;
+let err = 0, subErr = 0, aboveFar = 0, nearAbove = 0, nearBelow = 0;
+for (let i = 0; i < g.instanceCount; i++) {
+ const x = p[i * 3], y = p[i * 3 + 1], z = p[i * 3 + 2];
+ err = Math.max(err, Math.abs(y - bed(x, z)));
+ const want = Math.max(0, Math.min(1, -y / s[i * 4]));
+ subErr = Math.max(subErr, Math.abs(s[i * 4 + 2] - want));
+ if (y > 0.3) aboveFar++;
+ else if (y > 0) nearAbove++;
+ else if (y > -0.3) nearBelow++;
+}
+const flat = makeReeds({ extent: 6, density: 20 }).children[0].geometry;
+const fp = flat.attributes.iPos.array;
+let flatMax = 0;
+for (let i = 1; i < fp.length; i += 3) flatMax = Math.max(flatMax, fp[i]);
+console.log(JSON.stringify({
+ err, subErr, aboveFar, nearAbove, nearBelow, flatMax,
+ n: g.instanceCount,
+}));
+""", _LIBS)
+ assert out["err"] < 1e-6, out
+ # The submerged fraction the shader breaks its bend at is measured from
+ # the same bed, or the break lands nowhere near the surface.
+ assert out["subErr"] < 1e-6, out
+ assert out["nearBelow"] > 100, out
+ # Reeds FRINGE water: they thin out over the wet bank and stop entirely
+ # above it, which is what makes a stand follow a shoreline instead of
+ # marching up the slope as a square patch.
+ assert out["aboveFar"] == 0, out
+ assert 0.2 < out["nearAbove"] / out["nearBelow"] < 0.75, out
+ # No heightAt: the bed is flat y = 0.
+ assert out["flatMax"] == 0, out
+
+
+def test_the_bend_breaks_at_the_waterline():
+ """The cue that says "standing in water": the submerged stem takes a
+ fraction of the surface bend, on a slower sway. Both numbers are
+ per-stem attributes and uniforms rather than claims about GLSL, so the
+ CPU and the shader cannot drift apart on them."""
+ out = measure("""
+import { makeReeds } from './lib/smalllife.js';
+const g = makeReeds({ extent: 10, density: 25, height: 1.8, waterY: 0.4,
+ heightAt: (x, z) => -0.5 + 0.03 * x, seed: 5,
+ wind: { strength: 1.2, speed: 1 } });
+const mesh = g.children[0];
+const b = mesh.geometry.attributes.iBend.array;
+const u = mesh.material.userData.uniforms;
+let ratio = -1, minAbove = 1e9, zeroBelow = 0;
+for (let i = 0; i < mesh.geometry.instanceCount; i++) {
+ ratio = Math.max(ratio, b[i * 4 + 1] / b[i * 4]);
+ minAbove = Math.min(minAbove, b[i * 4]);
+ if (b[i * 4 + 1] <= 0) zeroBelow++;
+}
+const calm = makeReeds({ extent: 6, density: 20, wind: 0.5 })
+ .children[0].geometry.attributes.iBend.array;
+console.log(JSON.stringify({
+ ratio, minAbove, zeroBelow,
+ rate: u.uReedRate.value.toArray(),
+ water: u.uReedWater.value,
+ windScales: calm[0] / b[0],
+}));
+""", _LIBS)
+ # Less bend below the line than above it, on every stem, and not by a
+ # hair: water damps hard.
+ assert 0 < out["ratio"] < 0.4, out
+ # Still a living stem down there, not a frozen post.
+ assert out["zeroBelow"] == 0 and out["minAbove"] > 0, out
+ # And SLOWER: the submerged sway runs at well under the surface's rate,
+ # which is what makes it read as rounder.
+ assert out["rate"][1] < 0.5 * out["rate"][0], out
+ assert out["water"] == 0.4, out
+ # The one wind option scales both, so grass and reeds share it.
+ assert 0.2 < out["windScales"] < 0.8, out
+
+
+def test_two_fields_with_one_seed_are_identical():
+ """Determinism is the contract for every shipped factory: a re-run that
+ reshuffles the swarm is a re-run nobody can compare against."""
+ out = measure("""
+import { makeInsects, makeReeds } from './lib/smalllife.js';
+const bugs = (s) => JSON.stringify(['iPos', 'iAmp', 'iSeed'].map((k) =>
+ Array.from(makeInsects({ kind: 'butterfly', count: 80, seed: s })
+ .children[0].geometry.attributes[k].array)));
+const reeds = (s) => JSON.stringify(['iPos', 'iShape', 'iBend'].map((k) =>
+ Array.from(makeReeds({ extent: 5, density: 30, seed: s })
+ .children[0].geometry.attributes[k].array)));
+console.log(JSON.stringify({
+ bugsSame: bugs(4) === bugs(4), bugsDiffer: bugs(4) !== bugs(9),
+ reedsSame: reeds(4) === reeds(4), reedsDiffer: reeds(4) !== reeds(9),
+ n: JSON.parse(bugs(4))[0].length,
+}));
+""", _LIBS)
+ assert out["bugsSame"] and out["bugsDiffer"], out
+ assert out["reedsSame"] and out["reedsDiffer"], out
+ assert out["n"] == 240, out
+
+
+def test_tick_advances_every_material():
+ """Every moving part lives in the vertex shader, so an un-advanced uTime
+ is not a still swarm — it is a swarm frozen mid-flight and a stand frozen
+ mid-gust, which reads as a photograph of a model."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeInsects, makeReeds } from './lib/smalllife.js';
+const g = new THREE.Group();
+for (const kind of ['midge', 'butterfly', 'firefly']) {
+ g.add(makeInsects({ kind, count: 30, seed: 2 }));
+}
+g.add(makeReeds({ extent: 4, density: 20 }));
+const times = () => {
+ const out = [];
+ g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (!m) continue;
+ const u = (m.uniforms && m.uniforms.uTime) ? m.uniforms
+ : (m.userData && m.userData.uniforms);
+ if (u && u.uTime) out.push(u.uTime.value);
+ }
+ });
+ return out;
+};
+const before = times();
+for (const c of g.children) c.userData.tick(2.5);
+console.log(JSON.stringify({ before, after: times() }));
+""", _LIBS)
+ assert out["before"] == [0, 0, 0, 0], out
+ assert out["after"] == [2.5] * 4, out
+
+
+def test_an_insect_at_the_lens_fades_instead_of_becoming_the_subject():
+ """A swarm is a VOLUME, and a camera inside one gets an insect at arm's
+ length. Measured on a delivered meadow: the hero camera sat inside a
+ 32 m butterfly swarm, a 17 cm butterfly 1 m from the lens covered a
+ quarter of a 40 deg frame, and the judge marked the whole scene's scale
+ down for it. No lens focuses at 30 cm either, so the close ones must
+ fade — in the shader, where every swarm gets it, not in a rule each
+ caller has to remember."""
+ src = (LIB_DIR / "smalllife.js").read_text(encoding="utf-8")
+ # The fade is measured from the INSTANCE centre in world space, not from
+ # the mesh origin: every insect in one swarm shares that.
+ assert "distance(cameraPosition, cW)" in src
+ assert "vNear = smoothstep(0.35, 1.8" in src
+ # And it must actually reach the alpha, not just be computed.
+ assert "a *= vNear;" in src
+
+
+# --------------------------------------------------------------------------
+# The port's own laws.
+# --------------------------------------------------------------------------
+
+
+def test_stem_shadows_are_opt_in_and_complete_when_asked():
+ """LAW 1. This rig's shadow map is ~0.05 m/texel and a stem is 4-10 mm
+ across, so a cast stem shadow cannot be narrower than 10-30 stems: a
+ stand of 3 000 painted 4.16% of the showcase bank with hard navy dashes
+ at 0.180 against mud at 0.375. Off by default, exactly as grass.js's
+ blades are. Asked for, it must still be COMPLETE — three's shadow pass
+ draws with its own MeshDepthMaterial, which never sees patchStandard, so
+ an unpatched stand casts NOTHING, and a depth patch owning its own
+ uniforms would freeze the shadow at t = 0 while the stand keeps
+ swaying."""
+ out = measure("""
+import { makeReeds } from './lib/smalllife.js';
+const shape = (opts) => {
+ const g = makeReeds(Object.assign(
+ { extent: 6, density: 20, height: 1.6, waterY: 0.4, seed: 2 }, opts));
+ let stems;
+ g.traverse((o) => { if (o.name === 'Stems') stems = o; });
+ return {
+ casts: stems.castShadow === true,
+ receives: stems.receiveShadow === true,
+ hasDepth: !!stems.customDepthMaterial,
+ shared: !!stems.customDepthMaterial
+ && stems.customDepthMaterial.userData.uniforms
+ === stems.material.userData.uniforms,
+ };
+};
+console.log(JSON.stringify({
+ off: shape({}), on: shape({ shadows: true }),
+ truthy: shape({ shadows: 1 }),
+}));
+""", _LIBS)
+ assert out["off"] == {"casts": False, "receives": True,
+ "hasDepth": False, "shared": False}, out
+ assert out["on"] == {"casts": True, "receives": True,
+ "hasDepth": True, "shared": True}, out
+ # Opt-IN, not opt-out: only `true` turns a cost like this on.
+ assert out["truthy"]["casts"] is False, out
+
+
+def test_a_swarm_reads_the_rig_it_was_added_to():
+ """LAW 2. An insect is an unlit billboard, so without this its hex is
+ its colour at every hour — and the midge's blur was a 0.5 grey, an albedo
+ brighter than a moonlit sky. The daylight number has to land on ~1, or
+ every existing swarm changes brightness; the night one has to be well
+ under it AND blue, because that is what the rig is."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeInsects } from './lib/smalllife.js';
+const under = (lights) => {
+ const scene = new THREE.Scene();
+ for (const l of lights) scene.add(l);
+ const g = makeInsects({ kind: 'midge', count: 20, seed: 1 });
+ scene.add(g);
+ const u = g.children[0].material.uniforms.uLight.value;
+ const loose = makeInsects({ kind: 'midge', count: 20, seed: 1 });
+ loose.userData.tick(0.5);
+ g.userData.tick(0.5);
+ return { lit: u.toArray(),
+ unattached: loose.children[0].material.uniforms.uLight.value
+ .toArray() };
+};
+// The library's own rigs, from environment.js RIGS.
+const day = under([new THREE.DirectionalLight(0xfff0d8, 5.4),
+ new THREE.HemisphereLight(0x9db8e8, 0x8a7f6a, 1.4)]);
+const night = under([new THREE.DirectionalLight(0xb5c7e8, 2.2),
+ new THREE.HemisphereLight(0x3f5378, 0x2a2a33, 1.0)]);
+const dark = under([]);
+const many = under(Array.from({ length: 12 },
+ () => new THREE.PointLight(0xffffff, 60)));
+console.log(JSON.stringify({ day, night, dark, many }));
+""", _LIBS)
+ # Never touched by a scene: the neutral it was built with, which is what
+ # an asset preview with no lights in it wants.
+ assert out["day"]["unattached"] == [1, 1, 1], out
+ assert out["dark"]["lit"] == [1, 1, 1], out
+ day, night = out["day"]["lit"], out["night"]["lit"]
+ # Daylight lands on 1.0 to within a tenth, warm: an existing swarm keeps
+ # the look it was tuned with.
+ assert all(0.8 < v < 1.2 for v in day), out
+ assert day[0] > day[1] > day[2], out
+ # Night is a THIRD of it, and blue — the moon is not a small sun.
+ assert max(night) < 0.4, out
+ assert night[2] > night[1] > night[0], out
+ assert sum(night) < 0.4 * sum(day), out
+ # And a rig with a dozen lamps in it is not a reason for a midge to
+ # become one.
+ assert all(v <= 2.5 for v in out["many"]["lit"]), out
+
+
+def test_the_firefly_is_a_lantern_and_the_others_are_lit_animals():
+ """LAW 3. The blink is EMITTED — it keeps its hue whatever the rig is
+ doing, peaks past white so the ACES shoulder leaves it a coloured core
+ rather than a flat white dot, and carries a second wide lobe so it reads
+ as a glow. The body under it is dark and scene-lit, or `color` doubles
+ as a near-white albedo and a daylit firefly is a chartreuse dot whether
+ it is flashing or not."""
+ src = (LIB_DIR / "smalllife.js").read_text(encoding="utf-8")
+ # Emitted, hue-preserving, and bloom-friendly rather than clipped.
+ assert "vec3 lamp = col / max(max(col.r, max(col.g, col.b)), 1e-3);" in src
+ assert "vec3 hot = mix(lamp, vec3(1.0, 0.97, 0.86), 0.42) * 2.6;" in src
+ # Two lobes: a core AND a falloff.
+ assert "0.74 * exp(-d * d * 9.0) + 0.32 * exp(-d * d * 1.5)" in src
+ # The body is dark and reads the rig; the lamp is damped when the rig is
+ # bright, because a lantern is only seen when it beats its background.
+ assert "vec3 body = mix(vec3(dot(col, vec3(0.3333))), col, 0.4) * 0.2;" \
+ in src
+ assert "col = mix(body * uLight, hot, lit);" in src
+ assert "float dim = 1.0 - clamp(dot(uLight, vec3(0.5)), 0.0, 1.0);" in src
+ # The other two are lit animals, not emitters.
+ assert "col = mix(haze, col, body) * uLight;" in src
+ assert "col *= (0.72 + 0.42 * abs(cos(vBeat))) * uLight;" in src
+ # And the blur that made a night swarm glow is gone.
+ assert "vec3(0.5, 0.5, 0.46)" not in src
+
+
+def test_the_waterline_and_the_stands_three_scales_of_colour():
+ """LAWS 4 and 5, read off the GLSL the patch chain really emits. The
+ drowned stem loses its colour EXPONENTIALLY (a linear ramp to 0.55 m left
+ a fringe stand with no underwater at all), the meniscus reads the water's
+ own tint rather than a fixed white, the stand carries dry stems, per-stem
+ hue and value and a metre-scale field on the ROOT position, and the
+ backlight term reads the scene's key light — everywhere but the seed
+ head, which is packed felt and lit up as a brick-red ember when it was
+ left in."""
+ out = measure(_COMPILE + """
+import { makeReeds } from './lib/smalllife.js';
+const g = makeReeds({ extent: 6, density: 20, waterY: 0.4,
+ waterColor: 0x123344, dryColor: 0x998855, seed: 3 });
+let stems;
+g.traverse((o) => { if (o.name === 'Stems') stems = o; });
+const s = compile(stems.material);
+const u = stems.material.userData.uniforms;
+console.log(JSON.stringify({
+ frag: s.fragmentShader,
+ vert: s.vertexShader,
+ deep: u.uReedDeep.value.getHex(),
+ dry: u.uReedDry.value.getHex(),
+}));
+""", _LIBS)
+ f, v = out["frag"], out["vert"]
+ # The caller's own water and straw, not two hexes baked into the GLSL.
+ assert out["deep"] == 0x123344 and out["dry"] == 0x998855, out["deep"]
+ # LAW 4: exponential extinction below the line, a wet skin above it, and
+ # a meniscus in the water's hue.
+ assert "1.0 - exp(min(vReed.z, 0.0) * 3.6)" in f, f
+ assert "1.0 - 0.42 * (1.0 - smoothstep(0.0, 0.085, vReed.z))" in f, f
+ assert "rdCol += (uReedDeep + vec3(0.1, 0.11, 0.1)) * 0.55" in f, f
+ # LAW 5: three scales of colour, and the field is read at the root.
+ assert "mix(uReedColor, uReedDry, vReedVar.z)" in f, f
+ assert "astraHueShift(rdCol, vReedVar.x)" in f, f
+ assert "astraHueBreak(rdCol, vReedW, 0.5, 0.34)" in f, f
+ assert "vReedW = rdRoot.xz;" in v, v
+ assert "rdCol *= 0.82 + 0.36 * vReedVar.y;" in f, f
+ # The head has its own hue, value and grain.
+ assert "astraHueShift(uReedHead, vReedVar.x * 0.7)" in f, f
+ # Translucency off the scene's OWN key light, guarded, and all but shut
+ # off on the seed head.
+ assert "#if NUM_DIR_LIGHTS > 0" in f, f
+ assert "directionalLights[0].direction" in f, f
+ assert "totalEmissiveRadiance += directionalLights[0].color * rdSap" in f
+ assert "(1.0 - 0.86 * rdIsHead)" in f, f
+
+
+def test_dead_stems_are_a_minority_that_runs_to_the_edges():
+ """LAW 5's one number. Dryness is a fourth `iVar` component, and a
+ LINEAR roll would bleach half the stand: a stand is this year's growth
+ with last year's straw standing in it, not a fifty-fifty mix."""
+ out = measure("""
+import { makeReeds } from './lib/smalllife.js';
+const g = makeReeds({ extent: 12, density: 25, seed: 6 }).children[0];
+const a = g.geometry.attributes.iVar;
+const v = a.array;
+let sum = 0, wet = 0, dead = 0, minV = 1e9, maxV = -1e9;
+for (let i = 0; i < g.geometry.instanceCount; i++) {
+ const d = v[i * 4 + 3];
+ sum += d;
+ if (d < 0.2) wet++;
+ if (d > 0.7) dead++;
+ minV = Math.min(minV, d); maxV = Math.max(maxV, d);
+}
+console.log(JSON.stringify({
+ size: a.itemSize, n: g.geometry.instanceCount,
+ mean: sum / g.geometry.instanceCount,
+ wetFrac: wet / g.geometry.instanceCount,
+ deadFrac: dead / g.geometry.instanceCount, minV, maxV,
+}));
+""", _LIBS)
+ assert out["size"] == 4, out
+ # Most of the stand is green, a tail of it is straw, and both ends of
+ # the range are actually reached.
+ assert 0.2 < out["mean"] < 0.36, out
+ assert out["wetFrac"] > 0.4, out
+ assert 0.03 < out["deadFrac"] < 0.2, out
+ assert out["minV"] < 0.02 and out["maxV"] > 0.95, out
diff --git a/harness/tests/scene_runtime/lib/test_strata.py b/harness/tests/scene_runtime/lib/test_strata.py
new file mode 100644
index 00000000..ed4c4187
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_strata.py
@@ -0,0 +1,928 @@
+"""strata.js: the bedding and the rain runs, and the chain they land in.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_strata_lib.py). Their renderer-contract assertions are dropped;
+the geology claims, the shared-name contract and the option-is-a-uniform law
+are kept, and the two things this port added are pinned so a later edit
+cannot quietly undo them:
+
+* the palette is solved against a MEASURED light. `sunRig`'s fill plus a
+ blue-sky environment puts linear (1, 1.56, 2.45) on a shaded vertical
+ face — a neutral grey albedo renders (88, 110, 134) there — so every bed
+ and every stain tone has to beat that ratio or the cliff comes back
+ cyan-green, which is what the reference palette did on our host;
+* every mark varies in HUE, not only in value: the bed grain, the foot of a
+ bed, the parting and the two minerals in a run.
+
+Both patches exist to go ON TOP of a cliff that already wears
+`patchTriplanar` / `patchSlopeSplat` and usually `patchMicroBreakup`, so the
+shared contract is asserted first — one world base, no name a neighbour owns,
+every option a uniform rather than baked GLSL — and then the geology. Two
+claims are checked by NUMBERS rather than by reading the source: the bed
+stack is walked with the shipped uniforms and the constants pulled out of the
+compiled GLSL, because "thickness varies" and "two cliffs share one bedding
+plane" are statements about a sequence of metres and a regex sees neither.
+"""
+from __future__ import annotations
+
+import json
+import re
+from collections import Counter
+
+import pytest
+from _probe import LIB_DIR, compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "terrain_shade.js", "waterside.js", "surface_wear.js",
+ "aging.js", "strata.js")
+
+_LIB_SRC = (LIB_DIR / "strata.js").read_text(encoding="utf-8")
+
+# The patch only exists inside onBeforeCompile, so every probe hands it
+# the two chunks patchStandard replaces and reads back what it wrote.
+_PRELUDE = """
+import * as THREE from 'three';
+import { patchRockStrata, patchErosionStreaks } from './lib/strata.js';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+import { patchShoreWet, patchShoreFoam } from './lib/waterside.js';
+import { patchDripStains, patchRust, patchDust } from './lib/aging.js';
+
+const std = (o = {}) => new THREE.MeshStandardMaterial(
+ Object.assign({ color: 0x8a8071, roughness: 0.9 }, o));
+
+function compile(mat) {
+ const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+ };
+ mat.onBeforeCompile(shader);
+ return shader;
+}
+
+const count = (src, needle) => src.split(needle).length - 1;
+"""
+
+# GLSL_UTIL's noise, transliterated once so a probe can WALK the bed
+# stack the shader builds. Every constant that shapes it is read out of
+# the compiled source instead of being repeated here.
+_STACK = """
+const fr = (x) => x - Math.floor(x);
+function hash21(x, y) {
+ let a = fr(x * 0.1031), b = fr(y * 0.1031), c = fr(x * 0.1031);
+ const d = a * (b + 33.33) + b * (c + 33.33) + c * (a + 33.33);
+ a += d; b += d; c += d;
+ return fr((a + b) * c);
+}
+function noise2(x, y) {
+ const ix = Math.floor(x), iy = Math.floor(y);
+ let fx = x - ix, fy = y - iy;
+ fx = fx * fx * (3 - 2 * fx); fy = fy * fy * (3 - 2 * fy);
+ const a = hash21(ix, iy), b = hash21(ix + 1, iy);
+ const c = hash21(ix, iy + 1), d = hash21(ix + 1, iy + 1);
+ return (a + (b - a) * fx) * (1 - fy) + (c + (d - c) * fx) * fy;
+}
+function fbm(x, y) {
+ let s = 0, a = 0.5;
+ for (let i = 0; i < 3; i++) {
+ s += a * noise2(x, y); x *= 2.02; y *= 2.02; a *= 0.5;
+ }
+ return Math.min(1, Math.max(0, s / 0.875));
+}
+const grab = (src, re) => {
+ const m = re.exec(src);
+ if (!m) throw new Error('not in the shipped GLSL: ' + re);
+ return m.slice(1).map(Number);
+};
+
+/** The bed the shader would pick at a world point, from ITS numbers. */
+function bedder(mat) {
+ const fs = compile(mat).fragmentShader;
+ const [lat] = grab(fs, /astraStrataFbm\\(vAstraWorld\\.xz \\* ([\\d.]+)\\s*\\+ uStrataSeed\\.xz\\) - 0\\.5\\) \\* uStrataJit/);
+ const [wf, wa] = grab(fs, /astraStrataFbm\\(vec2\\(stB \\* ([\\d.]+), uStrataSeed\\.y\\)\\) - 0\\.5\\)\\s*\\* ([\\d.]+)/);
+ const [off] = grab(fs, /astraStrataFloor\\(float k, float s\\) \\{\\s*return k \\+ \\(astraHash21\\(vec2\\(k, s\\)\\) - 0\\.5\\) \\* ([\\d.]+);/);
+ const u = mat.userData.uniforms;
+ const up = u.uStrataUp.value, sp = u.uStrataSpacing.value;
+ const jit = u.uStrataJit.value, sd = u.uStrataSeed.value;
+ const bedFloor = (k) => k + (hash21(k, sd.z) - 0.5) * off;
+ return (x, y, z) => {
+ let b = (x * up.x + y * up.y + z * up.z) / sp;
+ b += (fbm(x * lat + sd.x, z * lat + sd.z) - 0.5) * jit;
+ b += (fbm(b * wf, sd.y) - 0.5) * wa;
+ let i = Math.floor(b), lo = bedFloor(i);
+ if (b < lo) { i -= 1; lo = bedFloor(i); }
+ let hi = bedFloor(i + 1);
+ if (b >= hi) { i += 1; lo = hi; hi = bedFloor(i + 1); }
+ return { b, i, lo, hi };
+ };
+}
+
+/** Altitudes at which a vertical line at (x, z) crosses a contact. */
+function contacts(mat, x, z, top = 60) {
+ const at = bedder(mat);
+ const out = [];
+ let prev = at(x, 0, z).i;
+ for (let y = 0; y <= top; y += 0.002) {
+ const i = at(x, y, z).i;
+ if (i !== prev) { out.push(Math.round(y * 1000) / 1000); prev = i; }
+ }
+ return out;
+}
+
+/** sRGB hex -> the linear triple three uploads for it. */
+function lin(hex) {
+ return [16, 8, 0].map((s) => {
+ const v = ((hex >> s) & 255) / 255;
+ return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
+ });
+}
+
+// What a shaded vertical face gets from this library's own day rig
+// (`sunRig`: hemisphere 0x9db8e8 over warm ground + a blue-sky
+// environment), measured on our renderer by rendering a neutral 0x808080
+// albedo through the showcase host: it came back (88, 110, 134), i.e.
+// linear (1, 1.557, 2.445) relative to red.
+const SHADE_LIGHT = [1.0, 1.557, 2.445];
+const shaded = (c) => [0, 1, 2].map((i) => c[i] * SHADE_LIGHT[i]);
+"""
+
+# A butte with a talus, benches whose treads catch the sun, an overhang
+# and its ledge; a boulder and a flat-shaded fallen slab at its foot; and
+# scree on an InstancedMesh wearing the SAME material as the cliff, which
+# is the only way the USE_INSTANCING branch of the world base is compiled.
+_SCENE = """
+import * as THREE from 'three';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+import { patchMicroBreakup } from './lib/surface_wear.js';
+import { patchRockStrata, patchErosionStreaks } from './lib/strata.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 12, 20] };
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ scene.add(new THREE.HemisphereLight(0x9db8e8, 0x8a7f6a, 1.4));
+ const sun = new THREE.DirectionalLight(0xfff0d8, 5.4);
+ sun.position.set(-6, 6, -4);
+ sun.castShadow = true;
+ scene.add(sun);
+
+ const g = new THREE.Group();
+ const rock = new THREE.MeshStandardMaterial({
+ color: 0x8a8071, roughness: 0.92,
+ });
+ const slab = new THREE.MeshStandardMaterial({
+ color: 0x7d766b, roughness: 0.95, flatShading: true,
+ });
+ const prof = [[4.30, 0.00], [3.35, 1.05], [3.28, 2.25], [2.55, 2.48],
+ [2.48, 4.10], [1.98, 4.32], [1.92, 6.20], [1.52, 6.42],
+ [1.46, 7.30], [0, 7.36]]
+ .map(([x, y]) => new THREE.Vector2(x, y));
+ const butte = new THREE.Mesh(new THREE.LatheGeometry(prof, 96), rock);
+ butte.castShadow = butte.receiveShadow = true;
+ g.add(butte);
+
+ const boulder = new THREE.Mesh(new THREE.IcosahedronGeometry(0.85, 3), rock);
+ boulder.position.set(3.5, 0.62, 1.9);
+ boulder.castShadow = boulder.receiveShadow = true;
+ g.add(boulder);
+
+ // Unwelded: curvature reads ZERO on it, so the run field alone carries
+ // the streaks there.
+ const fallen = new THREE.Mesh(new THREE.BoxGeometry(2.6, 0.55, 1.9), slab);
+ fallen.position.set(-3.2, 0.30, 2.7);
+ fallen.rotation.set(0.08, 0.7, 0.16);
+ fallen.castShadow = fallen.receiveShadow = true;
+ g.add(fallen);
+
+ const scree = new THREE.InstancedMesh(
+ new THREE.IcosahedronGeometry(0.22, 1), rock, 24);
+ const m = new THREE.Matrix4();
+ let s = 11;
+ const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+ for (let i = 0; i < 24; i++) {
+ const a = rand() * Math.PI * 2, rr = 3.7 + rand() * 1.9;
+ m.compose(
+ new THREE.Vector3(Math.cos(a) * rr,
+ Math.max(0.09, 1.05 - rr * 0.22),
+ Math.sin(a) * rr),
+ new THREE.Quaternion().setFromEuler(
+ new THREE.Euler(rand() * 3, rand() * 3, rand() * 3)),
+ new THREE.Vector3(1, 0.7 + rand() * 0.6, 1));
+ scree.setMatrixAt(i, m);
+ }
+ scree.instanceMatrix.needsUpdate = true;
+ scree.frustumCulled = false;
+ scree.castShadow = true;
+ g.add(scree);
+
+ for (const [mat, seed] of [[rock, 2], [slab, 5]]) {
+ patchTriplanar(mat, { scale: 1.6 });
+ patchSlopeSplat(mat, { slopeLow: 0.78, slopeHigh: 0.5 });
+ patchRockStrata(mat, { spacing: 0.42, tilt: 9, contrast: 0.72, seed: 2 });
+ patchErosionStreaks(mat, { strength: 0.5, scale: 0.45, seed: 2 });
+ patchMicroBreakup(mat, { seed });
+ }
+ scene.add(g);
+ return {
+ scene,
+ cameras: [{ name: 'hero', position: [14, 6, 18], lookAt: [0, 2, 0],
+ fov: 45 }],
+ update() {},
+ };
+}
+"""
+
+
+def _probe(body: str) -> dict:
+ return measure(_PRELUDE + _STACK + body, _LIBS)
+
+
+def _find(pattern: str, src: str) -> re.Match:
+ m = re.search(pattern, src)
+ assert m, f"{pattern} not in\n{src}"
+ return m
+
+
+def _main_body(src: str) -> str:
+ return src[src.index("void main"):]
+
+
+def _unguarded(src: str) -> str:
+ """Drop `#ifndef X ... #endif` blocks, which may repeat verbatim."""
+ return re.sub(r"#ifndef\b.*?#endif", "", src, flags=re.S)
+
+
+def test_the_five_patch_chain_compiles_on_one_material():
+ """The stack this library exists to join, on our GPU: beds and runs on
+ the SAME material that already carries `patchTriplanar`,
+ `patchSlopeSplat` and `patchMicroBreakup`, in a scene that also wears it
+ on an InstancedMesh and on a flat-shaded box. Only a real instanced
+ program compiles the USE_INSTANCING branch of the world base, only a
+ flat-shaded mesh takes the curvature path where the normal derivative is
+ zero, and only a real compile proves three libraries' varyings, helpers
+ and main() locals survive being concatenated into one shader."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out
+ report = json.loads(out.strip().splitlines()[-1])
+ assert report["ok"] and report["errors"] == [], report
+ # Two patched built-ins, and more programs than that: the cliff
+ # material compiled twice (once per instancing state) and every caster
+ # compiled a depth program as well.
+ assert report["compile"]["custom_materials"] >= 2, report
+ assert report["compile"]["programs"] >= 3, report
+ assert report["compile"]["gpu"], report
+
+
+def test_the_two_patches_chain_without_losing_each_other():
+ """Beds and runs on one material is the ordinary case — a cliff that is
+ bedded but never streaked is half a cliff. patchStandard chains them,
+ but it repeats whatever it is handed: the shared world base and its
+ helpers must be emitted ONCE (a second function body is a compile
+ error), the base must run FIRST or every fragment body reads a varying
+ nobody wrote, and re-applying a patch has to retune its uniforms instead
+ of injecting a second copy of its code."""
+ out = _probe("""
+const m = std();
+patchRockStrata(m, { spacing: 2 });
+patchErosionStreaks(m, { strength: 0.2 });
+patchRockStrata(m, { spacing: 1.4, contrast: 0.5 });
+const s = compile(m);
+const bedsOnly = std();
+patchRockStrata(bedsOnly);
+console.log(JSON.stringify({
+ key: m.customProgramCacheKey(), bedKey: bedsOnly.customProgramCacheKey(),
+ beds: s.fragmentShader.includes('stCol, uStrataAmt'),
+ runs: s.fragmentShader.includes('erCol, erAmt'),
+ spacing: m.userData.uniforms.uStrataSpacing.value,
+ contrast: m.userData.uniforms.uStrataAmt.value,
+ erosion: m.userData.uniforms.uErosAmt.value,
+ worldBody: count(s.vertexShader, 'vec4 stbP ='),
+ fbmFn: count(s.fragmentShader, 'float astraStrataFbm('),
+ floorFn: count(s.fragmentShader, 'float astraStrataFloor('),
+ n3Fn: count(s.fragmentShader, 'float astraStrataN3('),
+ runFn: count(s.fragmentShader, 'float astraStrataRun('),
+ bendFn: count(s.fragmentShader, 'float astraStrataBend('),
+ toneFn: count(s.fragmentShader, 'vec3 astraStrataTone('),
+ pickFn: count(s.fragmentShader, 'float astraStrataPick('),
+ bedLine: count(s.fragmentShader, 'float stTh ='),
+ varyVs: count(s.vertexShader, 'varying vec3 vAstraWorld;'),
+ varyFs: count(s.fragmentShader, 'varying vec3 vAstraWorldN;'),
+}));
+""")
+ assert out["beds"] and out["runs"], "a patch was lost"
+ assert out["worldBody"] == 1 and out["fbmFn"] == 1 and out["n3Fn"] == 1
+ assert out["floorFn"] == 1 and out["runFn"] == 1 and out["bendFn"] == 1
+ assert out["toneFn"] == 1 and out["pickFn"] == 1
+ assert out["varyVs"] == 1 and out["varyFs"] == 1
+ # Every option is a uniform, so re-applying retunes in place.
+ assert out["bedLine"] == 1 and out["spacing"] == 1.4
+ assert out["contrast"] == 0.5 and out["erosion"] == 0.2
+ assert out["key"] == "astra:strata:base+strata:beds+strata:erosion"
+ # A longer chain must not collide with a shorter one's program.
+ assert out["bedKey"] == "astra:strata:base+strata:beds"
+
+
+def test_the_beds_ride_world_altitude_so_two_cliffs_share_one_stack():
+ """The claim the whole patch is for. Beds are checked by the eye
+ against each other, so the bed at 12 m on this face has to be the bed at
+ 12 m on the one across the valley — which means the coordinate is
+ `dot(worldPosition, beddingUp)` with no UV, no object space and nothing
+ a mesh knows in it. Walked numerically at two places 140 m apart on two
+ SEPARATE materials: with the surfaces level the contacts land at the
+ same altitudes to the millimetre, and with the default undulation they
+ stay within the jitter they were given rather than drifting apart."""
+ out = _probe("""
+const flatA = std(), flatB = std();
+patchRockStrata(flatA, { jitter: 0, tilt: 0 });
+patchRockStrata(flatB, { jitter: 0, tilt: 0, colors: [0x223344] });
+const wavy = std();
+patchRockStrata(wavy, { tilt: 0 });
+console.log(JSON.stringify({
+ here: contacts(flatA, 6, 3),
+ faraway: contacts(flatB, -83, 112),
+ wavyHere: contacts(wavy, 6, 3),
+ wavyFar: contacts(wavy, -83, 112),
+ jitter: wavy.userData.uniforms.uStrataJit.value,
+ spacing: wavy.userData.uniforms.uStrataSpacing.value,
+ fs: compile(flatA).fragmentShader,
+}));
+""")
+ assert len(out["here"]) > 40
+ # One stack for the whole world: a different material, a different
+ # palette and a point 140 m away still cut the same contacts.
+ assert out["here"] == out["faraway"]
+ # With the surfaces undulating they wander, but by the jitter they were
+ # given (in beds) and not by a bed or more.
+ wander = [abs(a - b) for a, b in zip(out["wavyHere"], out["wavyFar"], strict=False)]
+ limit = out["jitter"] * out["spacing"]
+ assert max(wander) <= limit, (max(wander), limit)
+ assert max(wander) > 0.01, "the surfaces are not undulating at all"
+ body = _main_body(out["fs"])
+ _find(r"float stB = dot\(vAstraWorld, normalize\(uStrataUp\)\)\s*"
+ r"/ uStrataSpacing;", body)
+ assert "vUv" not in body and " uv" not in body
+
+
+def test_the_base_folds_the_instance_transform_into_the_world_point():
+ """A scattered boulder is an InstancedMesh, and `vertexBody` lands after
+ <begin_vertex> and therefore BEFORE <project_vertex>: nothing has applied
+ `instanceMatrix` yet. Left alone, every copy of a scattered rock reads
+ the bedding at the mesh origin and the whole field wears one band."""
+ out = _probe("""
+const m = std();
+patchRockStrata(m);
+patchErosionStreaks(m);
+console.log(JSON.stringify({ vs: compile(m).vertexShader }));
+""")
+ body = _main_body(out["vs"])
+ assert "#ifdef USE_INSTANCING" in body
+ _find(r"stbP = instanceMatrix \* stbP;", body)
+ _find(r"stbN = mat3\(instanceMatrix\) \* stbN;", body)
+ _find(r"vAstraWorld = \(modelMatrix \* stbP\)\.xyz;", body)
+ # fwidth, dFdx and astraStroke are fragment-only, and the util block
+ # ships in both stages: they may be DEFINED in the vertex shader, never
+ # called.
+ assert "fwidth(" not in body and "dFdx(" not in body
+
+
+def test_tilt_tips_the_beds_off_horizontal():
+ """Level beds read as a stripe texture; beds that dip a few degrees read
+ as geology, because they then cut ACROSS the topography instead of
+ following it. So `tilt` has to reach the shader as a real bedding
+ NORMAL — a uniform, so two cliffs with different dips still share one
+ program — the dip has to show up as a change of bed along the GROUND,
+ and an absurd dip has to be clamped rather than flipping the stack."""
+ out = _probe("""
+const level = std(), dipped = std(), silly = std();
+patchRockStrata(level, { tilt: 0, jitter: 0 });
+patchRockStrata(dipped, { tilt: 12, jitter: 0 });
+patchRockStrata(silly, { tilt: 900, jitter: 0 });
+const atL = bedder(level), atD = bedder(dipped);
+console.log(JSON.stringify({
+ sameKey: level.customProgramCacheKey() === dipped.customProgramCacheKey(),
+ sameFs: compile(level).fragmentShader === compile(dipped).fragmentShader,
+ level: level.userData.uniforms.uStrataUp.value.toArray(),
+ dipped: dipped.userData.uniforms.uStrataUp.value.toArray(),
+ silly: silly.userData.uniforms.uStrataUp.value.toArray(),
+ levelRun: [atL(0, 9, 0).b, atL(40, 9, 0).b, atL(0, 9, 40).b],
+ dippedRun: [atD(0, 9, 0).b, atD(40, 9, 0).b, atD(0, 9, 40).b],
+}));
+""")
+ assert out["sameKey"] and out["sameFs"], "the dip was baked in"
+ assert out["level"] == [0, 1, 0], "level beds must be level"
+ dip = out["dipped"]
+ assert abs(dip[1] - 0.9781) < 1e-3, dip # cos(12 deg)
+ assert abs((dip[0] ** 2 + dip[2] ** 2) ** 0.5 - 0.2079) < 1e-3, dip
+ # A dip past vertical would turn the stack over; it is clamped.
+ assert out["silly"][1] > 0.08, out["silly"]
+ # Level beds are the same bed all across the ground at one altitude;
+ # dipped ones are not, and by the dip they were given.
+ assert out["levelRun"][0] == out["levelRun"][1] == out["levelRun"][2]
+ moved = [abs(v - out["dippedRun"][0]) for v in out["dippedRun"][1:]]
+ assert max(moved) > 2.0, moved
+
+
+def test_bed_thickness_varies_rather_than_repeating_at_one_period():
+ """A repeating stripe of one width is wallpaper, and it is the tell that
+ a shader drew it. So the stack is walked with the shipped uniforms and
+ the constants read out of the compiled GLSL: an average bed has to come
+ out at `spacing`, the thinnest and the thickest have to differ by more
+ than 3x, and no lag may repeat — a stack alternating two widths would
+ pass a spread test and still read as a pattern."""
+ out = _probe("""
+const m = std();
+patchRockStrata(m, { spacing: 0.8, tilt: 0, jitter: 0 });
+const wide = std();
+patchRockStrata(wide, { spacing: 2.5, tilt: 0, jitter: 0 });
+console.log(JSON.stringify({
+ contacts: contacts(m, 6, 3),
+ wideContacts: contacts(wide, 6, 3),
+}));
+""")
+ th = [round(b - a, 4) for a, b in zip(out["contacts"], out["contacts"][1:], strict=False)]
+ assert len(th) > 40, len(th)
+ mean = sum(th) / len(th)
+ assert abs(mean - 0.8) < 0.12, mean
+ assert max(th) / min(th) > 3.0, (min(th), max(th))
+ spread = (sum((v - mean) ** 2 for v in th) / len(th)) ** 0.5 / mean
+ assert spread > 0.2, spread
+ # Nothing repeats: at every short lag the sequence still disagrees with
+ # itself by a fifth of a bed on average.
+ for lag in range(1, 9):
+ pairs = list(zip(th, th[lag:], strict=False))
+ drift = sum(abs(a - b) for a, b in pairs) / len(pairs)
+ assert drift > 0.2 * mean, (lag, drift)
+ # `spacing` is the AVERAGE, and it is a uniform: the same sequence
+ # scales with it rather than being re-rolled.
+ wide = [round(b - a, 4)
+ for a, b in zip(out["wideContacts"], out["wideContacts"][1:],
+ strict=False)]
+ assert abs(sum(wide) / len(wide) - 2.5) < 0.4
+
+
+def test_the_runs_go_down_the_fall_line_and_not_down_world_y():
+ """What separates this from a drip stain. On a vertical face the two
+ agree; on a slope they do not, and a run that keeps going down world Y
+ there cuts across the contours, which no water does. The direction is
+ gravity with the surface normal taken out, and the LENGTH of that same
+ vector is the sine of the slope, so one expression gives both the way
+ the water goes and the gate that keeps it off level ground. The field
+ is then smeared along it — taps upslope, weaker each time, which is what
+ gives a run a head at the top and a tail at the bottom."""
+ out = _probe("""
+const m = std();
+patchErosionStreaks(m, { scale: 0.9 });
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ body = _main_body(fs)
+ # Gravity projected into the surface: g - n * dot(g, n), which for
+ # g = -Y is exactly this.
+ _find(r"vec3 erG = vec3\(0\.0, -1\.0, 0\.0\) \+ erN \* erN\.y;", body)
+ _find(r"float erSin = length\(erG\);", body)
+ _find(r"vec3 erD = erG / max\(erSin, 1e-4\);", body)
+ # The field is smeared along THAT direction, never along world Y — and
+ # long enough to read as a track: at 5.5 run widths the runs came out on
+ # our host as round blotches, so the smear is pinned at 7 or more with
+ # at least five taps, and the fibre smear that tears the edge is
+ # weighted hard enough to actually break it.
+ m = _find(r"float erA = astraStrataRun\(erP, erD, ([\d.]+), (\d)\);", body)
+ assert float(m.group(1)) >= 7.0 and int(m.group(2)) >= 5, m.groups()
+ m = _find(r"float erFib = astraStrataRun\(erP \* ([\d.]+), erD,"
+ r" [\d.]+, \d\);", body)
+ assert float(m.group(1)) >= 3.0, m.group(1)
+ m = _find(r"float erF = erA \+ \(erFib - 0\.5\) \* ([\d.]+);", body)
+ assert float(m.group(1)) >= 0.35, m.group(1)
+ assert "vec3(0.0, 1.0, 0.0)" not in body
+ assert "vAstraWorld.y" not in body, "world Y is not the flow axis"
+ # The smear: taps UPSLOPE (-d) with a decaying weight, unevenly spaced
+ # so they cannot all land on one lattice phase.
+ _find(r"float astraStrataRun\(vec3 p, vec3 d, float len, int taps\) \{\s*"
+ r"float s = astraStrataN3\(p\), w = 1\.0, a = 1\.0, o = 0\.0;\s*"
+ r"for \(int i = 0; i < 6; i\+\+\) \{\s*"
+ r"if \(i >= taps\) break;\s*"
+ r"o \+= len \* \(([\d.]+) \+ ([\d.]+) \* float\(i\)\);\s*"
+ r"a \*= (0\.\d+); w \+= a;\s*"
+ r"s \+= a \* astraStrataN3\(p - d \* o\);", fs)
+ # Only a face that can shed takes a run: nothing on the level, and
+ # nothing on a soffit, which drips clear instead of tracking.
+ _find(r"float erFlow = smoothstep\([\d.]+, [\d.]+, erSin\)\s*"
+ r"\* \(1\.0 - smoothstep\([\d.]+, [\d.]+, -erN\.y\)\);", body)
+ _find(r"clamp\(erK \* erFlow \* uErosAmt, 0\.0, 1\.0\)", body)
+
+
+def test_the_runs_start_where_water_collects_rather_than_everywhere():
+ """Runs sprayed evenly over a face are a texture. Water collects, and
+ the only thing a fragment can see of that is the way the surface bends
+ under it — so curvature is split by DIRECTION: concave across the flow
+ is a gully and holds its thread the whole way down, convex along the
+ flow is a lip and pours what it caught over, convex across is a rib that
+ sheds sideways and stays clean. Both halves are needed because a bump
+ is convex in both and means neither. The response is band-limited in
+ run widths, or the pixel-scale wrinkle on any noisy mesh reads as a
+ gully; and a source lowers the field's THRESHOLD rather than dimming
+ it, so clean rock keeps a few strong runs."""
+ out = _probe("""
+const m = std();
+patchErosionStreaks(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ body = _main_body(fs)
+ # Curvature ALONG the flow, and the total minus it, which by Euler is
+ # the curvature across it. Both in run widths.
+ _find(r"float erAl = astraStrataBend\(erN, vAstraWorld, erD\)"
+ r" \* uErosScale;", body)
+ _find(r"float erAc = astraStrataCurv\(erN, vAstraWorld\) \* uErosScale\s*"
+ r"- erAl;", body)
+ _find(r"float erSrc = clamp\(([\d.]+) \+ ([\d.]+)"
+ r" \* astraStrataBand\(-erAc\)\s*"
+ r"\+ ([\d.]+) \* astraStrataBand\(erAl\)\s*"
+ r"- ([\d.]+) \* astraStrataBand\(erAc\), 0\.0, 1\.0\);", body)
+ # The band: a bend the size of a run counts, a wrinkle does not.
+ m = _find(r"float astraStrataBand\(float k\) \{\s*"
+ r"return smoothstep\(([\d.]+), ([\d.]+), k\)"
+ r" \* \(1\.0 - smoothstep\(([\d.]+), ([\d.]+), k\)\);", fs)
+ lo, hi, off0, off1 = (float(v) for v in m.groups())
+ assert lo < hi <= off0 < off1, m.groups()
+ assert off1 <= 8.0, "a pixel-scale wrinkle would still read as a gully"
+ # The source moves the threshold, and downward: more source, more of the
+ # field passes.
+ t = _find(r"float erT = mix\(([\d.]+), ([\d.]+), erSrc\);", body)
+ assert float(t.group(2)) < float(t.group(1)), t.groups()
+ # Two levels on one field, kept as SEPARATE terms because the port
+ # tints them differently, both widened by the field's own gradient.
+ _find(r"float erAA = clamp\(fwidth\(erF\), 0\.0, [\d.]+\);", body)
+ _find(r"float erBroad = smoothstep\(erT - [\d.]+ - erAA,\s*"
+ r"erT \+ [\d.]+ \+ erAA, erF\);", body)
+ _find(r"float erCore = smoothstep\(erT \+ [\d.]+ - erAA,\s*"
+ r"erT \+ [\d.]+ \+ erAA, erF\);", body)
+ _find(r"float erK = [\d.]+ \* erBroad \+ [\d.]+ \* erCore;", body)
+ # Curvature is the surface's own derivative, so it reads ZERO across a
+ # hard unwelded edge — the field has to carry those alone.
+ _find(r"float astraStrataCurv\(vec3 n, vec3 p\) \{\s*"
+ r"vec3 dx = dFdx\(p\), dy = dFdy\(p\);", fs)
+
+
+def test_a_contact_and_a_seam_stop_short_of_aliasing():
+ """Bedding is the one structure here with a PERIOD, which is what
+ aliases: at 60 m a pixel spans several beds, and a hard tone step per
+ bed would crawl into moire (MSAA never sees a shader's own edge). Three
+ defences, all keyed to the pixel footprint of the bed rather than to
+ distance: the contact between two beds is resolved over the pixel it
+ covers, the parting rides `astraStroke`, which fades a stroke out once a
+ pixel spans more than the stroke itself, and past a pixel per bed the
+ whole stack dissolves into its own mean tone — so a far cliff keeps its
+ rock colour instead of reverting to whatever was underneath."""
+ out = _probe("""
+const m = std();
+patchRockStrata(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ body = _main_body(fs)
+ # The footprint is measured in BEDS, so a thin bed defends itself sooner
+ # than a thick one.
+ _find(r"float stAA = clamp\(fwidth\(stB\) / stTh, 1e-4, [\d.]+\);", body)
+ _find(r"0\.5 - 0\.5 \* smoothstep\(0\.0, stAA,"
+ r" min\(stF, 1\.0 - stF\)\)\);", body)
+ _find(r"stCol = mix\(stCol, stAvg,"
+ r" smoothstep\([\d.]+, [\d.]+, stAA\)\);", body)
+ _find(r"astraStroke\(stP \+ 0\.5, mix\([\d.]+, [\d.]+, stS\)\)", body)
+ # The stroke's argument has to be CONTINUOUS across the contact or its
+ # own fwidth reads the jump and kills the seam there.
+ _find(r"float stP = stI \+ stF;", body)
+ assert "astraStroke" in fs
+
+
+def test_every_option_is_a_uniform_and_never_baked_into_the_source():
+ """three caches programs by key and the FIRST material to compile a key
+ decides the GLSL every material sharing it gets. Two materials that
+ differ only in options must therefore compile to the same source, or the
+ second silently wears the first's geology — one cliff's bed spacing, dip
+ and palette imposed on every other cliff in the scene. Same key,
+ byte-identical GLSL, different uniform values; and a palette of any
+ length has to land in the same four."""
+ out = _probe("""
+const a = std();
+patchRockStrata(a, { spacing: 0.8, tilt: 7, contrast: 0.7, jitter: 0.35,
+ seed: 1 });
+patchErosionStreaks(a, { strength: 0.45, scale: 0.8, seed: 1 });
+const b = std();
+patchRockStrata(b, { spacing: 4.5, tilt: -21, contrast: 0.2, jitter: 1.4,
+ seed: 77, colors: [0x112233, 0x445566] });
+patchErosionStreaks(b, { strength: 0.9, scale: 3.2, seed: 77,
+ color: new THREE.Color(0x778899) });
+const one = std();
+patchRockStrata(one, { colors: [0x203040] });
+const many = std();
+patchRockStrata(many, { colors: [0x101010, 0x202020, 0x303030, 0x404040,
+ 0x505050, 0x606060] });
+const sa = compile(a), sb = compile(b);
+const u = (m) => m.userData.uniforms;
+const pal = (m) => [0, 1, 2, 3].map(
+ (i) => u(m)['uStrataC' + i].value.getHex());
+console.log(JSON.stringify({
+ sameKey: a.customProgramCacheKey() === b.customProgramCacheKey(),
+ sameVs: sa.vertexShader === sb.vertexShader,
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ aBeds: [u(a).uStrataSpacing.value, u(a).uStrataAmt.value,
+ u(a).uStrataJit.value],
+ bBeds: [u(b).uStrataSpacing.value, u(b).uStrataAmt.value,
+ u(b).uStrataJit.value],
+ aEros: [u(a).uErosAmt.value, u(a).uErosScale.value],
+ bEros: [u(b).uErosAmt.value, u(b).uErosScale.value],
+ bDip: u(b).uStrataUp.value.y,
+ bPal: pal(b), onePal: pal(one), manyPal: pal(many),
+ erosColor: u(b).uErosColor.value.getHex(),
+}));
+""")
+ assert out["sameKey"] and out["sameVs"] and out["sameFs"]
+ assert out["aBeds"] == [0.8, 0.7, 0.35]
+ assert out["bBeds"] == [4.5, 0.2, 1.4]
+ assert out["aEros"] == [0.45, 0.8] and out["bEros"] == [0.9, 3.2]
+ assert abs(out["bDip"] - 0.9336) < 1e-3, out["bDip"] # cos(21 deg)
+ assert out["erosColor"] == 0x778899
+ # Two colours are resampled across the four, not repeated.
+ assert out["bPal"][0] == 0x112233 and out["bPal"][3] == 0x445566
+ assert len(set(out["bPal"])) == 4
+ assert set(out["onePal"]) == {0x203040}
+ assert out["manyPal"][0] == 0x101010 and out["manyPal"][3] == 0x606060
+
+
+def test_no_patch_declares_a_name_its_neighbours_own():
+ """The silent failure this library is most exposed to: a cliff wears
+ terrain_shade and surface_wear as a matter of course, and often aging
+ and waterside too, and patchStandard DROPS a repeated uniform or varying
+ and keeps the first — so a shared name would leave one patch reading the
+ other's value with nothing reported. A repeated local inside main is a
+ compile error instead, and a repeated helper with a different body
+ throws by name. So the uniform sets must be disjoint (uTime excepted,
+ the shared clock), and a material wearing all eleven patches must
+ declare every name exactly once."""
+ out = _probe("""
+const mine = std();
+patchRockStrata(mine);
+patchErosionStreaks(mine);
+const nbr = std();
+patchTriplanar(nbr);
+patchSlopeSplat(nbr, { snowLine: 30 });
+patchShoreWet(nbr);
+patchShoreFoam(nbr);
+patchMicroBreakup(nbr);
+patchEdgeWear(nbr);
+patchDripStains(nbr);
+patchRust(nbr);
+patchDust(nbr);
+const all = std();
+patchTriplanar(all);
+patchSlopeSplat(all, { snowLine: 30 });
+patchShoreWet(all);
+patchShoreFoam(all);
+patchMicroBreakup(all);
+patchEdgeWear(all);
+patchDripStains(all);
+patchRust(all);
+patchDust(all);
+patchRockStrata(all);
+patchErosionStreaks(all);
+const s = compile(all);
+console.log(JSON.stringify({
+ mineU: Object.keys(mine.userData.uniforms),
+ nbrU: Object.keys(nbr.userData.uniforms),
+ vs: s.vertexShader, fs: s.fragmentShader,
+}));
+""")
+ shared = set(out["mineU"]) & set(out["nbrU"])
+ assert shared == {"uTime"}, shared
+ for stage in ("vs", "fs"):
+ src = out[stage]
+ decls = re.findall(
+ r"^\s*(?:uniform|varying)\s+(?:lowp |mediump |highp )?"
+ r"[a-z0-9]+\s+(\w+)\s*;", src, re.M)
+ dupes = [n for n, c in Counter(decls).items() if c > 1]
+ assert not dupes, f"{stage} declares {dupes} twice"
+ fns = re.findall(r"^(?:float|vec[234]|int)\s+(\w+)\s*\(",
+ _unguarded(src), re.M)
+ assert not [n for n, c in Counter(fns).items() if c > 1]
+ locals_ = re.findall(
+ r"^\s*(?:float|vec[234]|int|mat[234])\s+(\w+)\s*=",
+ _main_body(src), re.M)
+ clash = [n for n, c in Counter(locals_).items() if c > 1]
+ assert not clash, f"{stage} main() declares {clash} twice"
+ # Named as the neighbours name them on purpose: ONE world position is
+ # written for the whole chain, not one per library.
+ assert "vAstraWorld" in out["vs"] and "vAstraWorld" in out["fs"]
+ # Every helper this library adds is prefixed, since a neighbour defining
+ # the same name with a different body throws.
+ mine = re.findall(r"^(?:float|vec[234])\s+(\w+)\s*\(",
+ _LIB_SRC.replace(" '", ""), re.M)
+ assert all(n.startswith("astraStrata") for n in mine), mine
+
+
+def test_one_seed_lays_the_same_geology_every_time():
+ """A render is re-run — for a fix round, for a video, for the judge —
+ and the rock must not move between takes. The seed reaches the GPU only
+ as a noise-space OFFSET (a uniform, because baking it would hand
+ material one's seed to every material sharing the key), so one seed must
+ give one offset, two seeds must not land on the same beds, the beds and
+ the runs must be decorrelated from each other, and both must differ from
+ aging's and surface_wear's for the same seed or the runs would ride that
+ library's stains."""
+ out = _probe("""
+const mk = (seed) => {
+ const m = std();
+ patchRockStrata(m, { seed });
+ patchErosionStreaks(m, { seed });
+ patchDripStains(m, { seed });
+ patchMicroBreakup(m, { seed });
+ return m;
+};
+const a = mk(7), b = mk(7), c = mk(8);
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ aBeds: u(a).uStrataSeed.value.toArray(),
+ bBeds: u(b).uStrataSeed.value.toArray(),
+ cBeds: u(c).uStrataSeed.value.toArray(),
+ aEros: u(a).uErosSeed.value.toArray(),
+ cEros: u(c).uErosSeed.value.toArray(),
+ aDrip: u(a).uDripSeed.value.toArray(),
+ aMicro: u(a).uMicroSeed.value.toArray(),
+ aUp: u(a).uStrataUp.value.toArray(),
+ cUp: u(c).uStrataUp.value.toArray(),
+ sameSrc: compile(a).fragmentShader === compile(c).fragmentShader,
+ contactsA: contacts(a, 4, 4, 20),
+ contactsB: contacts(b, 4, 4, 20),
+ contactsC: contacts(c, 4, 4, 20),
+}));
+""")
+ assert out["aBeds"] == out["bBeds"], "the same seed moved the beds"
+ assert out["aBeds"] != out["cBeds"] and out["aEros"] != out["cEros"]
+ assert out["aBeds"] != out["aEros"], "the runs ride the bed noise"
+ assert out["aBeds"] != out["aDrip"] and out["aBeds"] != out["aMicro"]
+ assert all(0 <= v <= 52 for v in out["aBeds"] + out["aEros"])
+ # The dip DIRECTION is seeded too, so one scene keeps one dip.
+ assert out["aUp"] != out["cUp"]
+ assert abs(out["aUp"][1] - out["cUp"][1]) < 1e-9, "the dip angle moved"
+ # Same GLSL for both seeds: the seed is a uniform, not source.
+ assert out["sameSrc"]
+ assert out["contactsA"] == out["contactsB"]
+ assert out["contactsA"] != out["contactsC"]
+ assert "Math.random" not in _LIB_SRC
+
+
+def test_the_wash_polishes_the_material_once_however_often_it_lands():
+ """`fragmentBody` lands after <color_fragment> and therefore BEFORE
+ <roughnessmap_fragment> declares roughnessFactor, so no patch here can
+ touch a per-pixel gloss. A face with water tracks is a face that gets
+ wet, so the runs take a small polish off the material — through
+ composeRoughness, so a refine round that re-runs the same build cannot
+ compound it into a mirror, and a neighbour's matte factor still composes
+ with it. Beds are not a finish and must not touch it at all."""
+ out = _probe("""
+const m = std({ roughness: 0.8 });
+patchRockStrata(m, { contrast: 1 });
+const beds = m.roughness;
+patchErosionStreaks(m, { strength: 1 });
+const r1 = m.roughness;
+patchErosionStreaks(m, { strength: 1 });
+const r2 = m.roughness;
+patchErosionStreaks(m, { strength: 0 });
+const r3 = m.roughness;
+const basic = new THREE.MeshBasicMaterial({ color: 0x445566 });
+patchRockStrata(basic);
+patchErosionStreaks(basic);
+console.log(JSON.stringify({
+ beds, r1, r2, r3, base: m.userData.astraRoughness.base,
+ factors: Object.keys(m.userData.astraRoughness.factors).sort(),
+ basicRough: basic.roughness === undefined,
+ basicPatched: basic.userData.astraPatches.length,
+}));
+""")
+ assert out["beds"] == 0.8, "bedding is albedo, not finish"
+ assert out["base"] == 0.8, "the authored value is the one to compose on"
+ assert out["factors"] == ["strata:erosion"]
+ assert out["r1"] < 0.8, "a washed face is not as matte as a dry one"
+ assert out["r2"] == out["r1"], "re-applying compounded the polish"
+ assert abs(out["r3"] - 0.8) < 1e-9
+ # A material with no roughness at all still takes the albedo patches.
+ assert out["basicRough"] and out["basicPatched"] == 3
+
+
+def test_the_palette_survives_this_renderer_s_blue_sky_fill():
+ """The port's own colour law, and the reason the palette changed.
+
+ Most of a cliff is in its own shade, and `sunRig`'s day fill plus a
+ blue-sky environment put linear (1, 1.56, 2.45) on a shaded vertical
+ face here — measured by rendering a neutral 0x808080 albedo through the
+ showcase host, which came back (88, 110, 134). A bed whose albedo does
+ not beat that ratio does not read as a cooler ROCK, it reads as a
+ cyan-green band of some other material: the reference palette's four
+ tones all landed at linear G/R around 0.8, well past the 0.64 the light
+ allows, which is exactly how the cliff rendered. So every shipped bed
+ tone, and the default stain and both minerals derived from it, are
+ solved against that measurement — and they are spread by SATURATION
+ rather than toward yellow, because a bed that reaches G/R = 1 in the
+ render is one grain-multiply away from green."""
+ out = _probe("""
+const beds = [];
+const m = std();
+patchRockStrata(m);
+const u = m.userData.uniforms;
+for (let i = 0; i < 4; i++) beds.push(u['uStrataC' + i].value.toArray());
+const e = std();
+patchErosionStreaks(e);
+console.log(JSON.stringify({
+ beds: beds.map(shaded),
+ bedLin: beds,
+ eros: shaded(e.userData.uniforms.uErosColor.value.toArray()),
+ fs: compile(m).fragmentShader,
+ efs: compile(e).fragmentShader,
+}));
+""")
+ # `THREE.Color.toArray` is already the LINEAR working-space triple, so
+ # these are the numbers the GPU multiplies.
+ for i, (r, g, b) in enumerate(out["beds"]):
+ assert g < r and b < r, f"bed {i} renders {(r, g, b)}: not rock"
+ # Warm, but never so warm the bed reads as painted terracotta.
+ assert 0.55 <= g / r <= 0.95, (i, g / r)
+ assert 0.30 <= b / r <= 0.85, (i, b / r)
+ r, g, b = out["eros"]
+ assert g < r and b < r, f"the default stain renders {(r, g, b)}"
+ # The two minerals a run can carry are BOTH kept off neutral, or a dark
+ # stain under a blue sky comes back as a slate-blue patch.
+ for name in ("erIron", "erMang"):
+ m = re.search(
+ rf"vec3 {name} = uErosColor \* vec3\(([\d.]+), ([\d.]+),"
+ rf" ([\d.]+)\);", out["efs"])
+ assert m, name
+ mr, mg, mb = (float(v) for v in m.groups())
+ assert (r * mr) > (g * mg) and (r * mr) > (b * mb), (name, m.groups())
+ # Albedo stays inside the linear range a lit surface can hold: nothing
+ # near black (which the sky's own specular then paints blue) and nothing
+ # so bright it blows on a sunlit ledge.
+ lum = [0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
+ for c in out["bedLin"]]
+ assert min(lum) > 0.02, lum
+ assert max(lum) < 0.8, lum
+ # ...and a real spread, or the stack has no beds in it.
+ assert max(lum) / min(lum) > 3.0, lum
+
+
+def test_every_mark_varies_in_hue_and_not_only_in_value():
+ """The aesthetic contract this port added, pinned so an edit cannot
+ flatten it back. A bed multiplied by a scalar grain is ONE colour over
+ a whole face, which is what makes a shader stack read as printed
+ stripes; the reference did that for the grain, for the foot of a bed and
+ for the parting, and replaced the albedo outright inside a run. Here:
+ the grain is a vec3 warm-to-bleached, the foot of a bed goes warm, the
+ parting keeps its hue and a floor instead of multiplying toward black,
+ and a run DARKENS the rock under it (so the bedding still shows through)
+ before being tinted toward one of two minerals."""
+ out = _probe("""
+const m = std();
+patchRockStrata(m);
+patchErosionStreaks(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ body = _main_body(out["fs"])
+ # The grain is a colour, warm at one end and bleached at the other, and
+ # the bleached end must not be cool enough to tip a bed into green.
+ m = _find(r"stCol \*= mix\(vec3\(([\d.]+), ([\d.]+), ([\d.]+)\),"
+ r" vec3\(([\d.]+), ([\d.]+), ([\d.]+)\),\s*stG\);", body)
+ wr, wg, wb, cr, cg, cb = (float(v) for v in m.groups())
+ assert wr > wg > wb, ("the warm end is not warm", m.groups())
+ assert cb / cr < 1.10, ("the bleached end is cool enough to go green",
+ m.groups())
+ # A second, finer mottle, so the metre-scale grain is not the smallest
+ # thing on the rock at arm's length.
+ _find(r"float stG2 = astraStrataFbm\(vAstraWorld\.xz \* [\d.]+", body)
+ # The foot of a bed is warm, not just dark.
+ m = _find(r"stCol \*= mix\(vec3\(1\.0\), vec3\(([\d.]+), ([\d.]+),"
+ r" ([\d.]+)\),\s*1\.0 - smoothstep", body)
+ fr, fg, fb = (float(v) for v in m.groups())
+ assert fr > fg > fb, m.groups()
+ # The parting fades along the bed rather than being a ruled line, and it
+ # lands on a floored, hue-keeping mix instead of a multiply to black.
+ _find(r"float stSeam = astraStroke\([\s\S]*?\* mix\([\d.]+, 1\.0, stG\);",
+ body)
+ m = _find(r"stCol = mix\(stCol,\s*stCol \* vec3\([\d.]+, [\d.]+, [\d.]+\)"
+ r"\s*\+ vec3\(([\d.]+), ([\d.]+), ([\d.]+)\), [\d.]+ \* stSeam\);",
+ body)
+ assert all(float(v) > 0 for v in m.groups()), "the seam can reach black"
+ # A run darkens what is under it before it tints, so the beds keep
+ # showing through the runs the way the module's header promises.
+ _find(r"vec3 erWet = diffuseColor\.rgb \* mix\([\d.]+, [\d.]+, erA\);",
+ body)
+ _find(r"vec3 erCol = mix\(erWet, erTint \* mix\([\d.]+, [\d.]+, erA\),"
+ r" [\d.]+\);", body)
+ # ...and the mineral it carries is chosen by a field far COARSER than
+ # the run, so one run is one mineral the whole way down.
+ m = _find(r"float erMin = astraStrataN3\(erP \* ([\d.]+)", body)
+ assert float(m.group(1)) < 0.5, m.group(1)
+ _find(r"vec3 erTint = mix\(erIron, erMang,\s*"
+ r"erCore \* mix\([\d.]+, [\d.]+, erMin\)\);", body)
diff --git a/harness/tests/scene_runtime/lib/test_submerged.py b/harness/tests/scene_runtime/lib/test_submerged.py
new file mode 100644
index 00000000..51bc43df
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_submerged.py
@@ -0,0 +1,1019 @@
+"""Under water everything is a column, and every shortcut is silent.
+
+``submerged.js`` ships three things a pool needs and one thing can go
+wrong with each of them without an error. An extinction that is one
+scalar compiles and turns a floor grey instead of teal, because losing
+red first IS the effect. A ring that scales its own card compiles and
+reads as a sprite popping, because a wave is a place on a surface, not a
+growing decal. A crack drawn from one noise call compiles and reads as
+cracked paint, because ice forks. And all three land on materials
+``caustics.js``, ``waterside.js``, ``terrain_shade.js`` and ``aging.js``
+are already on, where a shared uniform name is absorbed in silence and a
+shared local takes the whole material down.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference test. The
+assertions about THEIR renderer contract are gone (their fixture-level
+``scene_check`` too — our ``check_shaders.mjs`` boots ``src/scene.js``,
+so the GPU pass here is a scene of its own). What is new is the colour
+half this host measured and this session added: the turbidity spectrum,
+the veil's dither and its ``light``, and the FRESNEL the ice interior
+now sits behind.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "submerged.js", "caustics.js", "waterside.js",
+ "terrain_shade.js", "aging.js")
+_LIB = LIB_DIR / "submerged.js"
+
+# The two hooks patchStandard injects into, as a material three would.
+# Nothing else is in the source, so what comes back is the patch itself.
+_FAKE_SHADER = """
+const fake = () => ({
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+});
+const mains = (sh) => sh.fragmentShader.slice(
+ sh.fragmentShader.indexOf('void main')) + '\\n' +
+ sh.vertexShader.slice(sh.vertexShader.indexOf('void main'));
+const locals = (src) => (src.match(
+ /^\\s+(?:float|vec2|vec3|vec4|mat3|mat4)\\s+(\\w+)/gm) || [])
+ .map((h) => h.trim().split(/\\s+/)[1]);
+"""
+
+
+def _measure(script: str) -> dict:
+ return measure(_FAKE_SHADER + script, _LIBS)
+
+
+def _approx(x):
+ """Local approx: one comparison does not justify an import."""
+ class _A: # pylint: disable=too-few-public-methods
+ def __eq__(self, other):
+ return abs(other - x) < 1e-9
+ return _A()
+
+
+def _smooth(x, a, b):
+ t = min(1.0, max(0.0, (x - a) / (b - a)))
+ return t * t * (3 - 2 * t)
+
+
+def test_extinction_is_a_spectrum_and_red_goes_first():
+ """The whole effect. Water does not dim what is under it, it eats
+ the RED out of it first — an order of magnitude faster than the blue
+ — which is why a submerged rock goes teal and not grey. So the
+ coefficient is a vec3, the loss is Beer-Lambert on it, and the
+ default scalar rides water's own spectrum. A single float here
+ would compile, run, and read as a rock in fog.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchUnderwater } from './lib/submerged.js';
+const sh = fake();
+const m = patchUnderwater(new THREE.MeshStandardMaterial());
+m.onBeforeCompile(sh);
+const u = (mat, k) => mat.userData.uniforms[k].value;
+const strong = patchUnderwater(new THREE.MeshStandardMaterial(),
+ { extinction: 0.9 });
+const given = patchUnderwater(new THREE.MeshStandardMaterial(),
+ { extinction: [0.5, 0.2, 0.05] });
+const vec = patchUnderwater(new THREE.MeshStandardMaterial(),
+ { extinction: new THREE.Vector3(0.4, 0.3, 0.2) });
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ ext: u(m, 'uSubExt'), strong: u(strong, 'uSubExt'),
+ given: u(given, 'uSubExt'), vec: u(vec, 'uSubExt'),
+ neg: u(patchUnderwater(new THREE.MeshStandardMaterial(),
+ { extinction: -3 }), 'uSubExt'),
+ color: u(m, 'uSubColor').getHex(),
+}));
+""")
+ fs = out["fs"]
+ ext = out["ext"]
+ # Three coefficients, not one: the ratio IS the effect.
+ assert "uniform vec3 uSubExt;" in fs
+ assert ext["x"] > ext["y"] > ext["z"] > 0, ext
+ assert ext["x"] > 3 * ext["y"], "red must die far faster than green"
+ assert ext["y"] > 2 * ext["z"], "and green faster than blue"
+ # Beer-Lambert on the albedo, exponential in the path.
+ assert "vec3 subT = exp(-subK * ((subD + subView) * subMk));" in fs
+ assert "diffuseColor.rgb *= subT;" in fs
+ # A scalar scales the spectrum; a triple is taken as given.
+ assert out["strong"]["x"] / ext["x"] == _approx(0.9 / 0.35)
+ assert out["given"] == {"x": 0.5, "y": 0.2, "z": 0.05}
+ assert out["vec"] == {"x": 0.4, "y": 0.3, "z": 0.2}
+ # A negative coefficient would AMPLIFY with depth and blow out.
+ assert all(v == 0 for v in out["neg"].values()), out["neg"]
+
+ # And the numbers the shipped default actually produces. Same
+ # surface, three depths, one metre of view path per metre of depth.
+ rgb = []
+ for depth in (0.5, 2.0, 5.0):
+ path = depth * 2
+ rgb.append(tuple(
+ math.exp(-ext[a] * path) for a in ("x", "y", "z")))
+ for r, g, b in rgb:
+ assert r < g < b, (r, g, b)
+ # Red is not merely lower, it FALLS faster: by 5 m it is gone while
+ # the blue has barely started.
+ assert rgb[2][0] < 0.05 and rgb[2][2] > 0.35, rgb
+ # Over the same three depths the red loses 23x of itself where the
+ # blue loses 1.4x — that RATE gap is the whole look.
+ assert rgb[0][0] / rgb[2][0] > 10 * (rgb[0][2] / rgb[2][2]), rgb
+
+
+def test_the_loss_runs_on_depth_and_on_the_ray_to_the_camera():
+ """Depth alone is half of it. Light falls through the column to the
+ surface and then travels BACK OUT through it to the eye, so the far
+ end of a pool floor is further gone than the near end at the same
+ depth — that second leg is what makes a bay recede instead of merely
+ darkening. The eye ray counts only where it is under the surface,
+ which is its own share of the climb to the camera, so a camera in
+ the air and a camera in the water both come out right.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchUnderwater } from './lib/submerged.js';
+const sh = fake();
+patchUnderwater(new THREE.MeshStandardMaterial(), { level: 3 })
+ .onBeforeCompile(sh);
+console.log(JSON.stringify({ fs: sh.fragmentShader }));
+""")
+ fs = out["fs"]
+ assert "float subRise = max(cameraPosition.y - vAstraWorld.y, 1e-4);" in fs
+ assert "float subWet = clamp(subD / subRise, 0.0, 1.0);" in fs
+ assert "float subView = length(cameraPosition - vAstraWorld) * subWet;" in fs
+ # Both legs, summed, before the exponential.
+ assert "(subD + subView)" in fs
+
+ # The geometry of that share, in numbers: a camera 6 m up, a
+ # fragment 2 m down under a level at 0, at three distances.
+ level, frag_y, cam_y = 0.0, -2.0, 6.0
+ rise = cam_y - frag_y
+ wet = min(max((level - frag_y) / rise, 0.0), 1.0)
+ assert abs(wet - 0.25) < 1e-9
+ near, far = 10.0, 40.0
+ assert far * wet > near * wet, "further away is more water"
+ # A fragment AT the line takes none of the ray, whatever the range.
+ assert (level - level) / rise == 0
+ # A camera under the surface takes the whole ray.
+ assert min(max((level - frag_y) / max(-1.0 - frag_y, 1e-4), 0.0), 1.0) == 1
+
+
+def test_nothing_above_the_water_line_is_touched():
+ """A column that climbs the dry bank is the tell that it is a
+ texture, and here it would tint the whole scene. Both terms are
+ gated by the same clamp: the depth is clamped at zero at the line
+ and the ray's underwater share is ``depth / rise``, which is zero
+ there too — so the transmittance is exactly 1.0 and the veil exactly
+ 0.0 above the line, not merely small, and with no step AT the line
+ either. And the patch writes in exactly two places, so it cannot
+ leak past the line by some other route.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchUnderwater } from './lib/submerged.js';
+const sh = fake();
+const m = patchUnderwater(new THREE.MeshStandardMaterial(),
+ { level: 2.5, murk: 0.4 });
+m.onBeforeCompile(sh);
+const fs = sh.fragmentShader;
+console.log(JSON.stringify({
+ fs, body: fs.slice(fs.indexOf('#include <color_fragment>')),
+ level: m.userData.uniforms.uSubLevel.value,
+ murk: m.userData.uniforms.uSubMurk.value,
+ clampMurk: patchUnderwater(new THREE.MeshStandardMaterial(),
+ { murk: 9 }).userData.uniforms.uSubMurk.value,
+}));
+""")
+ fs, body = out["fs"], out["body"]
+ assert out["level"] == 2.5 and out["murk"] == 0.4
+ assert "float subD = max(uSubLevel - vAstraWorld.y, 0.0);" in fs
+ # exp(-k * 0) is exactly 1 and 1 - 1 is exactly 0: above the line
+ # the albedo is untouched and the veil contributes nothing. The
+ # dither and the hue break are both MULTIPLIERS on that zero, so
+ # neither can resurrect it.
+ assert "diffuseColor.rgb *= subT;" in fs
+ assert "vec3 subVeil = uSubColor * uSubLight * (1.0 - subT)" in fs
+ assert "totalEmissiveRadiance += subVeil;" in fs
+ # The murk multiplies the PATH, so it cannot resurrect a zero path
+ # above the line, and it is clamped so it can never go negative.
+ assert out["clampMurk"] == 1
+ assert "float subS = uSubMurk * (astraFbm2(subQ, 3) - 0.44);" in fs
+ assert "float subMk = 1.0 + subS;" in fs
+ writes = re.findall(
+ r"^\s*(diffuseColor|totalEmissiveRadiance|gl_FragColor|"
+ r"roughnessFactor)[.\w]*\s*[-+*/]?=", body, re.M)
+ assert writes == ["diffuseColor", "totalEmissiveRadiance"], writes
+ # roughnessFactor does not exist at this hook, and gloss belongs to
+ # waterside's wet patch anyway.
+ assert "roughnessFactor" not in fs
+
+
+def test_the_veil_is_what_kills_contrast_rather_than_darkness():
+ """Under water two neighbouring albedos converge, and they converge
+ on the WATER's colour, not on black. That is one subtraction and
+ one addition: the surface's own return is multiplied by the
+ transmittance, and the column scatters back exactly what was lost,
+ so the difference between two albedos falls by the transmittance
+ while the mean walks to the water. Dropping the veil would leave a
+ submerged floor merely dark, which is the look of a scene that
+ forgot to light it.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchUnderwater } from './lib/submerged.js';
+const sh = fake();
+const m = patchUnderwater(new THREE.MeshStandardMaterial(),
+ { color: 0x123456 });
+m.onBeforeCompile(sh);
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ color: m.userData.uniforms.uSubColor.value.getHex(),
+ warned: (() => {
+ const said = [];
+ console.warn = (msg) => said.push(String(msg));
+ patchUnderwater(new THREE.MeshStandardMaterial());
+ const quiet = said.length;
+ patchUnderwater(new THREE.MeshBasicMaterial({ name: 'Tile' }));
+ patchUnderwater(new THREE.ShaderMaterial({ name: 'Ocean' }));
+ return { quiet, said };
+ })(),
+}));
+""")
+ fs = out["fs"]
+ assert out["color"] == 0x123456
+ assert "vec3 subVeil = uSubColor * uSubLight * (1.0 - subT)" in fs
+ # The veil is dimmed by the light that got this deep, and the blue
+ # is what got this deep — so a lake bottom goes dark, not neon.
+ # (Filtering it per CHANNEL is the more literal physics and was
+ # measured worse on this host: the red of a green-blue water colour
+ # is already near zero in linear, so the deep end clipped to one
+ # channel — region saturation 0.930 -> 0.941, no visible gain.)
+ assert "* exp(-uSubExt.b * subD);" in fs
+ # Contrast, in numbers: two albedos 0.2 apart under transmittance
+ # 0.3 come out 0.06 apart, whatever the veil is.
+ t = 0.3
+ veil = 0.4
+ assert abs(((0.6 * t + veil) - (0.4 * t + veil)) - 0.2 * t) < 1e-12
+ # The veil lands on LIGHT, so it survives in shadow — which is
+ # where a submerged surface loses its contrast hardest. Two
+ # materials cannot carry that term, and both are named out loud.
+ assert out["warned"]["quiet"] == 0
+ said = out["warned"]["said"]
+ assert len(said) == 3, said
+ assert "Tile" in said[0] and "totalEmissiveRadiance" in said[0]
+ # A raw ShaderMaterial is told BOTH things: it has no emissive term
+ # and it has no <color_fragment> hook to be patched at either.
+ assert "Ocean" in said[1] and "totalEmissiveRadiance" in said[1]
+ assert "Ocean" in said[2] and "<color_fragment>" in said[2]
+
+
+def test_the_column_has_a_colour_a_dither_and_a_lamp_to_scatter():
+ """The three things this host's own frames asked for, added
+ 2026-09-01 and each measured on them.
+
+ Turbidity is a HUE, not a second dimmer: the silt field that swings
+ the path swings the extinction SPECTRUM (silt scatters green and
+ drinks blue) and the veil's own colour with it, or a whole basin is
+ one flat teal. The swings are bounded so no coefficient can go
+ negative and amplify with depth. A basin is also a hundred pixels
+ of a smooth exponential, which is where 8-bit output lays contours —
+ measured: the longest constant run across the deep water fell from
+ 31 px to 7. And the veil is scattered LIGHT that lands on the
+ emissive term, so nothing in the scene dims it: without ``light``
+ the same green glows through a night frame (measured: the night
+ basin read (9, 73, 71) against a 0.25 frame and (7, 42, 53) once it
+ was turned down — green above blue, which is a daylight pool).
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchUnderwater } from './lib/submerged.js';
+const sh = fake();
+const m = patchUnderwater(new THREE.MeshStandardMaterial(), { murk: 0.8 });
+m.onBeforeCompile(sh);
+const u = (mat, k) => mat.userData.uniforms[k].value;
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ vs: sh.vertexShader,
+ light: u(m, 'uSubLight'),
+ night: u(patchUnderwater(new THREE.MeshStandardMaterial(),
+ { light: 0.22 }), 'uSubLight'),
+ neg: u(patchUnderwater(new THREE.MeshStandardMaterial(),
+ { light: -4 }), 'uSubLight'),
+ lit: u(patchUnderwater(new THREE.MeshStandardMaterial(),
+ { light: 2.5 }), 'uSubLight'),
+}));
+""")
+ fs = out["fs"]
+ # The spectrum rides the same field as the path, so it costs one
+ # fbm and it drifts with the silt rather than being a static stain.
+ assert "vec3 subK = uSubExt" in fs
+ assert "* vec3(1.0, 1.0 - 0.30 * subS, 1.0 + 1.60 * subS);" in fs
+ assert "vec3 subT = exp(-subK * ((subD + subView) * subMk));" in fs
+ # murk <= 1 and the field bottoms out at -0.44, so subS >= -0.44 and
+ # every coefficient stays positive: 1 - 0.30*(-0.44) and
+ # 1 + 1.60*(-0.44) are both above zero, and so is the top end.
+ for sub_s in (-0.44, 0.435):
+ assert 1.0 - 0.30 * sub_s > 0, sub_s
+ assert 1.0 + 1.60 * sub_s > 0, sub_s
+ # The veil's own colour breaks with the same field, which is where
+ # the murk becomes VISIBLE — inside the exponent it only moves an
+ # already-saturated exponential.
+ assert ("subVeil = astraHueBreak(subQ" not in fs), "the field, not the p"
+ assert "subVeil = astraHueBreak(subVeil, subQ, 1.0," in fs
+ assert "0.30 + 0.9 * uSubMurk);" in fs
+ # Dither, per pixel, on the veil — and in the FRAGMENT stage only:
+ # gl_FragCoord does not exist in a vertex shader and this patch's
+ # GLSL ships into both.
+ assert "subVeil *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.07;" in fs
+ assert "gl_FragCoord" not in out["vs"]
+ # The lamp: 1 by default (so a daylight scene is unchanged), a
+ # night scene turns it down, a lit pool can turn it up, and a
+ # negative would SUBTRACT light and punch black holes in the water.
+ assert out["light"] == 1
+ assert out["night"] == 0.22
+ assert out["neg"] == 0
+ assert out["lit"] == 2.5
+ assert "uniform float uSubLight;" in fs
+
+
+def test_rings_expand_and_fade_with_age_instead_of_popping():
+ """A ring on water is a place on the surface the wave has reached,
+ and the four things that keep it from reading as a sprite are all
+ measurable. The CARD does not grow — its size is the drop's, never
+ the age's — so what moves is the wavefront inside it. The front
+ DECELERATES, so a frozen frame catches rings bunched at the rim and
+ wide apart near the impact instead of evenly spaced. Amplitude
+ falls as the same water spreads over a longer front, and the whole
+ ring is born through a smoothstep so it cannot appear at full
+ strength. And it is a crest, a trailing crest and a DARK trough
+ between them: a lone white circle is a decal.
+ """
+ out = _measure("""
+import { makeRainRings } from './lib/submerged.js';
+const m = makeRainRings({ count: 8 }).material;
+console.log(JSON.stringify({
+ vs: m.vertexShader, fs: m.fragmentShader,
+}));
+""")
+ vs, fs = out["vs"], out["fs"]
+ # The card is sized by the drop, not by its age: vAge must not
+ # reach the vertex displacement at all.
+ assert "* (uRingSize * iExtra.y);" in vs
+ disp = vs[vs.rindex("transformed ="):]
+ assert "vAge" not in disp, disp
+ # The front travels, and decelerates.
+ assert "float rgFront = 0.90 * pow(vAge, 0.62);" in fs
+ assert "float rgA = (rgR - rgFront) / rgW;" in fs
+ # Amplitude falls as the front lengthens, the ring dies with age,
+ # and it is born soft rather than at full strength.
+ assert "float rgFade = (1.0 - vAge) * smoothstep(0.0, 0.07, vAge)" in fs
+ assert "/ (1.0 + 2.2 * rgFront);" in fs
+ # Crest, capillary train, and the dark trough between them.
+ assert "float rgCrest = exp(-rgA * rgA);" in fs
+ assert "float rgTrain = 0.40 * exp(-rgB * rgB);" in fs
+ assert "float rgDip = 0.30 * exp(-rgD * rgD);" in fs
+ assert "mix(uRingTrough, uRingColor," in fs
+ # Antialiased against its own gradient: a 5 cm crest 20 m off is
+ # thinner than a pixel and would alias into a dotted circle.
+ assert "float rgAA = max(fwidth(rgR), 0.002);" in fs
+ assert "rgAA * 1.6);" in fs
+ # And a ring thinner than a couple of pixels does not draw at all,
+ # because at that size it can only alias into a hard little square.
+ assert "rgFade *= smoothstep(rgAA * 1.2, rgAA * 3.5, rgFront);" in fs
+
+ # And the profile the shipped constants give, in numbers.
+ def front(age):
+ return 0.90 * age ** 0.62
+
+ def peak(age):
+ return ((1.0 - age) * min(1.0, _smooth(age, 0.0, 0.07))
+ / (1.0 + 2.2 * front(age)))
+
+ ages = [0.05, 0.2, 0.5, 0.8, 0.95]
+ radii = [front(a) for a in ages]
+ assert radii == sorted(radii), radii
+ peaks = [peak(a) for a in ages[1:]]
+ assert peaks == sorted(peaks, reverse=True), peaks
+ # Born at nothing, not at half: a ring that pops is the failure.
+ assert peak(0.0) == 0 and peak(0.001) < 0.02
+ # Decelerating: the first half of the life covers most of the run.
+ assert front(0.5) > 0.6 * front(1.0)
+
+
+def test_every_drop_catches_its_own_patch_of_sky():
+ """A field of rings all one colour reads as printed. The swing is
+ per IMPACT — hashed on the same cycle index the relocation uses, so
+ it changes when the drop lands somewhere new — and it is carried to
+ the fragment as a varying rather than sampled per pixel, or one ring
+ would come out speckled instead of one wave. Measured on this
+ host's frames it is a small effect (a peak of 3/255 over a 0.42
+ field), which is why it is per drop and not per pixel: it is the
+ difference between a rain field and a decal sheet, not a look.
+ """
+ out = _measure("""
+import { makeRainRings } from './lib/submerged.js';
+const m = makeRainRings({ count: 8 }).material;
+console.log(JSON.stringify({ vs: m.vertexShader, fs: m.fragmentShader }));
+""")
+ vs, fs = out["vs"], out["fs"]
+ assert "varying float vRgT;" in vs and "varying float vRgT;" in fs
+ # Hashed on the cycle, so a relocated drop is a new drop.
+ assert "vRgT = astraHash21(vec2(iExtra.z + 2.7, rgCyc)) - 0.5;" in vs
+ # Warm one, cool the next, about whatever crest colour was given.
+ assert "rgCol *= 1.0 + vRgT * vec3(0.34, 0.14, -0.24);" in fs
+ # It rides the colour, never the alpha: a ring that varied its own
+ # opacity would flicker as drops relocate.
+ tail = fs[fs.index("vRgT * vec3"):]
+ assert "a =" not in tail, tail
+ # And it is centred, so the field's mean colour is the one asked
+ # for: 0.5 of the range each way about 1.0.
+ assert 0.34 * 0.5 < 0.2 and 0.24 * 0.5 < 0.2
+
+
+def test_the_ring_field_is_rain_and_survives_the_render_passes():
+ """A field of transparent cards has two ways to wreck a frame that
+ have nothing to do with how it looks. An ambient-occlusion pass
+ redraws the scene with an opaque override material, where every one
+ of these is a solid wall, so the field must be kept out of the depth
+ passes; and ``position`` is all zeros (the same override draws it
+ raw), so without a stated bounding sphere three culls the whole
+ field the moment the origin leaves frame. Beyond that it has to be
+ RAIN: the impacts relocate every cycle, or the same eight spots
+ dimple forever, and their phases are spread so one still shows every
+ radius at once.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { makeRainRings } from './lib/submerged.js';
+const mesh = makeRainRings({ area: 30, count: 200, y: 1.5, size: 0.8 });
+const g = mesh.geometry;
+const ph = g.attributes.iExtra.array;
+const phases = [];
+for (let i = 0; i < 200; i++) phases.push(ph[i * 3]);
+phases.sort((a, b) => a - b);
+const num = makeRainRings({ area: 12, count: 4 });
+const obj = makeRainRings({ area: { x: 0, z: 0, w: 12, d: 12 }, count: 4 });
+console.log(JSON.stringify({
+ vs: mesh.material.vertexShader,
+ name: mesh.name, order: mesh.renderOrder,
+ noOverride: mesh.userData.astraNoOverride,
+ casts: mesh.castShadow,
+ transparent: mesh.material.transparent,
+ depthWrite: mesh.material.depthWrite,
+ radius: g.boundingSphere.radius,
+ posZero: Array.from(g.attributes.position.array).every((v) => v === 0),
+ hasCorner: !!g.attributes.aCorner,
+ instances: g.instanceCount,
+ ys: [g.attributes.iOff.array[1], g.attributes.iOff.array[4]],
+ lo: phases[0], hi: phases[199],
+ numArea: Array.from(num.geometry.attributes.iOff.array).every(Number.isFinite),
+ sameArea: Array.from(num.geometry.attributes.iOff.array).join(',')
+ === Array.from(obj.geometry.attributes.iOff.array).join(','),
+ jit: mesh.material.uniforms.uRingJit.value,
+}));
+""")
+ assert out["name"] == "RainRings"
+ # Out of the AO/override passes, and not casting a shadow either.
+ assert out["noOverride"] is True and out["casts"] is False
+ assert out["transparent"] and out["depthWrite"] is False
+ assert out["order"] == 2
+ # A real radius, big enough for the field it covers (a 30 m square
+ # of 0.8 m rings 1.5 m up), and geometry three can cull honestly.
+ assert out["posZero"] and out["hasCorner"]
+ assert out["instances"] == 200
+ assert out["radius"] > 21, out["radius"]
+ assert out["radius"] < 40, "a radius that large stops culling at all"
+ # Lying just above the water, not in it.
+ assert all(abs(y - 1.512) < 1e-6 for y in out["ys"]), out["ys"]
+ # Phases spread over the whole cycle: one still shows all radii.
+ assert out["lo"] < 0.05 and out["hi"] > 0.95, (out["lo"], out["hi"])
+ # `area: 12` is a square, not an undefined width — a truthy number
+ # read as an object put every ring at NaN in rain.js.
+ assert out["numArea"] and out["sameArea"]
+ # Impacts relocate every cycle, inside their own share of the rect.
+ vs = out["vs"]
+ assert "float rgCyc = floor(rgP);" in vs
+ assert "astraHash21(vec2(iExtra.z, rgCyc))" in vs
+ assert "* uRingJit;" in vs
+ assert abs(out["jit"] - math.sqrt(900 / 200)) < 1e-6, out["jit"]
+
+
+def test_ice_cracks_branch_instead_of_being_one_noise_call():
+ """The one thing that separates ice from cracked paint. A crack
+ leaves an origin and FORKS, so the pattern doubles its ray count
+ every step outward with the phase scaled to match — which keeps
+ every existing ray exactly where it was and grows a new one between
+ them — and cross-fades the two levels so the new arm narrows in
+ rather than switching on. Written with a per-level phase instead,
+ the rays would jump to new angles at every ring and the network
+ would be concentric bands; written with one fbm it would be a smear.
+ The nesting is arithmetic, so it can be measured.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchThinIce } from './lib/submerged.js';
+const sh = fake();
+patchThinIce(new THREE.MeshStandardMaterial()).onBeforeCompile(sh);
+const fs = sh.fragmentShader;
+// The shipped ray-distance function, transcribed: rays are where it
+// touches zero, so scanning for zeros IS scanning for rays.
+const ray = (a, n, j) => {
+ const x = (a * 0.15915494 + j) * n;
+ return Math.abs(x - Math.floor(x + 0.5)) / n;
+};
+const rays = (n, j) => {
+ const found = [];
+ const N = 200000;
+ for (let i = 0; i < N; i++) {
+ const a = -Math.PI + (2 * Math.PI * i) / N;
+ const p = ray(a - 2 * Math.PI / N, n, j);
+ const c = ray(a, n, j);
+ const q = ray(a + 2 * Math.PI / N, n, j);
+ if (c < p && c <= q) found.push(a);
+ }
+ return found;
+};
+const j = 0.37;
+const at3 = rays(3, j), at6 = rays(6, j);
+const near = (x, list) => list.some((y) => Math.abs(x - y) < 1e-3);
+console.log(JSON.stringify({
+ fs,
+ n3: at3.length, n6: at6.length,
+ nested: at3.every((a) => near(a, at6)),
+ rayCalls: (fs.match(/astraIceRay\\(/g) || []).length,
+ crackCalls: (fs.match(/astraIceCracks\\(/g) || []).length,
+}));
+""")
+ fs = out["fs"]
+ # The phase is added BEFORE the ray count multiplies it, which is
+ # what makes level n a subset of level 2n.
+ assert "float x = (atan(d.y, d.x) * 0.15915494 + j) * n;" in fs
+ assert "float g = abs(x - k) / n * 6.2831853 * max(length(d), 0.18);" in fs
+ # Doubling, and the same j for both levels.
+ assert "float n = 3.0 * exp2(lv);" in fs
+ assert "vec2 ra = astraIceRay(d, n, j);" in fs
+ assert "vec2 rb = astraIceRay(d, n * 2.0, j);" in fs
+ assert "float g = mix(ra.x, rb.x, f);" in fs
+ assert "float lv = floor(r * 3.0);" in fs
+ assert "float f = fract(r * 3.0);" in fs
+ # Measured: twice as many rays one level out, and every old one is
+ # still there. That is a fork, not a redraw.
+ assert out["n3"] == 3 and out["n6"] == 6, (out["n3"], out["n6"])
+ assert out["nested"], "a branch keeps its parent"
+ # And no two arms are the same length, or the fork is a snowflake.
+ assert "float reach = mix(astraHash21(id + ra.y * 0.37 + 5.0)," in fs
+ assert "reach = 0.30 + 0.55 * reach;" in fs
+ assert "* (1.0 - smoothstep(reach * 0.55, reach, r));" in fs
+ # One definition, called twice per layer and two layers deep, so
+ # the cell grid does not read as a grid — and the dark fissure core
+ # is taken from the SAME field by a smoothstep rather than a third
+ # and fourth call.
+ assert out["rayCalls"] == 3, out["rayCalls"]
+ assert out["crackCalls"] == 3, "one helper, two rotated layers"
+ assert "float iceCr = max(astraIceCracks(iceP, iceW)," in fs
+ assert "astraIceCracks(iceQ, iceW * 0.55));" in fs
+ assert "float iceCore = smoothstep(0.55, 0.98, iceCr);" in fs
+ assert "iceC *= 1.0 - 0.55 * iceCore;" in fs
+ # Crooked, not ruled, and antialiased against its own gradient.
+ assert "iceP += (astraNoise2(iceP * 0.9 + 5.7) - 0.5) * 0.35;" in fs
+ # A crack is 2 cm of ice at any density, so its width is stated in
+ # metres and scaled by the density rather than left in cell units.
+ assert "float iceW = max(uIceDens * 0.022," in fs
+ assert "max(fwidth(iceP.x), fwidth(iceP.y)) * 1.3);" in fs
+
+
+def test_thin_ice_has_a_depth_a_rim_a_gloss_and_a_fresnel():
+ """Ice over water is a SLAB, and three layers at three depths are
+ what say so. The interior is sampled where the eye ray arrives
+ after refracting at the surface and running down by the thickness,
+ so it slides against the surface as the camera moves — the cracks
+ are sampled unrefracted and therefore sit above it. Thickness also
+ tints, at 1.6 per metre: ice is CLEAR, and at the 3.0 this shipped
+ with a 10 cm sheet mixed a quarter of a pale mint over the dark
+ water and reached an albedo of 0.25 linear, which on a sunlit
+ horizontal plane is 200/255 before a crack is drawn.
+
+ And the interior sits behind a FRESNEL while the two surface layers
+ do not, because only what the air-ice interface let in ever reached
+ the bubbles. Our renderer adds that reflection itself as specular,
+ so without the term the sheet is paid for the sky twice — measured
+ here at an 11 deg view: a flat plate at 200/255 with no visible
+ crack. Gloss can only be a MATERIAL value (the hook runs before
+ roughness exists), so frostier ice is duller through
+ composeRoughness.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchThinIce } from './lib/submerged.js';
+const sh = fake();
+const m = patchThinIce(new THREE.MeshStandardMaterial({ roughness: 0.8 }),
+ { thickness: 0.2, crackDensity: 1.5, frost: 0.5, rim: 0.3,
+ color: 0x445566 });
+m.onBeforeCompile(sh);
+const u = (mat, k) => mat.userData.uniforms[k].value;
+const glassy = patchThinIce(
+ new THREE.MeshStandardMaterial({ roughness: 0.8 }), { frost: 0 });
+const frosty = patchThinIce(
+ new THREE.MeshStandardMaterial({ roughness: 0.8 }), { frost: 1 });
+console.log(JSON.stringify({
+ fs: sh.fragmentShader, vs: sh.vertexShader,
+ thick: u(m, 'uIceThick'), dens: u(m, 'uIceDens'),
+ frost: u(m, 'uIceFrost'), rim: u(m, 'uIceRim'),
+ color: u(m, 'uIceColor').getHex(),
+ zeroThick: u(patchThinIce(new THREE.MeshStandardMaterial(),
+ { thickness: 0 }), 'uIceThick'),
+ zeroRim: u(patchThinIce(new THREE.MeshStandardMaterial(),
+ { rim: 0 }), 'uIceRim'),
+ rough: m.roughness, glassy: glassy.roughness, frosty: frosty.roughness,
+ base: m.userData.astraRoughness.base,
+}));
+""")
+ fs, vs = out["fs"], out["vs"]
+ assert out["thick"] == 0.2 and out["dens"] == 1.5
+ assert out["frost"] == 0.5 and out["rim"] == 0.3
+ assert out["color"] == 0x445566
+ # Refraction at the surface, then down by the thickness: that
+ # parallax IS the depth, and eta < 1 so refract() cannot return the
+ # zero vector and there is no total-internal-reflection case.
+ assert "vec3 iceRf = refract(iceV, iceN, 0.763);" in fs
+ assert "iceN = faceforward(iceN, iceV, iceN);" in fs
+ assert "+ iceRf.xz * (uIceThick / max(abs(iceRf.y), 0.25));" in fs
+ assert "float iceB = astraFbm2(icePar * 2.6 + uIceSeed, 3);" in fs
+ # The cracks take the UNREFRACTED point, so they stay on top.
+ assert "vec2 iceP = vAstraWorld.xz * uIceDens + uIceSeed;" in fs
+ # Thickness tints as a column, so thin ice is not thick ice — and
+ # 10 cm of it is nearly nothing, which is what 1.6 per metre says.
+ assert "float iceK = 1.0 - exp(-uIceThick * 1.6);" in fs
+ assert "vec3 iceC = mix(diffuseColor.rgb, uIceColor, iceK);" in fs
+ assert 1 - math.exp(-0.10 * 1.6) < 0.16, "a 10 cm sheet is see-through"
+ assert 1 - math.exp(-1.00 * 1.6) > 0.75, "a metre of it is not"
+ # The FRESNEL, and the ORDER around it: interior first and behind
+ # it, cracks and frost after and in front of it.
+ assert "float iceFz = astraFresnel(iceN, -iceV, 5.0);" in fs
+ assert "iceC *= 1.0 - 0.78 * iceFz;" in fs
+ assert fs.index("iceFz;") < fs.index("float iceCr ="), "cracks are surface"
+ assert fs.index("iceFz;") < fs.index("float iceFr ="), "frost is on top"
+ assert fs.index("astraHueBreak(iceC") < fs.index("iceFz;"), "bubbles are in"
+ # Schlick's shape, in numbers: nothing at normal incidence, most of
+ # it at the grazing angles a frozen pond is usually seen at.
+ assert (1 - 1.0) ** 5 == 0
+ assert (1 - 0.196) ** 5 > 0.3, "an 11 deg view is a third reflected"
+ # Broken colour in all three layers: bubble cloud, crack lip, frost.
+ assert "iceC = astraHueBreak(iceC, icePar * 1.4, 1.0, 0.30);" in fs
+ assert "vec3(0.87, 0.93, 0.96) * (0.84 + 0.30 * iceB)," in fs
+ assert "vec3 iceFc = astraHueBreak(" in fs
+ assert "vAstraWorld.xz, 0.8, 0.22);" in fs
+ # The rim is the sheet's own border, torn by noise. The uv comes
+ # through this patch's own varying: three declares vUv only when
+ # the material happens to carry a map.
+ assert "varying vec2 vAstraIceUv;" in vs and "vAstraIceUv = uv;" in vs
+ assert "float iceE = min(min(vAstraIceUv.x, 1.0 - vAstraIceUv.x)," in fs
+ assert "* uIceRim * 0.9;" in fs
+ assert "float iceFr = astraContact(iceE, uIceRim) * uIceFrost;" in fs
+ # A sheet is a wide smooth ramp, so it carries its own dither too.
+ assert "iceC *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.03;" in fs
+ assert "gl_FragCoord" not in vs
+ # Zeros that would divide or smoothstep over an empty band.
+ assert out["zeroThick"] > 0 and out["zeroRim"] > 0
+ # Gloss through composeRoughness only, off the material's TRUE
+ # base, so re-applying cannot compound it.
+ assert out["base"] == 0.8
+ assert out["glassy"] < out["frosty"] < 0.8, out
+ assert abs(out["glassy"] - 0.8 * 0.18) < 1e-9
+ assert abs(out["frosty"] - 0.8 * 0.80) < 1e-9
+ assert "roughnessFactor" not in fs
+
+
+def test_its_names_collide_with_none_of_the_libraries_it_lands_on():
+ """The failure with no symptom. dedupeUniforms drops a repeated
+ ``uniform`` declaration and keeps the FIRST, so a name this library
+ shares with caustics or the waterline would silently read the
+ other's number for the rest of the run. A repeated local is the
+ opposite and just as fatal: every patch on a material shares ONE
+ injected main, and a redeclared local is a redefinition that takes
+ the whole material down. A submerged, weathered, splatted bank
+ wears all of these at once, so both sets must be disjoint from all
+ of them — with uTime and the world varyings the deliberate shares.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchUnderwater, patchThinIce } from './lib/submerged.js';
+import { patchCaustics } from './lib/caustics.js';
+import { patchShoreWet, patchShoreFoam, patchShallowWater }
+ from './lib/waterside.js';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+import { patchDripStains, patchRust, patchDust } from './lib/aging.js';
+import { GLSL_UTIL } from './lib/shader.js';
+const mineSh = fake(), sibSh = fake();
+const mine = new THREE.MeshStandardMaterial();
+patchUnderwater(mine); patchThinIce(mine);
+mine.onBeforeCompile(mineSh);
+const sib = new THREE.MeshStandardMaterial();
+patchCaustics(sib);
+patchShoreWet(sib); patchShoreFoam(sib); patchShallowWater(sib);
+patchTriplanar(sib); patchSlopeSplat(sib);
+patchDripStains(sib); patchRust(sib); patchDust(sib);
+sib.onBeforeCompile(sibSh);
+const fns = (src) => (src.match(/^\\s*(?:float|vec[234]|void)\\s+(\\w+)\\s*\\(/gm)
+ || []).map((h) => h.trim().split(/[\\s(]+/)[1]);
+console.log(JSON.stringify({
+ mineU: Object.keys(mine.userData.uniforms),
+ sibU: Object.keys(sib.userData.uniforms),
+ mineL: locals(mains(mineSh)),
+ sibL: locals(mains(sibSh)),
+ util: fns(GLSL_UTIL),
+ mineF: fns(mineSh.fragmentShader.slice(
+ 0, mineSh.fragmentShader.indexOf('void main'))),
+ sibF: fns(sibSh.fragmentShader.slice(
+ 0, sibSh.fragmentShader.indexOf('void main'))),
+}));
+""")
+ shared_uniforms = set(out["mineU"]) & set(out["sibU"])
+ assert shared_uniforms == {"uTime"}, shared_uniforms
+ assert all(u.startswith(("uSub", "uIce"))
+ for u in out["mineU"] if u != "uTime"), out["mineU"]
+ shared_locals = set(out["mineL"]) & set(out["sibL"])
+ assert shared_locals == set(), shared_locals
+ assert all(x.startswith(("sub", "ice")) for x in out["mineL"]), out["mineL"]
+ # Nothing declared twice inside this library's own bodies either.
+ assert len(out["mineL"]) == len(set(out["mineL"])), out["mineL"]
+ # And the helpers: patchStandard THROWS on a colliding function
+ # name with a different body, which would take out every scene that
+ # put a frozen pond next to a rusted rail.
+ util = set(out["util"])
+ mine_own = set(out["mineF"]) - util
+ sib_own = set(out["sibF"]) - util
+ assert mine_own == {"astraIceRay", "astraIceCracks"}, mine_own
+ assert mine_own & sib_own == set(), mine_own & sib_own
+
+
+def test_the_whole_chain_shares_one_main_without_a_redefinition():
+ """The load-bearing case: a pool floor wears the rock projection,
+ the waterline, this column and the caustic net at once.
+ patchStandard chains by name, so every body must survive in call
+ order, the cache key must name the whole chain (the first material
+ to compile a key decides the source for all of them), the world
+ varyings must be declared once however many patches ask for them,
+ and re-applying a patch must retune it rather than stack a second.
+ Order matters here beyond compiling: the column runs BEFORE the net,
+ so the net is tinted by the already-extinguished albedo.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchUnderwater } from './lib/submerged.js';
+import { patchCaustics } from './lib/caustics.js';
+import { patchShoreWet } from './lib/waterside.js';
+import { patchTriplanar } from './lib/terrain_shade.js';
+const sh = fake();
+const m = new THREE.MeshStandardMaterial();
+patchTriplanar(m);
+patchShoreWet(m, { level: 1.2 });
+patchUnderwater(m, { level: 1.2, seed: 4 });
+patchCaustics(m, { level: 1.2, depthFade: 2.8 });
+patchUnderwater(m, { level: 1.4, seed: 4 }); // retune, not a 5th patch
+m.onBeforeCompile(sh);
+const fs = sh.fragmentShader, vs = sh.vertexShader;
+const count = (s, re) => (s.match(re) || []).length;
+const seen = {};
+for (const name of locals(mains(sh))) seen[name] = (seen[name] || 0) + 1;
+console.log(JSON.stringify({
+ key: m.customProgramCacheKey(),
+ level: m.userData.uniforms.uSubLevel.value,
+ order: fs.indexOf('subT') < fs.indexOf('cauNet'),
+ tri: fs.includes('mix(uTriA, uTriB'),
+ sub: fs.includes('diffuseColor.rgb *= subT;'),
+ cau: fs.includes('totalEmissiveRadiance += cauTint'),
+ varyingVs: count(vs, /varying vec3 vAstraWorld;/g),
+ varyingFs: count(fs, /varying vec3 vAstraWorld;/g),
+ utilOnce: count(fs, /float astraFbm2\\(/g),
+ timeOnce: count(fs, /uniform float uTime;/g),
+ uniforms: ['uTriA', 'uWetY', 'uSubExt', 'uCauLevel', 'uTime']
+ .every((k) => !!sh.uniforms[k]),
+ dupLocals: Object.keys(seen).filter((k) => seen[k] > 1),
+}));
+""")
+ assert out["tri"] and out["sub"] and out["cau"], out
+ assert out["key"] == ("astra:terrain:world+terrain:triplanar"
+ "+waterside:base+waterside:shoreWet"
+ "+submerged:base+submerged:underwater"
+ "+caustics:net")
+ # The column runs first, so patchCaustics tints its net with the
+ # albedo this has already taken the red out of.
+ assert out["order"], "bodies run in call order"
+ assert out["level"] == 1.4, "re-applying retunes in place"
+ assert out["uniforms"], "every patch's uniforms reach the program"
+ # The world varyings are shared with the neighbours BY NAME on
+ # purpose, so the pair is declared once for the four of them.
+ assert out["varyingVs"] == 1 and out["varyingFs"] == 1
+ assert out["utilOnce"] == 1 and out["timeOnce"] == 1
+ assert out["dupLocals"] == [], out["dupLocals"]
+
+
+def test_it_is_deterministic_stage_safe_and_tickable():
+ """A pool must come back identical on a re-render, so every seed is
+ arithmetic and never a Math.random; the patches' GLSL ships into the
+ VERTEX stage too, where a fragment-only builtin would fail every
+ program in the engine at once; and every one of these rides uTime,
+ so ONE ``tickShaders(scene, t)`` has to reach all of them — an
+ un-advanced uTime is a frozen silt and a frozen ring.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchUnderwater, patchThinIce, makeRainRings }
+ from './lib/submerged.js';
+import { tickShaders } from './lib/shader.js';
+const a = fake(), b = fake();
+const opts = { level: 1.5, seed: 9, extinction: 0.5 };
+const ma = patchUnderwater(new THREE.MeshStandardMaterial(), opts);
+const mb = patchUnderwater(new THREE.MeshStandardMaterial(), opts);
+patchThinIce(ma, { seed: 9 }); patchThinIce(mb, { seed: 9 });
+ma.onBeforeCompile(a);
+mb.onBeforeCompile(b);
+const seed = (m, k) => m.userData.uniforms[k].value;
+const s8 = patchUnderwater(new THREE.MeshStandardMaterial(), { seed: 8 });
+const r1 = makeRainRings({ seed: 4, count: 6 });
+const r2 = makeRainRings({ seed: 4, count: 6 });
+const r3 = makeRainRings({ seed: 5, count: 6 });
+const arr = (m) => Array.from(m.geometry.attributes.iOff.array);
+
+// One tick, every material: a patched floor and the ring field.
+const g = new THREE.Group();
+const floor = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), ma);
+g.add(floor, r1);
+const n = tickShaders(g, 7.5);
+console.log(JSON.stringify({
+ same: a.fragmentShader === b.fragmentShader
+ && a.vertexShader === b.vertexShader,
+ seedA: seed(ma, 'uSubSeed'), seedB: seed(mb, 'uSubSeed'),
+ seed8: seed(s8, 'uSubSeed'),
+ iceSeed: seed(ma, 'uIceSeed'),
+ ringsSame: arr(r1).join(',') === arr(r2).join(','),
+ ringsDiffer: arr(r1).join(',') !== arr(r3).join(','),
+ ticked: n,
+ matTime: ma.userData.uniforms.uTime.value,
+ ringTime: r1.material.uniforms.uTime.value,
+ updateTime: (() => { r1.userData.update(2.25);
+ return r1.material.uniforms.uTime.value; })(),
+ vsBody: a.vertexShader.slice(a.vertexShader.indexOf('void main')),
+ vsHead: a.vertexShader.slice(0, a.vertexShader.indexOf('void main')),
+}));
+""")
+ assert out["same"], "one seed, one shader"
+ assert out["seedA"] == out["seedB"]
+ # A seed must MOVE the lattice, not shift it by a cell — a one-cell
+ # offset is the same pool drawn twice.
+ assert abs(out["seed8"]["x"] - out["seedA"]["x"]) > 5, out["seed8"]
+ assert out["seedA"] != out["iceSeed"] or out["seedA"]["x"] > 0
+ assert out["ringsSame"] and out["ringsDiffer"]
+ # One call reaches the patched material AND the ring field.
+ assert out["ticked"] == 2, out["ticked"]
+ assert out["matTime"] == 7.5 and out["ringTime"] == 7.5
+ assert out["updateTime"] == 2.25, "its own update still works"
+ # Nothing of these patches reaches the vertex stage but the world
+ # position and the uv: fwidth there is only GLSL_UTIL's, behind
+ # ASTRA_FRAG, and the crack helpers are fragment work.
+ assert "fwidth" not in out["vsBody"]
+ assert "astraIceCracks" not in out["vsHead"]
+ assert "astraIceRay" not in out["vsHead"]
+
+ src = _LIB.read_text(encoding="utf-8")
+ assert "Math.random" not in src
+ assert "Date.now" not in src
+ assert src.count("\nexport ") == 3
+ for name in ("patchUnderwater", "makeRainRings", "patchThinIce"):
+ assert "export function " + name in src
+ assert max(len(ln) for ln in src.splitlines()) <= 80
+
+
+_SCENE = """
+import * as THREE from 'three';
+import { patchUnderwater, patchThinIce, makeRainRings }
+ from './lib/submerged.js';
+import { patchCaustics } from './lib/caustics.js';
+import { patchTriplanar } from './lib/terrain_shade.js';
+import { tickShaders } from './lib/shader.js';
+
+export const BOUNDS = { min: [-8, -1, -6], max: [8, 5, 6] };
+
+const LEVEL = 1.45;
+const SUN = new THREE.Vector3(0.45, 0.75, 0.35);
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ // Without this USE_FOG is undefined and every fog branch compiles to
+ // nothing — which is how a library ships fog chunks that cannot
+ // compile at all and nobody finds out.
+ scene.fog = new THREE.FogExp2(0x9dbcd8, 0.018);
+ scene.background = new THREE.Color(0x9dbcd8);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ // And without a shadow CASTER the depth variant of every patched
+ // material is never compiled either.
+ const sun = new THREE.DirectionalLight(0xfff0d6, 2.6);
+ sun.position.set(6, 9, 5);
+ sun.castShadow = true;
+ scene.add(sun);
+
+ // ONE material wearing the rock projection, the column and the net:
+ // the chain this library exists to survive.
+ const tile = new THREE.MeshStandardMaterial(
+ { color: 0x5a6a62, roughness: 0.9 });
+ patchTriplanar(tile, { scale: 1.4 });
+ patchUnderwater(tile, { level: LEVEL, extinction: 0.34, seed: 2,
+ light: 0.6 });
+ patchCaustics(tile, { level: LEVEL, sunDir: SUN, depthFade: 2.9 });
+
+ const floor = new THREE.Mesh(new THREE.BoxGeometry(11, 0.3, 8), tile);
+ floor.position.set(0, 0.15, 0);
+ floor.receiveShadow = true;
+ scene.add(floor);
+
+ // Steps straddling the line: two under it, two above.
+ for (let i = 0; i < 4; i++) {
+ const h = 0.5 * (i + 1);
+ const step = new THREE.Mesh(new THREE.BoxGeometry(0.8, h, 4), tile);
+ step.position.set(4.4 - i * 0.8, 0.3 + h / 2, 1.6);
+ step.castShadow = step.receiveShadow = true;
+ scene.add(step);
+ }
+
+ // A boulder half under, and instanced cobbles so the USE_INSTANCING
+ // branch of the shared base has to compile too.
+ const rock = new THREE.MeshStandardMaterial(
+ { color: 0x6f6559, roughness: 0.95 });
+ patchTriplanar(rock, { scale: 0.9 });
+ patchUnderwater(rock, { level: LEVEL, seed: 5 });
+ patchCaustics(rock, { level: LEVEL, sunDir: SUN, seed: 3 });
+ const boulder = new THREE.Mesh(
+ new THREE.IcosahedronGeometry(1.15, 2), rock);
+ boulder.position.set(-1.7, 1.2, -1.3);
+ boulder.castShadow = true;
+ scene.add(boulder);
+
+ const pebbles = new THREE.InstancedMesh(
+ new THREE.IcosahedronGeometry(0.32, 1), rock, 12);
+ const m4 = new THREE.Matrix4();
+ for (let i = 0; i < 12; i++) {
+ m4.makeTranslation(-4.4 + i * 0.8, 0.42, -2.7 + (i % 3) * 0.8);
+ pebbles.setMatrixAt(i, m4);
+ }
+ pebbles.castShadow = true;
+ scene.add(pebbles);
+
+ // A sheet of thin ice over a corner of the same pool.
+ const ice = new THREE.MeshStandardMaterial(
+ { color: 0x1c2a30, roughness: 0.5, metalness: 0 });
+ patchThinIce(ice, { thickness: 0.09, crackDensity: 0.8, frost: 0.85 });
+ const sheet = new THREE.Mesh(new THREE.PlaneGeometry(4.4, 3.4), ice);
+ sheet.rotation.x = -Math.PI / 2;
+ sheet.position.set(-3.2, LEVEL, 2.0);
+ sheet.receiveShadow = true;
+ scene.add(sheet);
+
+ // The ring field assembles its OWN shader rather than inheriting
+ // three's, so its fog and depth chunks are only checked here.
+ scene.add(makeRainRings(
+ { area: { x: 2.4, z: -1.2, w: 6, d: 5 }, y: LEVEL, count: 90,
+ size: 0.5, seed: 6 }));
+
+ // A camera, because the host reports a scene with none as not booted
+ // and never reaches the compile stage at all.
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [7, 3, 9], lookAt: [0, 1, 0],
+ fov: 45 }],
+ // One tick drives every patch in the chain; an un-advanced uTime is
+ // a frozen silt and a frozen ring.
+ update(t) { tickShaders(scene, t); },
+ };
+}
+"""
+
+
+def test_the_chain_compiles_on_the_real_renderer():
+ """The only witness that counts. Everything above reads a string;
+ whether the GPU accepts four chained bodies in one main, the
+ instancing branch, a refract into a parallax and two levels of
+ branching cracks per fragment cannot be asserted from source, and a
+ patch that does not compile is worth nothing. The scene sets its
+ own fog, because USE_FOG is a define and a define that is never set
+ compiles nothing — rain.js shipped a fog branch that could not
+ compile at all for months behind exactly that.
+ """
+ code, out = compile_scene(
+ _SCENE, ("shader.js", "submerged.js", "caustics.js",
+ "terrain_shade.js"))
+ assert code == 0, out
+ assert "every program compiled" in out
+ # Patched built-ins keep the built-in's own depth and fog chunks,
+ # and the ring field gets them from makeShaderMaterial — so nothing
+ # here may be flagged as discardable.
+ assert "DISCARDED" not in out
diff --git a/harness/tests/scene_runtime/lib/test_surface_wear.py b/harness/tests/scene_runtime/lib/test_surface_wear.py
new file mode 100644
index 00000000..4be71c05
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_surface_wear.py
@@ -0,0 +1,617 @@
+"""surface_wear.js: the two patches that land on EVERY material.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_surface_wear_lib.py). Its claims are kept as they stood — one
+shared world base, no name a neighbour already owns, every option a uniform
+rather than baked GLSL, one seed one surface, a hard bound on the albedo
+swing, a SIGNED curvature in 1/m for the edge route, and a gloss that
+composes on the material because per-pixel roughness is unreachable from
+<color_fragment>.
+
+THE PORT'S OWN LAWS, and the two regressions this file exists to stop.
+
+1. A HUE JITTER MAY NOT BE A ROTATION ABOUT THE GREY AXIS. The reference
+ shifted hue with `astraHueShift`, and that operator returns a neutral
+ EXACTLY unchanged (c*cos + cross(k,c)*sin + k*dot(k,c)*(1-cos) collapses
+ to c when c is parallel to k). Measured on the albedos this patch is
+ sold for: 0.0 change on a grey, 0.0014 peak channel move on our stone
+ 0x8d8577 at the reference default of 0.03 rad — so the one line meant to
+ make the breakup "a change of MATERIAL rather than a brightness dial" did
+ nothing at all on stone, plaster, concrete and dirt. It is a warm/cool
+ break now (the transfer `astraHueBreak` already uses), and `hue` is a
+ fraction of the albedo. Measured on the showcase host
+ (fx/out/surface_wear, stone drum face, close view): warm/cool spread
+ std((R-B)/(R+G+B)) 0.0132 -> 0.0189, +43%, with the drum's mean luminance
+ unmoved (0.480 -> 0.477).
+
+2. EDGE WEAR MAY NOT DEGENERATE INTO A BARBER POLE. Past ~3x the onset
+ curvature the ramp is saturated, so on anything much thinner than
+ `width` the ONLY structure left is the break-up field — and the
+ reference's was one fixed 14 cm blotch field regardless of the feature.
+ On a 6 cm painted rail post that is alternating solid bands of flat bone
+ white (measured: post region saturation std 0.219, and the same white
+ 0xe8e2d6 on every material wearing the patch). The break-up is two
+ octaves now, both scaled to the `width` asked for, and the worn tone is
+ the object's OWN colour rubbed thin before it is bare substrate, with the
+ substrate itself broken in value and warm/cool. Measured: the worn ring
+ kept its hue (saturation 0.257 -> 0.418 against an unworn control's
+ 0.538) and stopped washing out (luminance 0.496 -> 0.397, p99 0.861 ->
+ 0.807).
+
+3. A RAIL MAY NOT BE POLISHED INTO A SKY MIRROR. Same trap roadway.js
+ found: `fragmentBody` lands before <roughnessmap_fragment>, so the gloss
+ move is the MATERIAL's and must therefore be area-weighted. Wear covers
+ a fraction of a surface; the reference spent 0.35 * strength of polish on
+ all of it. 0.12 here.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from collections import Counter
+
+import pytest
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "terrain_shade.js", "waterside.js", "surface_wear.js")
+
+_LIB_SRC = (LIB_DIR / "surface_wear.js").read_text(encoding="utf-8")
+
+# The patch only exists inside onBeforeCompile, so every probe hands it the
+# two chunks patchStandard replaces and reads back what it wrote.
+_PRELUDE = """
+import * as THREE from 'three';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+import { patchShoreWet, patchShoreFoam } from './lib/waterside.js';
+
+const std = (o = {}) => new THREE.MeshStandardMaterial(
+ Object.assign({ color: 0xb2603a, roughness: 0.6 }, o));
+
+function compile(mat) {
+ const shader = {
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+ };
+ mat.onBeforeCompile(shader);
+ return shader;
+}
+
+const count = (src, needle) => src.split(needle).length - 1;
+"""
+
+# A few primitives plus one instanced set, and ONE material carrying
+# patchTriplanar as well: the plate is where the terrain chain and the wear
+# chain meet, which is the combination that has to compile.
+_SCENE = """
+import * as THREE from 'three';
+import { patchTriplanar } from './lib/terrain_shade.js';
+import { patchMicroBreakup, patchEdgeWear } from './lib/surface_wear.js';
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ const g = new THREE.Group();
+
+ const stone = new THREE.MeshStandardMaterial({
+ color: 0x8d8577, roughness: 0.9,
+ });
+ patchTriplanar(stone, { scale: 2.5 });
+ const plate = new THREE.Mesh(new THREE.BoxGeometry(6, 0.3, 6), stone);
+ plate.position.y = 0.15;
+ g.add(plate);
+
+ const paint = new THREE.MeshStandardMaterial({
+ color: 0xb2603a, roughness: 0.62,
+ });
+ // Flat shading on the box: the patches must not lean on vNormal, which
+ // three omits when FLAT_SHADED.
+ const wall = new THREE.MeshStandardMaterial({
+ color: 0xcdc4b2, roughness: 0.8, flatShading: true,
+ });
+
+ const put = (mesh, x, z, y) => {
+ mesh.position.set(x, 0.3 + y, z);
+ g.add(mesh);
+ return mesh;
+ };
+ put(new THREE.Mesh(new THREE.SphereGeometry(0.45, 48, 32), paint),
+ -1.5, -1.4, 0.45);
+ put(new THREE.Mesh(new THREE.TorusKnotGeometry(0.26, 0.075, 96, 20), paint),
+ 0.2, 0.1, 0.36);
+ put(new THREE.Mesh(new THREE.BoxGeometry(0.9, 0.9, 0.9), wall),
+ -1.6, 1.5, 0.45);
+
+ // The instanced set: the only place USE_INSTANCING is ever compiled.
+ const pebble = new THREE.InstancedMesh(
+ new THREE.IcosahedronGeometry(0.17, 3), wall, 24);
+ const m = new THREE.Matrix4();
+ let s = 7;
+ const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+ for (let i = 0; i < 24; i++) {
+ m.compose(
+ new THREE.Vector3((rand() * 2 - 1) * 2.6, 0.42,
+ (rand() * 2 - 1) * 2.6),
+ new THREE.Quaternion().setFromEuler(
+ new THREE.Euler(rand(), rand() * 3, rand())),
+ new THREE.Vector3(1, 0.8 + rand() * 0.5, 1));
+ pebble.setMatrixAt(i, m);
+ }
+ pebble.instanceMatrix.needsUpdate = true;
+ pebble.frustumCulled = false;
+ g.add(pebble);
+
+ for (const [mat, seed] of [[stone, 3], [paint, 11], [wall, 23]]) {
+ patchMicroBreakup(mat, { seed });
+ patchEdgeWear(mat, { seed });
+ }
+ scene.add(g);
+ // A camera is not decoration here: the host reports `ok: false` with an
+ // EMPTY error when `cameras` is empty, so a scene with none fails the
+ // compile preflight before a program is built.
+ return {
+ scene,
+ cameras: [{ name: 'hero', position: [12, 5, 14], lookAt: [0, 2, 0],
+ fov: 45 }],
+ update() {},
+ };
+}
+"""
+
+
+def _probe(body: str) -> dict:
+ return measure(_PRELUDE + body, _LIBS)
+
+
+def _find(pattern: str, src: str) -> re.Match:
+ m = re.search(pattern, src)
+ assert m, f"{pattern} not in\n{src}"
+ return m
+
+
+def _main_body(src: str) -> str:
+ return src[src.index("void main"):]
+
+
+def _unguarded(src: str) -> str:
+ """Drop `#ifndef X ... #endif` blocks, which may repeat verbatim.
+
+ terrain_shade ships astraFbmUnit from two patches behind one guard, so
+ the TEXT carries it twice and the preprocessor keeps one. Only an
+ unguarded repeat is a redefinition.
+ """
+ return re.sub(r"#ifndef\b.*?#endif", "", src, flags=re.S)
+
+
+def test_both_patches_and_a_triplanar_compile_on_one_material():
+ """The stack this library exists to join: a triplanar terrain patch and
+ both wear patches on ONE material, in a scene that also puts a wear
+ material on an InstancedMesh. Only a real instanced program ever
+ compiles the USE_INSTANCING branch of the world base, and only a real
+ compile proves the two libraries' shared varyings, helpers and locals
+ survive being concatenated into one shader."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out
+ report = json.loads(out.strip().splitlines()[-1])
+ assert report["ok"] and report["errors"] == [], report
+ # Three patched built-ins, and more programs than that: the pebble
+ # material compiled twice, once per instancing state.
+ assert report["compile"]["custom_materials"] >= 3, report
+ assert report["compile"]["programs"] >= 4, report
+ assert report["compile"]["gpu"], report
+
+
+def test_the_two_patches_chain_without_losing_each_other():
+ """Both patches on one material is the ordinary case — a surface that
+ varies but has no worn edges is half the idea. patchStandard chains
+ them, but it repeats whatever it is handed: the shared world base and
+ its two helpers must be emitted ONCE (a second function body is a
+ compile error), and re-applying a patch has to retune its uniforms
+ instead of injecting a second copy of its code."""
+ out = _probe("""
+const m = std();
+patchMicroBreakup(m, { strength: 0.08 });
+patchEdgeWear(m, { strength: 0.5 });
+patchMicroBreakup(m, { strength: 0.12 });
+const s = compile(m);
+const microOnly = std();
+patchMicroBreakup(microOnly);
+console.log(JSON.stringify({
+ key: m.customProgramCacheKey(), microKey: microOnly.customProgramCacheKey(),
+ micro: s.fragmentShader.includes('mbV * uMicroAmt'),
+ edge: s.fragmentShader.includes('ewK * uEdgeAmt'),
+ amt: m.userData.uniforms.uMicroAmt.value,
+ edgeAmt: m.userData.uniforms.uEdgeAmt.value,
+ worldBody: count(s.vertexShader, 'vec4 wrP ='),
+ axesFn: count(s.fragmentShader, 'vec3 astraWearAxes(vec3 n) {'),
+ noiseFn: count(s.fragmentShader, 'float astraWearNoise(vec3 p, vec3 w) {'),
+ mixLine: count(s.fragmentShader, 'float mbV ='),
+ varyVs: count(s.vertexShader, 'varying vec3 vAstraWorld;'),
+ varyFs: count(s.fragmentShader, 'varying vec3 vAstraWorldN;'),
+}));
+""")
+ assert out["micro"] and out["edge"], "one patch lost the other"
+ assert out["worldBody"] == 1 and out["axesFn"] == 1 and out["noiseFn"] == 1
+ assert out["varyVs"] == 1 and out["varyFs"] == 1
+ # Every option is a uniform, so re-applying retunes in place.
+ assert out["mixLine"] == 1 and out["amt"] == 0.12 and out["edgeAmt"] == 0.5
+ # The base runs FIRST or both bodies read a varying nobody wrote, and a
+ # longer chain must not collide with a shorter one's program.
+ assert out["key"] == "astra:wear:base+wear:micro+wear:edge", out["key"]
+ assert out["microKey"] == "astra:wear:base+wear:micro"
+
+
+def test_neither_patch_declares_a_name_its_neighbours_own():
+ """The silent failure this library is most exposed to. patchStandard
+ DROPS a repeated uniform or varying declaration and keeps the first, so
+ a name shared with terrain_shade or waterside would leave one patch
+ reading the other's value with nothing reported; a repeated local inside
+ main is a compile error instead. So: the uniform sets must be disjoint
+ (uTime excepted, which is the shared clock), and a material wearing all
+ six patches must declare every local, uniform and helper exactly once."""
+ out = _probe("""
+const wear = std();
+patchMicroBreakup(wear);
+patchEdgeWear(wear);
+const nbr = std();
+patchTriplanar(nbr);
+patchSlopeSplat(nbr, { snowLine: 30 });
+patchShoreWet(nbr);
+patchShoreFoam(nbr);
+const all = std();
+patchTriplanar(all);
+patchSlopeSplat(all, { snowLine: 30 });
+patchShoreWet(all);
+patchShoreFoam(all);
+patchMicroBreakup(all);
+patchEdgeWear(all);
+const s = compile(all);
+console.log(JSON.stringify({
+ wearU: Object.keys(wear.userData.uniforms),
+ nbrU: Object.keys(nbr.userData.uniforms),
+ vs: s.vertexShader, fs: s.fragmentShader,
+}));
+""")
+ shared = set(out["wearU"]) & set(out["nbrU"])
+ assert shared == {"uTime"}, shared
+ for stage in ("vs", "fs"):
+ src = out[stage]
+ decls = re.findall(
+ r"^\s*(?:uniform|varying)\s+(?:lowp |mediump |highp )?"
+ r"[a-z0-9]+\s+(\w+)\s*;", src, re.M)
+ dupes = [n for n, c in Counter(decls).items() if c > 1]
+ assert not dupes, f"{stage} declares {dupes} twice"
+ fns = re.findall(r"^(?:float|vec[234]|int)\s+(\w+)\s*\(",
+ _unguarded(src), re.M)
+ assert not [n for n, c in Counter(fns).items() if c > 1]
+ locals_ = re.findall(
+ r"^\s*(?:float|vec[234]|int|mat[234])\s+(\w+)\s*=",
+ _main_body(src), re.M)
+ clash = [n for n, c in Counter(locals_).items() if c > 1]
+ assert not clash, f"{stage} main() declares {clash} twice"
+ # Named as the neighbours name them on purpose: ONE world position is
+ # written for the whole chain, not one per library.
+ assert "vAstraWorld" in out["vs"] and "vAstraWorld" in out["fs"]
+
+
+def test_an_option_is_a_uniform_and_never_baked_into_the_source():
+ """three caches programs by key, and the FIRST material to compile a key
+ decides the GLSL every material sharing it gets. Two materials that
+ differ only in options must therefore compile to the same source, or the
+ second one silently wears the first one's settings. Same key,
+ byte-identical GLSL, different uniform values."""
+ out = _probe("""
+const a = std();
+patchMicroBreakup(a, { scale: 0.6, strength: 0.1, hue: 0.15, seed: 1 });
+patchEdgeWear(a, { strength: 0.35, width: 0.35, seed: 1 });
+const b = std();
+patchMicroBreakup(b, { scale: 9, strength: 0.02, hue: 0.4, seed: 99 });
+patchEdgeWear(b, {
+ strength: 0.9, width: 0.05, seed: 99, color: new THREE.Color(0x112233),
+});
+const sa = compile(a), sb = compile(b);
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ sameKey: a.customProgramCacheKey() === b.customProgramCacheKey(),
+ sameVs: sa.vertexShader === sb.vertexShader,
+ sameFs: sa.fragmentShader === sb.fragmentShader,
+ aScale: u(a).uMicroScale.value, bScale: u(b).uMicroScale.value,
+ aWidth: u(a).uEdgeWidth.value, bWidth: u(b).uEdgeWidth.value,
+ aAmt: u(a).uEdgeAmt.value, bAmt: u(b).uEdgeAmt.value,
+ aHue: u(a).uMicroHue.value, bHue: u(b).uMicroHue.value,
+ aColor: u(a).uEdgeColor.value.getHex(),
+ bColor: u(b).uEdgeColor.value.getHex(),
+}));
+""")
+ assert out["sameKey"] and out["sameVs"] and out["sameFs"]
+ assert out["aScale"] == 0.6 and out["bScale"] == 9
+ assert out["aWidth"] == 0.35 and out["bWidth"] == 0.05
+ assert out["aAmt"] == 0.35 and out["bAmt"] == 0.9
+ assert out["aHue"] == 0.15 and out["bHue"] == 0.4
+ assert out["bColor"] == 0x112233
+
+
+def test_the_bare_substrate_default_sits_inside_the_sane_albedo_range():
+ """PORT LAW 3 of the aesthetic brief: a non-emissive albedo belongs in
+ 0.02..0.8 linear. The reference's bone white 0xe8e2d6 is 0.816 linear
+ on its red channel, and on our host — ACES in the fragment tail, no post
+ chain, a bright baked environment — it read as white primer wherever the
+ wear saturated. A warmer, slightly darker bone leaves room for the
+ per-patch value break (x0.85..1.15) to stay under the top."""
+ out = _probe("""
+const m = std();
+patchEdgeWear(m);
+const c = m.userData.uniforms.uEdgeColor.value;
+console.log(JSON.stringify({ hex: c.getHex(), rgb: [c.r, c.g, c.b] }));
+""")
+ assert out["hex"] == 0xd2cabb, "a warm bone, not paper white"
+ # Linear working space, and the patch's own breaks ride on top: the
+ # value one peaks at 1.10 and the warm/cool one at 1.12.
+ assert max(out["rgb"]) * 1.10 * 1.12 <= 0.80, out["rgb"]
+ assert min(out["rgb"]) >= 0.02
+
+
+def test_one_seed_places_the_same_wear_every_time():
+ """A render is re-run — for a fix round, for a video, for the judge —
+ and the surface must not move between takes. The seed reaches the GPU
+ only as a noise-space OFFSET (a uniform, because baking it would hand
+ material one's seed to every material sharing the key), so the same seed
+ must produce the same offsets and the same roughness detune, and two
+ seeds must not land on the same blotches. The two patches also have to
+ be decorrelated from each other, or every worn edge would sit on the
+ same blob as a light patch."""
+ out = _probe("""
+const mk = (seed) => {
+ const m = std({ roughness: 0.7 });
+ patchMicroBreakup(m, { seed });
+ patchEdgeWear(m, { seed });
+ return m;
+};
+const a = mk(7), b = mk(7), c = mk(8);
+const u = (m) => m.userData.uniforms;
+console.log(JSON.stringify({
+ aMicro: u(a).uMicroSeed.value.toArray(),
+ bMicro: u(b).uMicroSeed.value.toArray(),
+ cMicro: u(c).uMicroSeed.value.toArray(),
+ aEdge: u(a).uEdgeSeed.value.toArray(),
+ cEdge: u(c).uEdgeSeed.value.toArray(),
+ aRough: a.roughness, bRough: b.roughness, cRough: c.roughness,
+ sameSrc: compile(a).fragmentShader === compile(c).fragmentShader,
+}));
+""")
+ assert out["aMicro"] == out["bMicro"] and out["aRough"] == out["bRough"]
+ assert out["aMicro"] != out["cMicro"] and out["aEdge"] != out["cEdge"]
+ assert out["aRough"] != out["cRough"], "the detune ignores the seed"
+ assert out["aMicro"] != out["aEdge"], "wear rides the breakup's blobs"
+ assert all(0 <= v <= 64 for v in out["aMicro"] + out["aEdge"])
+ # Same GLSL for both seeds: the seed is a uniform, not source.
+ assert out["sameSrc"]
+ assert "Math.random" not in _LIB_SRC
+
+
+def test_the_breakup_stays_under_the_strength_it_was_given():
+ """Subtlety is the feature: this rides on every material in the scene,
+ so an unbounded swing would be scene-wide dirt. The noise is centred,
+ stretched to reach the strength asked for, then CLAMPED before it is
+ scaled — so `strength` is a hard bound on the albedo swing however the
+ octaves stack. Each octave also fades out once a pixel spans it, which
+ is what keeps a receding surface from turning into static."""
+ out = _probe("""
+const m = std();
+patchMicroBreakup(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ mix = _find(r"float (\w+) = clamp\(\(mbLo - 0\.5\) \* [\d.]+\s*"
+ r"\+ \(mbMi - 0\.5\) \* [\d.]+ \* (\w+)\s*"
+ r"\+ \(mbHi - 0\.5\) \* [\d.]+ \* (\w+), -1\.0, 1\.0\);", fs)
+ _find(rf"diffuseColor\.rgb \*= 1\.0 \+ {mix.group(1)} \* uMicroAmt;", fs)
+ # One fade per octave, measured in cycles per pixel, not in metres.
+ fw = _find(r"float (\w+) = length\(fwidth\(mbP\)\);", fs).group(1)
+ for var, step in ((mix.group(2), "2.03"), (mix.group(3), "4.1")):
+ _find(rf"float {var} = 1\.0 - smoothstep\([\d.]+, [\d.]+,"
+ rf" {fw} \* {step}\);", fs)
+ _find(rf"float mb(?:Mi|Hi) = astraWearNoise\(mbP \* {step}, mbW\);",
+ fs)
+
+
+def test_the_breakup_varies_colour_and_not_only_brightness():
+ """PORT LAW 1. `astraHueShift` is a rotation about the grey axis and
+ therefore the identity on a neutral — 0.0 change on a grey, 0.0014 peak
+ channel move on the stone albedo 0x8d8577 at the reference's 0.03 rad —
+ and stone, plaster, concrete and dirt are most of what this patch is
+ ever asked to break up. The warm/cool transfer that replaces it moves
+ R up and B down (and G a little, as `astraHueBreak` does), riding the
+ DIFFERENCE of two octaves so the colour swing is not the brightness
+ field wearing a second label. A dust term takes saturation with it on
+ the dark half, so the patch changes MATERIAL rather than exposure."""
+ out = _probe("""
+const m = std();
+patchMicroBreakup(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ tint = _find(r"float (\w+) = clamp\(\(mbLo - mbHi\) \* [\d.]+, "
+ r"-1\.0, 1\.0\) \* uMicroHue;", fs).group(1)
+ _find(rf"diffuseColor\.rgb \*= vec3\(1\.0 \+ {tint}, "
+ rf"1\.0 \+ {tint} \* [\d.]+,\s*1\.0 - {tint}\);", fs)
+ # saturation rides the same field, bounded by strength
+ lum = _find(r"float (\w+) = dot\(diffuseColor\.rgb, "
+ r"vec3\(0\.2126, 0\.7152, 0\.0722\)\);", fs).group(1)
+ _find(rf"diffuseColor\.rgb = mix\(diffuseColor\.rgb, vec3\({lum}\),\s*"
+ r"max\(-mbV, 0\.0\) \* uMicroAmt \* [\d.]+\);", fs)
+ # GLSL_UTIL still DEFINES the rotation for whoever wants it; what this
+ # patch may not do is call it, because on a neutral it is the identity.
+ assert "astraHueShift(" not in _main_body(fs)
+
+
+def test_edge_wear_reads_signed_curvature_in_metres_not_screen_pixels():
+ """The whole edge estimate. The normal's screen derivative is divided
+ by the world length of the same pixel step, which makes it curvature in
+ 1/m: the same edge wears the same amount at any distance, where a raw
+ fwidth(normal) would draw a line that grew as the camera pulled back.
+ And the ratio is SIGNED — the ramp starts at a positive curvature, so a
+ concave corner (negative) gets nothing, which is right: dirt collects
+ there, wear does not."""
+ out = _probe("""
+const m = std();
+patchEdgeWear(m, { width: 0.35 });
+console.log(JSON.stringify({
+ fs: compile(m).fragmentShader,
+ width: m.userData.uniforms.uEdgeWidth.value,
+}));
+""")
+ fs = out["fs"]
+ curv = _find(r"float (\w+) = \(dot\(ewNx, ewPx\) \+ dot\(ewNy, ewPy\)\)\s*"
+ r"/ max\((\w+), 1e-12\);", fs)
+ _find(rf"float {curv.group(2)} = dot\(ewPx, ewPx\) \+ dot\(ewPy, ewPy\);",
+ fs)
+ _find(r"vec3 ewPx = dFdx\(vAstraWorld\);", fs)
+ _find(r"vec3 ewNx = dFdx\(ewN\);", fs)
+ # Onset at 1/width and full at three times that: a positive-only ramp,
+ # so concave curvature never leaves zero.
+ radius = _find(r"float (\w+) = 1\.0 / uEdgeWidth;", fs)
+ _find(rf"float (\w+) = smoothstep\({radius.group(1)},"
+ rf" {radius.group(1)} \* 3\.0, {curv.group(1)}\);", fs)
+ assert out["width"] == 0.35
+
+
+def test_the_break_up_is_two_octaves_scaled_to_the_width_asked_for():
+ """PORT LAW 2, the barber pole. The curvature ramp saturates at 3x the
+ onset, so on anything much thinner than `width` the break-up field is
+ the only structure the patch has left — and one fixed-frequency blotch
+ field on a 6 cm rail post is alternating solid BANDS, a painted pattern
+ rather than wear. Both octaves are tied to 1/width, so the pattern
+ scales with the feature the author declared instead of with the world;
+ and the fine one fades out once a pixel spans it, or a receding rail
+ turns into static.
+
+ The frequency may NOT be taken from the measured curvature, tempting as
+ that is: that estimate is a screen-space average of the two principal
+ curvatures, so on a cylinder it changes with the camera and the chips
+ would swim across the surface as it orbits."""
+ out = _probe("""
+const m = std();
+patchEdgeWear(m, { width: 0.35 });
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ ramp = _find(r"float (\w+) = smoothstep\(ewR, ewR \* 3\.0, ewC\);",
+ fs).group(1)
+ p = _find(r"vec3 (\w+) = vAstraWorld \* \(ewR \* [\d.]+\) \+ uEdgeSeed;",
+ fs).group(1)
+ coarse = _find(rf"float (\w+) = astraWearNoise\({p}, ewAx\);", fs).group(1)
+ fine = _find(rf"float (\w+) = astraWearNoise\({p} \* ([\d.]+) \+ [\d.]+,"
+ rf" ewAx\);", fs)
+ fade = _find(rf"float (\w+) = 1\.0 - smoothstep\([\d.]+, [\d.]+,\s*"
+ rf"length\(fwidth\({p}\)\) \* {fine.group(2)}\);", fs)
+ _find(rf"{ramp} \*= smoothstep\([\d.]+, [\d.]+, {coarse} \+ "
+ rf"\({fine.group(1)} - 0\.5\) \* {fade.group(1)}\);", fs)
+ assert "dFdx(ewC)" not in fs and "* ewC +" not in fs, \
+ "a view-dependent frequency makes the chips swim"
+
+
+def test_the_worn_tone_is_the_object_before_it_is_the_substrate():
+ """PORT LAW 2's other half. The reference mixed straight to ONE flat
+ colour, so every material in a scene wearing this patch wore the same
+ bone white in the same flat value — the exact evenness the sibling patch
+ exists to destroy. Light wear is the finish rubbed THIN: the surface's
+ own colour, lightened and desaturated, which keeps the wear belonging to
+ the thing it is on. Only where the ramp is nearly saturated does it go
+ through to the substrate, and the substrate carries its own value break
+ and its own warm/cool break so no two worn patches match."""
+ out = _probe("""
+const m = std();
+patchEdgeWear(m);
+console.log(JSON.stringify({ fs: compile(m).fragmentShader }));
+""")
+ fs = out["fs"]
+ lum = _find(r"float (\w+) = dot\(diffuseColor\.rgb, "
+ r"vec3\(0\.2126, 0\.7152, 0\.0722\)\);", fs).group(1)
+ thin = _find(rf"vec3 (\w+) = mix\(diffuseColor\.rgb, vec3\({lum}\), "
+ rf"[\d.]+\) \* [\d.]+;", fs).group(1)
+ tint = _find(r"float (\w+) = \(ewF - 0\.5\) \* [\d.]+;", fs).group(1)
+ bare = _find(r"vec3 (\w+) = uEdgeColor \* \([\d.]+ \+ [\d.]+ \* ewP\)\s*"
+ rf"\* vec3\(1\.0 \+ {tint}, 1\.0 \+ {tint} \* [\d.]+,"
+ rf" 1\.0 - {tint}\);", fs).group(1)
+ tone = _find(rf"vec3 (\w+) = mix\({thin}, {bare}, "
+ r"smoothstep\([\d.]+, [\d.]+, ewK\)\);", fs).group(1)
+ _find(rf"diffuseColor\.rgb = mix\(diffuseColor\.rgb, {tone},\s*"
+ r"clamp\(ewK \* uEdgeAmt, 0\.0, 1\.0\)\);", fs)
+
+
+def test_gloss_composes_on_the_material_because_per_pixel_is_unreachable():
+ """`fragmentBody` lands after <color_fragment> and therefore BEFORE
+ <roughnessmap_fragment> declares roughnessFactor, so neither patch can
+ touch a per-pixel gloss and both move the material's own roughness
+ instead. Two patches sharing one number is the trap: each owns ONE
+ factor over the authored value, so they compose, and re-applying either
+ replaces its factor rather than compounding it — a refine round that
+ re-runs the same build would otherwise polish the scene to a mirror.
+
+ PORT LAW 3: because the move is the whole material's it has to be
+ AREA-WEIGHTED. Worn edges are a fraction of a surface, and on a
+ renderer with no post chain and a bright environment a painted rail
+ polished by the worn patch's own value stops reading as paint at all.
+ 0.12 * strength, not 0.35."""
+ out = _probe("""
+const m = std({ roughness: 0.8 });
+patchMicroBreakup(m, { seed: 4 });
+const r1 = m.roughness;
+patchEdgeWear(m, { strength: 0.4 });
+const r2 = m.roughness;
+patchEdgeWear(m, { strength: 0.4 });
+const r3 = m.roughness;
+patchEdgeWear(m, { strength: 0 });
+const r4 = m.roughness;
+const basic = new THREE.MeshBasicMaterial({ color: 0x445566 });
+patchMicroBreakup(basic);
+patchEdgeWear(basic);
+console.log(JSON.stringify({
+ r1, r2, r3, r4, base: m.userData.astraRoughness.base,
+ basicRough: basic.roughness === undefined,
+ basicPatched: !!basic.userData.astraPatches.length,
+}));
+""")
+ assert out["base"] == 0.8, "the authored value is the one to compose on"
+ # The breakup detunes by up to +/- strength; a scene where every
+ # material shares one exact roughness shares one exact highlight.
+ assert out["r1"] != 0.8 and abs(out["r1"] - 0.8) <= 0.8 * 0.1 + 1e-9
+ assert abs(out["r2"] - out["r1"] * (1 - 0.12 * 0.4)) < 1e-9
+ assert out["r3"] == out["r2"], "re-applying compounded the gloss"
+ assert abs(out["r4"] - out["r1"]) < 1e-9
+ # A material with no roughness at all still takes the albedo patch.
+ assert out["basicRough"] and out["basicPatched"]
+
+
+def test_the_world_base_folds_in_the_instance_transform():
+ """`vertexBody` runs after <begin_vertex>, which is before
+ <project_vertex>, so `transformed` has not had instanceMatrix applied —
+ and this engine builds instanced meshes for most of what it scatters.
+ Without the guarded fold, every copy of a scattered rock would take its
+ blotches and its wear from the mesh ORIGIN and two hundred pebbles would
+ wear one identical pattern. three declares the attribute itself, so
+ declaring it again fails every instanced material."""
+ out = _probe("""
+const m = std();
+patchMicroBreakup(m);
+patchEdgeWear(m);
+console.log(JSON.stringify({ vs: compile(m).vertexShader }));
+""")
+ vs = out["vs"]
+ body = _main_body(vs)
+ assert "#ifdef USE_INSTANCING" in body
+ _find(r"wrP = instanceMatrix \* wrP;", body)
+ _find(r"wrN = mat3\(instanceMatrix\) \* wrN;", body)
+ _find(r"vAstraWorld = \(modelMatrix \* wrP\)\.xyz;", body)
+ assert "attribute mat4 instanceMatrix" not in vs
+ # fwidth and astraStroke are fragment-only: the util block ships in both
+ # stages, so they may be DEFINED here, never called.
+ assert vs.count("astraStroke(") == 1
+ assert "fwidth(" not in body
+ assert "#define ASTRA_FRAG" not in vs
diff --git a/harness/tests/scene_runtime/lib/test_terrain.py b/harness/tests/scene_runtime/lib/test_terrain.py
new file mode 100644
index 00000000..22170c7b
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_terrain.py
@@ -0,0 +1,157 @@
+"""terrain.js — the ground ships as a function; the cliff is one ribbon.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference (tests/test_terrain_lib.py);
+the composer-prompt assertions are dropped (ours is a different prompt set).
+"""
+from __future__ import annotations
+
+import re
+
+import pytest
+from _probe import LIB_DIR, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("terrain.js", "materials.js")
+
+_PROBE = """
+import * as THREE from 'three';
+import { ground, cliff } from './lib/terrain.js';
+const prng = (seed) => { let s = seed; return () => (s = (s * 16807) % 2147483647) / 2147483647; };
+
+// ground(): mesh + height agree, textured and tiled, seeded, flat() damps.
+const g1 = ground({ size: 200, rand: prng(5), relief: 6 });
+const g2 = ground({ size: 200, rand: prng(5), relief: 6 });
+const g3 = ground({ size: 200, rand: prng(6), relief: 6 });
+const pos = g1.mesh.geometry.attributes.position;
+let drift = 0, same = 0, other = 0, minY = 1e9, maxY = -1e9;
+for (let i = 0; i < pos.count; i += 7) {
+ drift = Math.max(drift, Math.abs(g1.height(pos.getX(i), pos.getZ(i)) - pos.getY(i)));
+ same = Math.max(same, Math.abs(g2.mesh.geometry.attributes.position.getY(i) - pos.getY(i)));
+ other = Math.max(other, Math.abs(g3.mesh.geometry.attributes.position.getY(i) - pos.getY(i)));
+ minY = Math.min(minY, pos.getY(i)); maxY = Math.max(maxY, pos.getY(i));
+}
+const flat = ground({ size: 200, rand: prng(5), relief: 6, flat: (x, z) => (Math.hypot(x, z) < 30 ? 1 : 0) });
+const m = g1.mesh.material;
+
+// cliff(): one connected ribbon, strata as vertex colours, faceAt on the mesh.
+const c = cliff({ length: 300, height: 40, rand: prng(11) });
+let meshes = 0; c.mesh.traverse((o) => { if (o.isMesh) meshes++; });
+const geo = c.mesh.geometry, cp = geo.attributes.position;
+const xs = [...new Set(Array.from({ length: cp.count }, (_, i) => Math.round(cp.getX(i) * 1000) / 1000))].sort((a, b) => a - b);
+let maxGap = 0;
+for (let i = 1; i < xs.length; i++) maxGap = Math.max(maxGap, xs[i] - xs[i - 1]);
+const cell = (xs[xs.length - 1] - xs[0]) / (xs.length - 1);
+const bb = new THREE.Box3().setFromObject(c.mesh);
+const colAttr = geo.attributes.color;
+const distinct = new Set();
+for (let i = 0; i < colAttr.count; i++) distinct.add([0, 1, 2].map((k) => Math.round(colAttr.array[i * 3 + k] * 50)).join(','));
+let fdrift = 0;
+for (const i of [0, Math.floor(cp.count / 3), Math.floor(cp.count / 2), cp.count - 1]) {
+ const p = c.faceAt(cp.getX(i) + 150, cp.getY(i));
+ fdrift = Math.max(fdrift, Math.abs(p.z - cp.getZ(i)), Math.abs(p.x - cp.getX(i)), Math.abs(p.y - cp.getY(i)));
+}
+const c3 = cliff({ length: 120, height: 30, rand: prng(7), strata: [0xff0000, 0x00ff00, 0x0000ff] });
+const p3 = c3.mesh.geometry.attributes.position, k3 = c3.mesh.geometry.attributes.color;
+const domAt = (ty) => {
+ let best = 0, bd = 1e9;
+ for (let i = 0; i < p3.count; i++) { const d = Math.abs(p3.getX(i)) + Math.abs(p3.getY(i) - ty); if (d < bd) { bd = d; best = i; } }
+ const r = k3.array[best * 3], g = k3.array[best * 3 + 1], b = k3.array[best * 3 + 2];
+ return r > g && r > b ? 'r' : g > b ? 'g' : 'b';
+};
+// The default material comes from the SHARED library cache: retiling it in
+// place reached back through that cache into every other asset of the look.
+import * as MAT from './lib/materials.js';
+const wall = MAT.soil();
+const wallRepeatBefore = wall.map.repeat.x;
+const small = ground({ size: 120, rand: prng(5) });
+const big = ground({ size: 480, rand: prng(5) });
+const leak = { wallRepeatBefore, wallRepeatAfter: wall.map.repeat.x,
+ wallMaterialReused: small.mesh.material === wall, wallMapReused: small.mesh.material.map === wall.map,
+ smallRepeat: small.mesh.material.map.repeat.x, bigRepeat: big.mesh.material.map.repeat.x,
+ bumpIsMap: small.mesh.material.bumpMap === small.mesh.material.map,
+ sharesGpuSource: small.mesh.material.map.source === big.mesh.material.map.source,
+ wraps: small.mesh.material.map.wrapS === THREE.RepeatWrapping };
+// A caller's OWN material is still honoured (and still retiled on a copy).
+const mine = new THREE.MeshStandardMaterial({ color: 0x808080 });
+const custom = ground({ size: 240, rand: prng(5), material: mine });
+leak.customKept = custom.mesh.material === mine;
+
+console.log(JSON.stringify({
+ leak,
+ ground: { drift, same, other, relief: maxY - minY, flatCentre: Math.abs(flat.height(0, 0)), flatEdge: Math.abs(flat.height(90, 90)),
+ textured: !!m.map && !!m.roughnessMap, repeat: m.map ? m.map.repeat.x : 0,
+ wraps: m.map ? m.map.wrapS === THREE.RepeatWrapping : false, receives: g1.mesh.receiveShadow, name: g1.mesh.name },
+ cliff: { meshes, children: c.mesh.children.length, maxGap, cell, minY: bb.min.y, maxY: bb.max.y, zSpan: bb.max.z - bb.min.z,
+ hasColor: !!colAttr, colorCount: colAttr.count, posCount: cp.count, distinct: distinct.size, drift: fdrift,
+ band0: domAt(5), band1: domAt(15), band2: domAt(25), children3: c3.mesh.children.length },
+}));
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ return measure(_PROBE, _LIBS)
+
+
+def test_ground_returns_the_height_function_it_displaced_with(probe):
+ g = probe["ground"]
+ assert g["drift"] < 1e-5, g
+ assert g["relief"] > 3, g
+ assert g["receives"] and g["name"] == "Ground"
+
+
+def test_ground_is_seeded_and_flat_damps_relief(probe):
+ g = probe["ground"]
+ assert g["same"] == 0 and g["other"] > 0.5, g
+ assert g["flatCentre"] < 1e-9 and g["flatEdge"] > 0.1, g
+
+
+def test_ground_retiles_a_copy_never_the_shared_library_material(probe):
+ """Measured 2026-09-01: `MAT.soil()` is a CACHED material whose maps are
+ shared with every other caller of that look, and `ground()` set the repeat on
+ it in place — a wall built with soil before a 480 m ground came out at
+ repeat 40x40, and two grounds of different sizes fought over one texture."""
+ k = probe["leak"]
+ assert k["wallRepeatBefore"] == 1 and k["wallRepeatAfter"] == 1, k
+ assert not k["wallMaterialReused"] and not k["wallMapReused"], k
+ assert k["smallRepeat"] == 10 and k["bigRepeat"] == 40, k
+ # bumpMap is the same object as map: one clone, or the emboss slides off.
+ assert k["bumpIsMap"] and k["wraps"], k
+ # A Texture clone shares its GPU source: the copy is state, not an upload.
+ assert k["sharesGpuSource"], k
+ # A material the caller owns is theirs — never swapped out underneath them.
+ assert k["customKept"], k
+
+
+def test_ground_textures_by_default_and_tiles_to_its_size(probe):
+ g = probe["ground"]
+ assert g["textured"] and g["wraps"]
+ assert abs(g["repeat"] - 200 / 12) < 1e-6, g
+
+
+def test_ground_source_is_seeded_never_math_random():
+ src = (LIB_DIR / "terrain.js").read_text(encoding="utf-8")
+ code = "\n".join(ln for ln in src.splitlines() if not ln.strip().startswith(("*", "//", "/*")))
+ assert not re.search(r"Math\.random\s*\(", code)
+ assert "opts.rand" in src and "MAT.soil()" in src
+
+
+def test_cliff_is_one_connected_ribbon_with_no_gaps(probe):
+ c = probe["cliff"]
+ assert c["meshes"] == 1 and c["children"] == 0
+ assert c["maxGap"] <= c["cell"] * 1.5 + 1e-6, c
+
+
+def test_cliff_strata_are_vertex_colors_on_the_face(probe):
+ c = probe["cliff"]
+ assert c["hasColor"] and c["colorCount"] == c["posCount"]
+ assert c["distinct"] >= 6 and c["children3"] == 0
+ assert (c["band0"], c["band1"], c["band2"]) == ("r", "g", "b"), c
+
+
+def test_cliff_faceat_matches_the_displaced_mesh(probe):
+ c = probe["cliff"]
+ assert c["drift"] < 1e-4, c
+ assert abs(c["minY"]) < 1e-6 and abs(c["maxY"] - 40) < 1e-6
+ assert c["zSpan"] > 2, c
diff --git a/harness/tests/scene_runtime/lib/test_terrain_shade.py b/harness/tests/scene_runtime/lib/test_terrain_shade.py
new file mode 100644
index 00000000..43c2a5b5
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_terrain_shade.py
@@ -0,0 +1,571 @@
+"""terrain_shade.js — the surface chooses the shading, not a UV.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_terrain_shade_lib.py). Their renderer-contract assertions are
+dropped; the scenarios are kept, and the value assertions follow this
+port's regrade (see below), which was measured on our host rather than
+argued in code:
+
+* the patched rock rendered COLDER than the unpatched dirt beside it
+ (R-B = -32 against +21) at saturation 0.06-0.09 with a hue spread of
+ 0.02 across a whole region — a grey putty card. One `astraHueBreak`
+ is a TINT: its field is metres wide, so anything boulder-sized lands
+ inside a single lobe. `astraTerrainGrain` stacks two decorrelated
+ scales and pulls the mean warm; patched rock now reads R-B = +6 where
+ the unpatched soil beside it in the same shadow reads -6.
+* the snow cap was one flat value (hue spread 0.003, luminance sigma
+ 0.018 over an entire peak) at an albedo of 0.93-0.97, above the 0.8 an
+ unlit dielectric may hold. The drift field now moves the COVERAGE, so
+ scoured rock shows through.
+* the +/-5 m snow transition was hardcoded, which hazes anything smaller
+ than a mountain from base to tip; it is `snowBand` now, and the
+ off-sentinel floors it so the smoothstep edges can still resolve in
+ float32.
+"""
+from __future__ import annotations
+
+import json
+import re
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "terrain_shade.js")
+_LIB = LIB_DIR / "terrain_shade.js"
+
+
+# The two hooks patchStandard injects into, as a material three would.
+_FAKE_SHADER = """
+const fake = () => ({
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+});
+"""
+
+
+def _measure(script: str) -> dict:
+ return measure(_FAKE_SHADER + script, _LIBS)
+
+
+def test_triplanar_projects_on_three_world_planes_and_reads_no_uv():
+ """The whole point of the patch: a face at any angle takes the
+ projection it faces most, so nothing stretches and no UV is needed.
+ Weights that are not renormalised would darken or blow out every
+ 45-degree face."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchTriplanar } from './lib/terrain_shade.js';
+const sh = fake();
+patchTriplanar(new THREE.MeshStandardMaterial()).onBeforeCompile(sh);
+console.log(JSON.stringify({ vs: sh.vertexShader, fs: sh.fragmentShader }));
+""")
+ fs, vs = out["fs"], out["vs"]
+ for plane in ("tpP.yz", "tpP.zx", "tpP.xy"):
+ assert plane in fs, plane
+ assert "w.x + w.y + w.z" in fs, "the three weights must sum to one"
+ assert "abs(n)" in fs and "uTriSharp" in fs
+ # No UV anywhere: the geometry this shades has none worth using.
+ assert not re.search(r"\buv\b|\bvUv\b", fs), fs
+ assert not re.search(r"\buv\b|\bvUv\b", vs), vs
+ # The surface itself is the input, and it arrives in WORLD space.
+ assert "modelMatrix" in vs and "vAstraWorld =" in vs
+ assert "vAstraWorldN = normalize" in vs
+ # A varying declared in one stage only is a link failure, and the
+ # symptom is the patch simply not drawing.
+ for decl in ("varying vec3 vAstraWorld;", "varying vec3 vAstraWorldN;"):
+ assert decl in vs and decl in fs, decl
+
+
+def test_triplanar_tunables_are_uniforms_with_the_documented_defaults():
+ """Metres per repeat and the blend exponent are what an author
+ retunes after seeing a frame; as uniforms they need no recompile —
+ and, being uniforms rather than baked literals, two materials that
+ share a program still keep their own values."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchTriplanar } from './lib/terrain_shade.js';
+const u = (m) => {
+ const o = {};
+ for (const k of Object.keys(m.userData.uniforms)) {
+ const v = m.userData.uniforms[k].value;
+ o[k] = (v && v.isColor) ? v.getHex() : v;
+ }
+ return o;
+};
+const d = patchTriplanar(new THREE.MeshStandardMaterial());
+const t = patchTriplanar(new THREE.MeshStandardMaterial(), {
+ scale: 7.5, sharpness: 12, noiseOctaves: 9,
+ colorA: new THREE.Color(0x112233), colorB: 0x445566,
+});
+console.log(JSON.stringify({ d: u(d), t: u(t) }));
+""")
+ assert out["d"]["uTriScale"] == 2 and out["d"]["uTriSharp"] == 4
+ assert out["d"]["uTriOct"] == 4
+ assert out["t"]["uTriScale"] == 7.5 and out["t"]["uTriSharp"] == 12
+ # astraFbm2 loops over at most six octaves; asking for more would
+ # silently do nothing, so it is clamped where it can be seen.
+ assert out["t"]["uTriOct"] == 6
+ assert out["t"]["uTriA"] == 0x112233 and out["t"]["uTriB"] == 0x445566
+
+
+def test_the_triplanar_default_pair_is_hue_separated_not_two_greys():
+ """The noise mixes A into B, so if the pair shares a hue the mix is
+ a VALUE ramp and the grain has no colour to travel through — which
+ is how a whole cliff came out one flat tone. The shipped pair now
+ spans a shaded grey-pink to a buff ochre."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchTriplanar } from './lib/terrain_shade.js';
+const m = patchTriplanar(new THREE.MeshStandardMaterial());
+const hsl = (c) => { const o = {}; c.getHSL(o); return o; };
+console.log(JSON.stringify({
+ a: hsl(m.userData.uniforms.uTriA.value),
+ b: hsl(m.userData.uniforms.uTriB.value),
+}));
+""")
+ spread = abs(out["b"]["h"] - out["a"]["h"]) * 360.0
+ assert spread > 20.0, (out["a"], out["b"])
+ # Albedo, not light: an unlit dielectric holds 0.02..0.8.
+ for end in ("a", "b"):
+ assert 0.02 < out[end]["l"] < 0.8, out[end]
+
+
+def test_slope_splat_bands_run_flats_to_scree_to_bare_rock():
+ """Grass on the flats, scree between, bare rock on the steepest —
+ and the two thresholds are ordered so the bands cannot cross. GLSL
+ smoothstep with edge0 > edge1 is undefined, so an author who swaps
+ slopeLow and slopeHigh would get an undefined snow mask, not a
+ warning."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchSlopeSplat } from './lib/terrain_shade.js';
+const sh = fake();
+const m = patchSlopeSplat(new THREE.MeshStandardMaterial());
+m.onBeforeCompile(sh);
+const swapped = patchSlopeSplat(new THREE.MeshStandardMaterial(),
+ { slopeLow: 0.3, slopeHigh: 0.9 });
+const val = (x, k) => x.userData.uniforms[k].value;
+const hsl = (c) => { const o = {}; c.getHSL(o); return o; };
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ low: val(m, 'uSplatLow'), high: val(m, 'uSplatHigh'),
+ blend: val(m, 'uSplatBlend'),
+ swappedLow: val(swapped, 'uSplatLow'),
+ swappedHigh: val(swapped, 'uSplatHigh'),
+ grass: hsl(val(m, 'uSplatGrass')),
+ scree: hsl(val(m, 'uSplatScree')),
+ rock: hsl(val(m, 'uSplatRock')),
+ snow: hsl(val(m, 'uSplatSnow')),
+}));
+""")
+ assert out["low"] == 0.75 and out["high"] == 0.45
+ assert out["blend"] == 0.08
+ assert out["swappedLow"] == 0.9 and out["swappedHigh"] == 0.3
+ fs = out["fs"]
+ # Grass is what the FLATTEST slope resolves to and rock what the
+ # steepest does: the rock weight is the complement of the same ramp.
+ assert "smoothstep(uSplatLow - spB, uSplatLow + spB, spUp)" in fs
+ assert "1.0 - smoothstep(uSplatHigh - spB, uSplatHigh + spB, spUp)" in fs
+ assert "mix(mix(uSplatScree, uSplatRock, spR), uSplatGrass, spG)" in fs
+ # Slope is read from the surface normal, not from height.
+ assert "spN.y" in fs and "normalize(vAstraWorldN)" in fs
+ # The four zones must read as MATERIALS, not one grey at four
+ # brightnesses: bare rock is the darkest AND the most saturated,
+ # scree is pale and dusty, and every one of them is an albedo.
+ rock, scree, snow = out["rock"], out["scree"], out["snow"]
+ assert rock["l"] < scree["l"], "bare rock is the darker of the two"
+ assert rock["s"] > scree["s"], "and the more saturated"
+ assert snow["s"] < 0.10, "snow is neutral; the LIGHT makes it blue"
+ for zone in (out["grass"], scree, rock, snow):
+ assert 0.02 < zone["l"] <= 0.80, zone
+
+
+def test_slope_splat_boundaries_wander_instead_of_ruling_a_line():
+ """A threshold on normal.y alone draws a contour line no hillside
+ has — the band edge reads as a decal laid over the terrain. The
+ boundary is displaced by world-space noise, which is also what puts
+ the snow line on the rock rather than on a plane. ONE wander is not
+ enough: at 12 m it still draws a smooth rim across anything
+ boulder-sized (the grass cap on a 1 m rock measured saturation 0.39
+ against 0.06 for the rock under it), so a hand-scale term breaks
+ that rim into speckle."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchSlopeSplat } from './lib/terrain_shade.js';
+const sh = fake();
+patchSlopeSplat(new THREE.MeshStandardMaterial()).onBeforeCompile(sh);
+console.log(JSON.stringify({ fs: sh.fragmentShader }));
+""")
+ fs = out["fs"]
+ assert "astraFbmUnit(vAstraWorld.xz * 0.08, 3)" in fs
+ assert "spN.y + spJit + spFine" in fs, "the slope threshold must wander"
+ assert "spFine" in fs and "vAstraWorld.xz * 1.6" in fs, "at TWO scales"
+ assert "vAstraWorld.y + spJit * uSplatSnowBand" in fs, "so must the snow"
+ # The library noise is the shipped one, so a mesh displaced on the
+ # CPU and this shader agree on what the same noise means.
+ assert "float astraFbm2(" in fs and "float astraHash21(" in fs
+
+
+def test_snow_is_off_by_default_and_never_settles_on_a_cliff():
+ """`snowLine: Infinity` means no snow, but Infinity cannot reach a
+ float uniform: smoothstep(inf, inf, y) is 0/0, and a NaN colour
+ renders black over the whole terrain. It becomes a finite sentinel
+ far above any scene whose transition band still resolves in float32
+ — and now that the band is an OPTION, a small one against that
+ sentinel would put the two edges on the same float and bring the
+ NaN straight back, so the off case floors it at a metre.
+ Above the line, snow is gated by the SAME slope knobs — the steepest
+ faces stay bare rock, which is what makes a peak read as a peak."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchSlopeSplat } from './lib/terrain_shade.js';
+const sh = fake();
+const off = patchSlopeSplat(new THREE.MeshStandardMaterial());
+off.onBeforeCompile(sh);
+const on = patchSlopeSplat(new THREE.MeshStandardMaterial(),
+ { snowLine: 180, snow: 0xffffff });
+const tight = patchSlopeSplat(new THREE.MeshStandardMaterial(),
+ { snowLine: 9, snowBand: 1.8 });
+const offTight = patchSlopeSplat(new THREE.MeshStandardMaterial(),
+ { snowBand: 0.05 });
+const u = (m, k) => m.userData.uniforms[k].value;
+const y = (m) => u(m, 'uSplatSnowY'), b = (m) => u(m, 'uSplatSnowBand');
+const resolves = (m) =>
+ Math.fround(y(m) + b(m)) !== Math.fround(y(m) - b(m));
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ off: y(off), on: y(on), band: b(off),
+ tightY: y(tight), tightBand: b(tight),
+ offTightBand: b(offTight),
+ bandResolves: resolves(off) && resolves(offTight) && resolves(tight),
+}));
+""")
+ assert out["on"] == 180
+ assert 1e5 <= out["off"] < 1e9, "a sentinel, not Infinity"
+ assert out["band"] == 5, "the documented default half-width, in metres"
+ assert out["tightY"] == 9 and out["tightBand"] == 1.8
+ assert out["offTightBand"] >= 1.0, "a 0.05 m band cannot resolve at 1e6"
+ assert out["bandResolves"], "the band must survive float32 everywhere"
+ fs = out["fs"]
+ assert "smoothstep(uSplatHigh, uSplatLow, spUp)" in fs, "snow needs a hold"
+ # The DRIFT moves the coverage, not just the tint: a smooth ramp
+ # painted the whole cap one value.
+ assert "spSnow * spHold * mix(0.45, 1.45, spDrift)" in fs
+ assert "mix(spC, spSnowC, spCov)" in fs
+
+
+def test_the_grain_stacks_two_scales_and_leans_warm():
+ """One `astraHueBreak` is a tint: its 2-octave field is metres wide,
+ so a boulder lands whole inside one lobe and comes out uniformly
+ cold (measured R-B = -32 beside dirt at +21). Two decorrelated
+ scales — patch-sized over hand-sized — plus an ochre term whose warm
+ excursion is larger than its cool one is what makes a rock face run
+ pink, grey and near-black across a metre. Shared by both patches
+ under an include guard: a material wearing BOTH would otherwise
+ redefine the function and die."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+const one = fake(), both = fake();
+patchTriplanar(new THREE.MeshStandardMaterial()).onBeforeCompile(one);
+const m = new THREE.MeshStandardMaterial();
+patchTriplanar(m); patchSlopeSplat(m);
+m.onBeforeCompile(both);
+console.log(JSON.stringify({ fs: one.fragmentShader,
+ bothFs: both.fragmentShader }));
+""")
+ fs = out["fs"]
+ assert "vec3 astraTerrainGrain(vec3 c, vec3 wp, float swing)" in fs
+ calls = re.findall(r"astraHueBreak\(\w+, wp\.\w\w[^;]*?, ([\d.]+),", fs)
+ assert len(calls) == 2, calls
+ coarse, fine = (float(c) for c in calls)
+ assert fine > coarse * 3, ("the two scales must be far apart", calls)
+ # The warm end of the ochre mix moves further than the cool end, so
+ # the MEAN of the field is warm — rock in daylight is never cooler
+ # than the ground beside it.
+ warm = re.search(
+ r"mix\(vec3\(([\d.]+), [\d.]+, ([\d.]+)\),"
+ r" vec3\(([\d.]+), [\d.]+, ([\d.]+)\), w\)", fs)
+ assert warm, fs
+ cool_r, cool_b, hot_r, hot_b = (float(g) for g in warm.groups())
+ assert hot_r - 1.0 > 1.0 - cool_r, "the warm excursion must be larger"
+ assert hot_r > hot_b and cool_r < cool_b, "one axis, red against blue"
+ # Both patches ship the block, and a material wearing BOTH must end
+ # up with ONE body — a second definition is "already has a body" and
+ # a dead material. patchStandard's duplicate-helper detector drops
+ # the repeat here; the `#ifndef` guard is the second line of defence
+ # for the day a sibling library ships its own copy of the block.
+ assert out["bothFs"].count("vec3 astraTerrainGrain(") == 1
+ assert "#ifndef ASTRA_TERRAIN_GRAIN" in fs
+ assert "#define ASTRA_TERRAIN_GRAIN" in fs
+
+
+def test_the_two_patches_never_share_one_compiled_program():
+ """three caches programs by material type and parameters, so two
+ differently patched MeshStandardMaterials would compile to ONE
+ program and the second patch would silently never run. Two materials
+ wearing the SAME patch are the safe case, and only because every
+ tunable is a uniform: their GLSL is byte-identical while their
+ values stay their own."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+const tri = patchTriplanar(new THREE.MeshStandardMaterial());
+const splat = patchSlopeSplat(new THREE.MeshStandardMaterial());
+const a = patchTriplanar(new THREE.MeshStandardMaterial(), { scale: 3 });
+const b = patchTriplanar(new THREE.MeshStandardMaterial(), { scale: 40 });
+const shA = fake(), shB = fake();
+a.onBeforeCompile(shA);
+b.onBeforeCompile(shB);
+console.log(JSON.stringify({
+ triKey: tri.customProgramCacheKey(),
+ splatKey: splat.customProgramCacheKey(),
+ namedKey: patchTriplanar(new THREE.MeshStandardMaterial(),
+ { name: 'scree' }).customProgramCacheKey(),
+ sameGlsl: shA.fragmentShader === shB.fragmentShader,
+ scaleA: shA.uniforms.uTriScale.value,
+ scaleB: shB.uniforms.uTriScale.value,
+ marked: !!tri.userData.astraShader,
+}));
+""")
+ assert out["triKey"] != out["splatKey"], "each patch kind needs its own"
+ assert out["namedKey"] not in (out["triKey"], out["splatKey"])
+ assert out["sameGlsl"], "one patch kind must compile to one source"
+ assert out["scaleA"] == 3 and out["scaleB"] == 40
+ assert out["marked"], "tickShaders finds patches by this flag"
+
+
+def test_both_patches_inject_at_the_hooks_patchstandard_documents():
+ """`transformed` only exists after <begin_vertex> and `diffuseColor`
+ only after <color_fragment>; injected anywhere else the patch is a
+ compile error on a line number in three's assembled source. The
+ instance transform is folded in at the vertex hook because
+ `transformed` is still object-space there — without it every
+ scattered rock projects from the world origin."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+const res = {};
+for (const [k, patch] of [['tri', patchTriplanar],
+ ['splat', patchSlopeSplat]]) {
+ const sh = fake();
+ patch(new THREE.MeshStandardMaterial()).onBeforeCompile(sh);
+ const vs = sh.vertexShader, fs = sh.fragmentShader;
+ res[k] = {
+ vertexAfterHook: vs.indexOf('#include <begin_vertex>') <
+ vs.indexOf('vAstraWorld ='),
+ fragAfterHook: fs.indexOf('#include <color_fragment>') <
+ fs.indexOf('diffuseColor.rgb ='),
+ instancing: vs.includes('#ifdef USE_INSTANCING') &&
+ vs.includes('instanceMatrix * astraWp'),
+ fragOnly: !vs.includes('astraFbmUnit(') && fs.includes('astraFbmUnit('),
+ fragDefine: fs.includes('#define ASTRA_FRAG'),
+ vertexDefine: vs.includes('#define ASTRA_FRAG'),
+ gotUniforms: !!sh.uniforms.uTime,
+ };
+}
+console.log(JSON.stringify(res));
+""")
+ for kind in ("tri", "splat"):
+ got = out[kind]
+ assert got["vertexAfterHook"], kind
+ assert got["fragAfterHook"], kind
+ assert got["instancing"], kind
+ assert got["fragOnly"], kind
+ # The util block ships in BOTH stages and its fwidth helper is
+ # fragment-only, so ASTRA_FRAG must stay undefined in the vertex
+ # stage or every program in the engine fails to compile.
+ assert got["fragDefine"] and not got["vertexDefine"], kind
+ assert got["gotUniforms"], kind
+
+
+def test_the_shipped_module_is_deterministic():
+ """Terrain has to come back identical on a re-render, so the whole
+ library is seeded noise and constants — the same rule terrain.js
+ holds to on the CPU side."""
+ src = _LIB.read_text(encoding="utf-8")
+ assert "Math.random" not in src
+ assert "Date.now" not in src
+ # Its GLSL ships into the VERTEX stage too, so it may not call a
+ # fragment-only builtin: fwidth there fails every program at once.
+ assert "fwidth" not in src
+ assert "export function patchTriplanar" in src
+ assert "export function patchSlopeSplat" in src
+
+
+_SCENE = """
+import * as THREE from 'three';
+import { ground, cliff } from './lib/terrain.js';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+
+export const BOUNDS = { min: [-100, 0, -100], max: [100, 60, 100] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ // FOGGED and lit: the patches ride the built-in's own fog and light
+ // chunks, and asset mode never defines USE_FOG, so an unfogged probe
+ // would never compile the branch these ship into.
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ scene.add(new THREE.HemisphereLight(0xbdd4ee, 0x5b4a3a, 1.1));
+ const sun = new THREE.DirectionalLight(0xffe8cc, 2.4);
+ sun.position.set(-30, 24, -20);
+ scene.add(sun);
+ const g = new THREE.Group();
+ let s = 7;
+ const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+
+ const land = ground({ size: 200, segments: 48, rand, relief: 24 });
+ patchSlopeSplat(land.mesh.material, {
+ grass: new THREE.Color(0x4f6b3a), scree: 0x8d8272,
+ rock: new THREE.Color(0x6b6258), snow: 0xeef2f6,
+ snowLine: 9, snowBand: 2.5, slopeLow: 0.8, slopeHigh: 0.5, blend: 0.1,
+ });
+ g.add(land.mesh);
+
+ const wall = cliff({ length: 80, height: 30, rand });
+ patchTriplanar(wall.mesh.material, {
+ scale: 3.5, sharpness: 6, noiseOctaves: 5,
+ colorA: new THREE.Color(0x6a5f52), colorB: 0xa2977f,
+ });
+ wall.mesh.position.set(0, land.height(0, -60), -60);
+ g.add(wall.mesh);
+
+ // Instanced, and on the DEFAULT snow line: the sentinel and the
+ // USE_INSTANCING branch have to compile too.
+ const rocks = new THREE.InstancedMesh(new THREE.IcosahedronGeometry(1.6, 1),
+ new THREE.MeshStandardMaterial({ color: 0x8a7f70 }), 12);
+ const m4 = new THREE.Matrix4();
+ for (let i = 0; i < 12; i++) {
+ const x = (rand() - 0.5) * 120, z = (rand() - 0.5) * 120;
+ m4.makeTranslation(x, land.height(x, z), z);
+ rocks.setMatrixAt(i, m4);
+ }
+ patchSlopeSplat(rocks.material, { name: 'terrain:slopeSplat:rocks' });
+ g.add(rocks);
+ scene.add(g);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [40, 20, 60], lookAt: [0, 6, 0],
+ fov: 45 }],
+ update() {},
+ };
+}
+"""
+
+
+def test_both_patches_compile_on_the_real_renderer():
+ """The only witness that counts. Everything above reads a string;
+ whether the GPU accepts the GLSL — the instancing branch, the int
+ octave uniform, three planar fbm reads inside one fragment, and a
+ fourth call site for astraTerrainGrain — cannot be asserted from
+ source, and a patch that does not compile is worth nothing."""
+ code, out = compile_scene(
+ _SCENE, ("shader.js", "materials.js", "terrain.js",
+ "terrain_shade.js"))
+ assert code == 0, out
+ # A green exit on an empty compile proves nothing: the ground, the
+ # cliff and the instanced boulders all had to reach the GPU. A floor,
+ # because materials.js patches its own, and an exact count here went
+ # stale the moment a sibling library did.
+ report = json.loads(out[out.index("{"):out.rindex("}") + 1])
+ assert report["compile"]["custom_materials"] >= 3, out
+
+
+def test_both_patches_on_one_material_still_compile():
+ """The prompt tells authors to use both on the same ground, and both
+ shipped the same locals and the same helper body: 'astraWp'
+ redefinition, 'astraFbmUnit' already has a body, dead material.
+ Caught on the GPU by a sibling library that landed on the same bank.
+ """
+ code, out = compile_scene("""
+import * as THREE from 'three';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 4, 20] };
+export function heightAt() { return 0; }
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.004);
+ scene.add(new THREE.HemisphereLight(0xbdd4ee, 0x5b4a3a, 1.2));
+ const m = new THREE.MeshStandardMaterial({ color: 0x8a8578 });
+ patchTriplanar(m, { scale: 3 });
+ patchSlopeSplat(m, { snowLine: 12 });
+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(40, 40, 8, 8), m);
+ mesh.rotation.x = -Math.PI / 2;
+ scene.add(mesh);
+ return { scene,
+ cameras: [{ name: 'a', position: [8, 5, 12], lookAt: [0, 0, 0],
+ fov: 45 }],
+ update() {} };
+}
+""", ("shader.js", "terrain_shade.js"))
+ assert code == 0, out
+ assert "redefinition" not in out and "already has a body" not in out
+
+
+def test_the_splat_keeps_the_triplanar_it_lands_on():
+ """Both patches used to assign `diffuseColor.rgb` outright, so on
+ the terrain the prompts recommend — triplanar for the rock, splat
+ for grass-to-scree-to-snow — whichever ran second erased the other
+ completely. The two are a colour and a variation, not two colours:
+ applied over a triplanar the splat carries its grain through, and
+ (this port) its mass-scale value and up-face wash as well, or the
+ splat flattens the cliff structure the triplanar just built."""
+ out = measure("""
+import * as THREE from 'three';
+import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';
+const compile = (build) => {
+ const m = new THREE.MeshStandardMaterial();
+ build(m);
+ const s = { uniforms: {},
+ vertexShader: 'void main() { #include <begin_vertex> }',
+ fragmentShader: '#include <color_fragment>' };
+ m.onBeforeCompile(s);
+ return s.fragmentShader;
+};
+const both = compile((m) => { patchTriplanar(m, {}); patchSlopeSplat(m, {}); });
+const triOnly = compile((m) => patchTriplanar(m, {}));
+const splatOnly = compile((m) => patchSlopeSplat(m, {}));
+// The composed body must READ the triplanar's own noise, not just
+// declare it and throw it away.
+const lastWrite = both.slice(both.lastIndexOf('diffuseColor.rgb ='));
+console.log(JSON.stringify({
+ composedUsesTriNoise: /tpN/.test(lastWrite.split(';')[0]),
+ composedUsesTriValue: /tpV/.test(lastWrite.split(';')[0]),
+ triAloneStillAssigns: /diffuseColor\\.rgb = tpC;/.test(triOnly),
+ splatAloneUnchanged:
+ /diffuseColor\\.rgb = spC \\* mix\\(0\\.86, 1\\.14, spVar\\);/
+ .test(splatOnly),
+ // The detection must survive the documented `name` option: it
+ // used to key off the name, so one custom name undid the fix.
+ survivesACustomName: (() => {
+ const m = new THREE.MeshStandardMaterial();
+ patchTriplanar(m, { name: 'myRock' });
+ patchSlopeSplat(m, {});
+ const s = { uniforms: {},
+ vertexShader: 'void main() { #include <begin_vertex> }',
+ fragmentShader: '#include <color_fragment>' };
+ m.onBeforeCompile(s);
+ const last = s.fragmentShader.slice(
+ s.fragmentShader.lastIndexOf('diffuseColor.rgb ='));
+ return /tpN/.test(last.split(';')[0]);
+ })(),
+ // Different structure means a different program: sharing the cache
+ // key would serve one compiled shader to both shapes.
+ distinctKey: (() => {
+ const a = new THREE.MeshStandardMaterial();
+ patchTriplanar(a, {}); patchSlopeSplat(a, {});
+ const b = new THREE.MeshStandardMaterial();
+ patchSlopeSplat(b, {});
+ return a.customProgramCacheKey() !== b.customProgramCacheKey();
+ })(),
+}));
+""", _LIBS)
+ assert out["composedUsesTriNoise"], (
+ "the splat threw the triplanar away again")
+ assert out["composedUsesTriValue"], (
+ "the splat flattened the triplanar's mass value and up-face wash")
+ assert out["triAloneStillAssigns"] and out["splatAloneUnchanged"]
+ assert out["survivesACustomName"], (
+ "a custom name must not undo the composition")
+ assert out["distinctKey"]
diff --git a/harness/tests/scene_runtime/lib/test_urban.py b/harness/tests/scene_runtime/lib/test_urban.py
new file mode 100644
index 00000000..baa9df44
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_urban.py
@@ -0,0 +1,487 @@
+"""urban.js: the glazed facade, the cables over the street, the hoarding.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_urban_lib.py). Its six laws are kept — the catenary, the
+grazing-angle fresnel, no second render target, no transparent card left
+in the occlusion pass, a compile in an asset AND in a fogged scene, and
+one seed rebuilding the same street — because none of them depend on
+their renderer. Their asset/scene split is rebuilt on OUR wrapper
+(`_probe.compile_scene`).
+
+THE PORT'S OWN LAWS, each measured on this host. Frames:
+fx/out/urban/{before,after,before_night,after_night}, one fixture
+(fx/fixtures/urban.js: two glazed towers, a four-span line of poles, a
+lit hoarding and a lit light box, both spilling onto the ground).
+
+1. A POSTER IS PRINTED INK, NOT A LIGHT SOURCE. The sheet peaked at
+ L 0.92 and clipped under its own gooseneck lamps: blown_frac over the
+ poster's pixels was 0.120 by day and 0.276 at night. Every texel now
+ sits in 0.155..0.80 sRGB (0.02..0.60 linear), held on LUMINANCE so a
+ dark ink stays a dark ink instead of turning pink-grey. Measured:
+ blown 0.120 -> 0.000 (day), 0.276 -> 0.000 (night).
+
+2. THE GRAIN WAS A BEAT, NOT A HASH. `sin(u * 91.7 + v * 47.3) *
+ 43758.5 % 1` is a 1-D function of a linear combination of u and v,
+ and a 128 px sheet magnified over a 5.4 m board printed it as
+ DIAGONAL STRIPES (crop fx/u_poster_before.png). It is fBm now, and
+ the law that pins it is band-limiting: neighbouring texels must
+ differ by far less than the sheet's own spread. Measured ratio
+ 1.153 (old, white noise) -> 0.032.
+
+3. A HALO IS LIGHT IN THE AIR, NOT A VEIL OVER THE ARTWORK. The glow
+ card peaked at the CENTRE, i.e. over the opaque board, and with no
+ bloom pass to justify it that additive sheet just clipped the top
+ band of the poster in daylight and at night both. It is hollowed
+ out over the board's own outline now, and its gain falls off as
+ (1 - ambient) ** 1.7 so one card reads at night and vanishes by noon.
+
+4. A RUN OF POLES IS NOT ONE FLAT BROWN. Weathering rides in a vertex
+ colour that only ever darkens, so `color` stays the true albedo.
+ Measured over the 2 572 pole pixels of the mid view: lum_std 0.0517
+ -> 0.0688, saturation 0.0702 -> 0.0870, mean luminance 0.307 ->
+ 0.268 (creosote at the foot, bleach at the top).
+
+5. A COATING REFLECTS A TINTED IMAGE. The reflected sky was untinted,
+ so under a hazy sky every tower returned the haze and read as one
+ grey sheet whatever `tint` said. `coat` (default 0.45) puts the
+ glass hue into the reflection and a per-panel batch varies it.
+ Measured saturation over the facade: 0.205 -> 0.318 (blue tower),
+ 0.111 -> 0.173 (green round tower), and the HUE SEPARATION between
+ the two towers in one frame 0.0257 -> 0.0897 — before this they were
+ the same pale grey-blue whatever glass they were given.
+"""
+
+from __future__ import annotations
+
+import math
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure
+
+_LIBS = ("shader.js", "noise.js", "materials.js", "neon.js", "urban.js")
+
+
+# The poster texture, read straight off the built material.
+_POSTER = """
+import { makeBillboard } from './lib/urban.js';
+const g = makeBillboard(%s);
+let tex = null;
+g.traverse((o) => { if (o.name === 'Face') tex = o.material.map; });
+const d = tex.image.data;
+const rgb = [];
+for (let i = 0; i < d.length; i += 4) rgb.push(d[i], d[i + 1], d[i + 2]);
+console.log(JSON.stringify({ size: tex.image.width, rgb }));
+"""
+
+
+def test_a_cable_hangs_as_a_catenary_and_not_as_a_parabola():
+ """A hanging cable is cosh, not x squared. The two agree to a
+ fraction of a percent at the shallow sags a tidy street has, so the
+ only honest test is a DEEP sag, where the catenary is visibly
+ fuller at the ends. Both models are fitted from the measured span
+ and dip by the same rule, not assumed."""
+ out = measure("""
+import * as THREE from 'three';
+import { makePowerLines } from './lib/urban.js';
+// A deep sag: the shallow case cannot tell the two curves apart.
+const g = makePowerLines({ points: [[-15, 8, 0], [15, 8, 0]], spans: 1,
+ sag: 9, seed: 4 });
+const pts = [];
+g.traverse((o) => {
+ if (!o.isMesh) return;
+ const p = o.geometry.getAttribute('position');
+ if (!p) return;
+ for (let i = 0; i < p.count; i++) {
+ pts.push([p.getX(i), p.getY(i), p.getZ(i)]);
+ }
+});
+console.log(JSON.stringify({ pts }));
+""", _LIBS)
+ prof: dict[float, float] = {}
+ for x, y, _z in out["pts"]:
+ k = round(x, 2)
+ prof[k] = min(prof.get(k, 1e9), y)
+ ks = sorted(k for k in prof if -14.5 <= k <= 14.5)
+ assert len(ks) >= 15, "too few samples to tell the two curves apart"
+ ends = max(prof[ks[0]], prof[ks[-1]])
+ dip = ends - min(prof[k] for k in ks)
+ assert dip > 1.0, f"the cable barely sags ({dip:.2f} m)"
+ half = (ks[-1] - ks[0]) / 2
+ mid = (ks[-1] + ks[0]) / 2
+
+ # Solve the catenary's own parameter from this span and dip, the
+ # same bisection the library documents.
+ lo, hi = 1e-6, 1.0
+ while half / hi * (math.cosh(hi) - 1) < dip and hi < 1e4:
+ hi *= 2
+ for _ in range(80):
+ m = 0.5 * (lo + hi)
+ if half / m * (math.cosh(m) - 1) < dip:
+ lo = m
+ else:
+ hi = m
+ u = 0.5 * (lo + hi)
+
+ def rms(model) -> float:
+ s = sum((prof[k] - (ends - dip * model((k - mid) / half))) ** 2
+ for k in ks)
+ return (s / len(ks)) ** 0.5
+
+ cat = rms(lambda v: (math.cosh(u) - math.cosh(u * v))
+ / (math.cosh(u) - 1))
+ par = rms(lambda v: 1 - v * v)
+ assert cat < par * 0.5, (
+ f"the profile fits a parabola at least as well as a catenary "
+ f"(catenary rms {cat:.4f}, parabola rms {par:.4f}) — a parabola "
+ "is the small-sag limit and gets the end curvature wrong")
+
+
+def test_the_facade_reflects_more_at_a_grazing_angle():
+ """Fresnel is what makes a tower a tower: it shows its rooms head-on
+ and the sky along its flank. A constant reflectivity is one mirror
+ sheet, which is the failure this patch exists to avoid."""
+ out = measure(r"""
+import * as THREE from 'three';
+import { patchCurtainWall } from './lib/urban.js';
+const m = new THREE.MeshStandardMaterial();
+patchCurtainWall(m, {});
+const s = { uniforms: {},
+ vertexShader: 'void main() { #include <begin_vertex> }',
+ fragmentShader: '#include <color_fragment>' };
+m.onBeforeCompile(s);
+const fs = s.fragmentShader;
+console.log(JSON.stringify({
+ // The reflected term has to ride a view-dependent quantity.
+ hasFresnel: /astraFresnel|Fresnel\(|1\.0\s*-\s*(abs\()?dot\(/.test(fs),
+ usesViewVector: /cameraPosition/.test(fs),
+ // Per-panel variation: without it the whole wall shares one ray.
+ perPanel: /cwPn|panel|uCwPanel/i.test(fs),
+ liftsLight: /totalEmissiveRadiance\s*\+=/.test(fs),
+}));
+""", _LIBS)
+ assert out["hasFresnel"] and out["usesViewVector"], (
+ "reflectivity must depend on the view angle")
+ assert out["perPanel"], "panels must differ or the wall is one mirror"
+ assert out["liftsLight"], (
+ "reflected radiance is light; albedo cannot carry it")
+
+
+def test_the_facade_spends_no_second_render_target():
+ """The scene has ONE render-target budget and mirror.js or
+ wetground.js has usually already spent it. A curtain wall that
+ quietly allocates a second one costs a frame nobody authorised, so
+ the fresnel sky has to be computed, not rendered."""
+ src = (LIB_DIR / "urban.js").read_text(encoding="utf-8")
+ # Comments may NAME the thing they refuse to use; code may not.
+ code = "\n".join(
+ line for line in src.splitlines()
+ if not line.lstrip().startswith(("*", "//", "/*")))
+ for banned in ("WebGLRenderTarget", "WebGLCubeRenderTarget",
+ "new Reflector", "CubeCamera"):
+ assert banned not in code, (
+ f"urban.js reaches for {banned}; the scene's one RTT is "
+ "already spent by mirror.js or wetground.js")
+
+
+def test_every_glow_is_kept_out_of_the_occlusion_pass():
+ """A depth/occlusion override pass redraws the scene with an opaque
+ material, where a transparent glow card is a solid wall. It also
+ stops the mesh casting a shadow, which a light source must not do."""
+ out = measure("""
+import * as THREE from 'three';
+import { makeBillboard, makePowerLines } from './lib/urban.js';
+const check = (g) => {
+ let transparent = 0, guarded = 0, casting = 0;
+ g.traverse((o) => {
+ if (!o.isMesh) return;
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.transparent) {
+ transparent++;
+ if (o.userData.astraNoOverride) guarded++;
+ if (o.castShadow) casting++;
+ }
+ }
+ });
+ return { transparent, guarded, casting };
+};
+console.log(JSON.stringify({
+ billboard: check(makeBillboard({ lit: true, seed: 3 })),
+ lines: check(makePowerLines({ seed: 3 })),
+}));
+""", _LIBS)
+ for who, r in out.items():
+ assert r["transparent"], f"{who} built no transparent mesh at all"
+ assert r["guarded"] == r["transparent"], (
+ f"{who} leaves {r['transparent'] - r['guarded']} transparent "
+ "meshes in the occlusion buffer")
+ assert r["casting"] == 0, f"{who} casts a shadow from a glow"
+
+
+_FIXTURE = """
+import * as THREE from 'three';
+import { patchCurtainWall, makePowerLines, makeBillboard }
+ from './lib/urban.js';
+const g = new THREE.Group();
+const glass = new THREE.MeshStandardMaterial({ color: 0x2b3a4a });
+patchCurtainWall(glass, {});
+g.add(new THREE.Mesh(new THREE.BoxGeometry(8, 30, 8), glass));
+// Instanced too: the patch folds instanceMatrix in by hand, and that
+// branch only compiles when something instanced carries the material.
+g.add(new THREE.InstancedMesh(new THREE.BoxGeometry(2, 2, 2), glass, 3));
+g.add(makePowerLines({ seed: 5 }));
+g.add(makeBillboard({ lit: true, seed: 6 }));
+const round = new THREE.MeshStandardMaterial({ color: 0x223028 });
+patchCurtainWall(round, { curve: 4.5, coat: 1, blinds: 0.4 });
+g.add(new THREE.Mesh(new THREE.CylinderGeometry(4, 4, 12, 24, 1, true),
+ round));
+"""
+
+
+def test_the_three_compile_in_a_fogged_scene():
+ """rain.js shipped fog chunks that could not compile for months
+ because only asset mode was ever checked: asset mode builds an
+ UNFOGGED scene, so USE_FOG is never defined and the branch is never
+ compiled. So the fogged half is built as a real scene here, through
+ `_probe.compile_scene` — the asset half of the reference test proves
+ strictly less and is not ported."""
+ code, out = compile_scene(_FIXTURE + """
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 34, 20] };
+export function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xc9d6e0, 0.006);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ const sun = new THREE.DirectionalLight(0xfff0d6, 2.5);
+ sun.position.set(5, 8, 7);
+ sun.castShadow = true;
+ scene.add(sun);
+ scene.add(g);
+ // A camera, or the host reports a scene that never booted and the
+ // compile stage is never reached.
+ return { scene, update() {},
+ cameras: [{ name: 'a', position: [16, 8, 20],
+ lookAt: [0, 6, 0], fov: 45 }] };
+}
+""", _LIBS)
+ assert code == 0, out
+ assert "WARN" not in out, out
+
+
+def test_one_seed_builds_the_same_street_twice():
+ out = measure("""
+import { makePowerLines, makeBillboard } from './lib/urban.js';
+// Names and vertex COUNTS do not move with a seed; the vertices do.
+const shape = (g) => {
+ const v = [];
+ g.traverse((o) => {
+ if (!o.isMesh) return;
+ const p = o.geometry.getAttribute('position');
+ let s = 0;
+ if (p) for (let i = 0; i < p.count; i += 7) s += p.getX(i) + p.getY(i);
+ v.push(o.name, p ? p.count : 0, s.toFixed(5));
+ });
+ return v.join('|');
+};
+console.log(JSON.stringify({
+ same: shape(makePowerLines({ seed: 8 }))
+ === shape(makePowerLines({ seed: 8 })),
+ differs: shape(makePowerLines({ seed: 8 }))
+ !== shape(makePowerLines({ seed: 12 })),
+ boardSame: shape(makeBillboard({ seed: 2 }))
+ === shape(makeBillboard({ seed: 2 })),
+}));
+""", _LIBS)
+ assert out["same"] and out["differs"] and out["boardSame"]
+
+
+# ------------------------------------------------- the port's own laws
+
+def _poster(opts: str = "{ lit: true, seed: 2 }") -> tuple[int, list]:
+ out = measure(_POSTER % opts, _LIBS)
+ return out["size"], out["rgb"]
+
+
+def _lum(rgb: list, i: int) -> float:
+ r, g, b = rgb[i * 3] / 255, rgb[i * 3 + 1] / 255, rgb[i * 3 + 2] / 255
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
+
+
+def test_a_poster_is_printed_ink_and_not_a_light_source():
+ """LAW 1. Paper reflects; it does not emit. The sheet used to print
+ its headline at L 0.92 and clipped under its own lamps (blown_frac
+ 0.120 by day, 0.276 at night, measured over the poster's pixels).
+ The band is held on luminance so a dark ink keeps its hue."""
+ size, rgb = _poster()
+ lum = [_lum(rgb, i) for i in range(size * size)]
+ assert min(lum) >= 0.15, (
+ f"the darkest ink is a hole at {min(lum):.3f} (0.155 sRGB is "
+ "0.02 linear, the floor of the albedo band)")
+ assert max(lum) <= 0.805, (
+ f"the sheet peaks at {max(lum):.3f}; 0.80 sRGB is 0.60 linear "
+ "and leaves the top of the band for the lamps")
+ # It must still be a POSTER: several inks over paper that is not one
+ # flat fill, not a tinted rectangle inside the band.
+ assert len({round(v, 2) for v in lum}) >= 10, (
+ "the whole sheet is two or three flat tones — ink density, the "
+ "paste seams and the bleach all have to survive the clamp")
+ mean = sum(lum) / len(lum)
+ std = (sum((v - mean) ** 2 for v in lum) / len(lum)) ** 0.5
+ assert std > 0.08, f"the sheet is one tone (lum std {std:.3f})"
+
+
+def test_the_paper_grain_is_band_limited_and_not_a_beat():
+ """LAW 2. `sin(u * 91.7 + v * 47.3) * 43758.5 % 1` is not a hash at
+ those frequencies: neighbouring texels are uncorrelated (white
+ noise), which magnified 40x over a hoarding beats against the
+ sampler and prints diagonal stripes. Real grain is band-limited —
+ neighbours differ by a fraction of the sheet's own spread. Measured
+ ratio: 1.153 for the old field, 0.032 for fBm."""
+ size, rgb = _poster()
+ lum = [_lum(rgb, i) for i in range(size * size)]
+ mean = sum(lum) / len(lum)
+ std = (sum((v - mean) ** 2 for v in lum) / len(lum)) ** 0.5
+ steps, n = 0.0, 0
+ for y in range(size):
+ row = lum[y * size:(y + 1) * size]
+ for x in range(size - 1):
+ steps += abs(row[x + 1] - row[x])
+ n += 1
+ ratio = (steps / n) / max(std, 1e-6)
+ assert ratio < 0.35, (
+ f"neighbouring texels differ by {ratio:.3f} of the sheet's own "
+ "spread — that is per-texel white noise, which is what printed "
+ "as diagonal stripes over the board")
+
+
+def test_the_halo_never_veils_the_board_it_glows_around():
+ """LAW 3. The glow card peaked over the OPAQUE board, and with no
+ bloom pass in our renderer that additive sheet only flattened the
+ artwork — it clipped the poster's top band by day and at night.
+ Hollowed out over the board's outline, and gone in daylight."""
+ out = measure("""
+import { makeBillboard } from './lib/urban.js';
+const read = (opts) => {
+ const g = makeBillboard(opts);
+ let glow = null, board = null;
+ g.traverse((o) => {
+ if (o.name === 'Glow') glow = o;
+ if (o.name === 'Board') board = o;
+ });
+ if (!glow) return { none: true };
+ const u = glow.material.uniforms;
+ glow.geometry.computeBoundingBox();
+ board.geometry.computeBoundingBox();
+ const gb = glow.geometry.boundingBox, bb = board.geometry.boundingBox;
+ return {
+ core: u.uBbCore.value,
+ inner: [u.uBbInner.value.x, u.uBbInner.value.y],
+ gain: u.uBbGain.value,
+ hollows: /uBbInner/.test(glow.material.fragmentShader),
+ cardW: gb.max.x - gb.min.x, boardW: bb.max.x - bb.min.x,
+ cardH: gb.max.y - gb.min.y, boardH: bb.max.y - bb.min.y,
+ };
+};
+console.log(JSON.stringify({
+ hoarding: read({ lit: true, kind: 'hoarding', ambient: 0.15, seed: 2 }),
+ panel: read({ lit: true, kind: 'panel', ambient: 0.15, seed: 2 }),
+ noon: read({ lit: true, kind: 'hoarding', ambient: 0.95, seed: 2 }),
+ unlit: read({ lit: false, seed: 2 }),
+}));
+""", _LIBS)
+ h = out["hoarding"]
+ assert h["hollows"], "the halo does not read the board's own outline"
+ assert h["core"] == 0, (
+ "a pasted sheet does not glow through itself; only a light box "
+ f"keeps a core (got {h['core']})")
+ assert out["panel"]["core"] > 0, (
+ "a light box's face really does emit — its core is not zero")
+ # The hollow only means something if the card is bigger than the board.
+ for who in ("hoarding", "panel"):
+ r = out[who]
+ assert r["cardW"] > r["boardW"] * 1.2 and r["cardH"] > r["boardH"] * 1.2, (
+ f"{who}: the halo has no air to stand in "
+ f"({r['cardW']:.2f} x {r['cardH']:.2f} vs the board's "
+ f"{r['boardW']:.2f} x {r['boardH']:.2f})")
+ assert abs(r["inner"][0] - r["boardW"] / r["cardW"]) < 0.02, (
+ f"{who}: uBbInner does not match where the board falls on "
+ "the card, so the hollow is cut in the wrong place")
+ assert out["noon"]["gain"] < out["hoarding"]["gain"] * 0.25, (
+ "a halo is light scattered in the air: in open daylight it has "
+ f"to all but vanish (gain {out['noon']['gain']:.3f} against "
+ f"{out['hoarding']['gain']:.3f} on an unlit street)")
+ assert out["unlit"].get("none"), "an unlit hoarding built a halo"
+
+
+def test_a_run_of_poles_is_not_one_flat_brown():
+ """LAW 4. Twenty poles merged into one mesh share one colour, which
+ reads as the same prop repeated. The weathering rides in a vertex
+ colour — and only DARKENS, so `color` stays the true albedo."""
+ out = measure("""
+import { makePowerLines } from './lib/urban.js';
+const read = (name, g) => {
+ let mesh = null;
+ g.traverse((o) => { if (o.name === name) mesh = o; });
+ const c = mesh.geometry.getAttribute('color');
+ const v = [];
+ for (let i = 0; i < c.count; i++) v.push(c.getX(i), c.getY(i), c.getZ(i));
+ return { vertexColors: !!mesh.material.vertexColors,
+ max: Math.max(...v), min: Math.min(...v),
+ mean: v.reduce((a, b) => a + b, 0) / v.length,
+ n: v.length };
+};
+const g = makePowerLines({ points: [[-30, 0, 0], [30, 0, 0]], spans: 6,
+ seed: 5 });
+console.log(JSON.stringify({ poles: read('Poles', g),
+ ins: read('Insulators', g) }));
+""", _LIBS)
+ for who, r in out.items():
+ assert r["vertexColors"], f"{who} ignores the weathering it carries"
+ assert r["max"] <= 1.0001, (
+ f"{who} brightens its own albedo to {r['max']:.3f}; a vertex "
+ "colour here may only darken or `color` stops being the albedo")
+ assert r["max"] - r["min"] > 0.15, (
+ f"{who} varies by only {r['max'] - r['min']:.3f} — that is one "
+ "flat prop again")
+ assert 0.72 < r["mean"] < 1.0, (
+ f"{who} is dimmed to {r['mean']:.3f} on average, which is a "
+ "new colour rather than weathering on the documented one")
+
+
+def test_the_glass_reflects_a_tinted_image():
+ """LAW 5. An untinted reflection returns the sky, so under a hazy
+ sky every tower read as one grey sheet whatever `tint` said —
+ measured saturation 0.205 over a blue facade, 0.111 over a green
+ one. `coat` puts the glass hue into what it mirrors."""
+ out = measure(r"""
+import * as THREE from 'three';
+import { patchCurtainWall } from './lib/urban.js';
+const uni = (o) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchCurtainWall(m, o);
+ return m.userData.uniforms;
+};
+const m = new THREE.MeshStandardMaterial();
+patchCurtainWall(m, {});
+const s = { uniforms: {}, vertexShader: 'void main() {}',
+ fragmentShader: '#include <color_fragment>' };
+m.onBeforeCompile(s);
+const fs = s.fragmentShader;
+// The reflected radiance must be multiplied by the tint, and the panel
+// key must reach it, before it is added as light.
+const body = fs.slice(0, fs.indexOf('totalEmissiveRadiance'));
+console.log(JSON.stringify({
+ dflt: uni({}).uCwCoat.value,
+ off: uni({ coat: 0 }).uCwCoat.value,
+ clamped: uni({ coat: 4 }).uCwCoat.value,
+ tintsReflection: /cwRefl\s*\*=[^;]*uCwTint/.test(body),
+ perPanelReflection: /cwRefl\s*\*=[^;]*astraCwJit|cwJb|cwJh/.test(body),
+}));
+""", _LIBS)
+ assert 0.2 <= out["dflt"] <= 0.7, (
+ f"the default coat is {out['dflt']} — 0 gives back the grey "
+ "sheet and 1 is a mirror-glass tower, not a default")
+ assert out["off"] == 0 and out["clamped"] == 1, "coat must clamp to 0..1"
+ assert out["tintsReflection"], (
+ "the reflected image carries no glass hue, so the facade "
+ "returns whatever the sky is and reads grey")
+ assert out["perPanelReflection"], (
+ "every panel reflects the identical radiance — one coating "
+ "batch, i.e. one mirror sheet again")
diff --git a/harness/tests/scene_runtime/lib/test_veils.py b/harness/tests/scene_runtime/lib/test_veils.py
new file mode 100644
index 00000000..802d4e5d
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_veils.py
@@ -0,0 +1,661 @@
+"""veils.js: weather seen AT DISTANCE — rain sheets, snowfall, dust motes.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_veils_lib.py). Its physical laws are kept exactly as they
+stood, because each one is about the effect rather than about their
+renderer: the rain veil must slant with the wind it is given and travel in
+a straight line, the snow must WANDER (that is the whole difference
+between snow and white rain), the motes must hang inside the box the
+caller was promised, every field must replay from its seed, and one tick
+must reach every material. Their two renderer-contract tests are folded
+into one compile check here — our renderer runs logarithmicDepthBuffer OFF
+so the logdepth chunks are no-ops, but the FOG branch trap they were
+written for is real on any host, so both the fogged and the fog-less scene
+are still compiled on the GPU.
+
+THE PORT'S OWN LAW — measured on our host at fx/out/veils/, each frame
+looked at and diffed against a control render of the same scene with the
+three fields removed (fx/out/veils_none/):
+
+ A VEIL IS NOT A LAMP. All three materials are unlit billboards at a
+ constant colour, and an unlit pale card is the brightest thing in any
+ frame that is not daylight. On the moonlit rig the shipped rain
+ curtain added +0.189 luminance to the sky band it crossed, with peaks
+ at 0.523 over a scene whose own mean was 0.170 — a sheet GLOWING in
+ front of a night sky (fx/out/veils/before_night/frames/mid_t1p5.png) —
+ and the motes stayed white inside a shadow. Nothing here can be lit
+ properly, because a veil is a volume and not a surface; but what it
+ SCATTERS is the irradiance where it hangs, and that is one vec3 the
+ scene can be asked for. Each field now probes its own scene's lights
+ every few frames and multiplies its colour by the answer, normalised so
+ the library's own day rig lands on 1.0 — so daylight is unchanged
+ (mid mean_lum 0.6121 -> 0.6125) and the same night curtain adds +0.081
+ at a peak of 0.249, in the night's own blue (saturation 0.31 -> 0.50)
+ rather than in grey. A lamp is included with its falloff at the
+ field's own origin, which is what puts a mote volume standing in a
+ lamp's pool into that pool.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "veils.js")
+# The light probe is calibrated against the library's OWN day rig, so the
+# test that holds the calibration has to build one.
+_RIG_LIBS = ("shader.js", "veils.js", "environment.js", "sky.js")
+
+_SCENE = """
+import * as THREE from 'three';
+import { makeRainVeil, makeSnowfall, makeMotes } from './lib/veils.js';
+
+export const BOUNDS = { min: [-60, 0, -60], max: [60, 45, 60] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ __FOG__
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ const veil = makeRainVeil({ extent: 90, height: 40, direction: [4, 2] });
+ const snow = makeSnowfall({ extent: 30, height: 14, seed: 4 });
+ const motes = makeMotes({ extent: 5, height: 3, seed: 6 });
+ scene.add(veil); scene.add(snow); scene.add(motes);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [20, 6, 24], lookAt: [0, 8, 0],
+ fov: 45 }],
+ update(t) {
+ veil.userData.tick(t);
+ snow.userData.tick(t);
+ motes.userData.tick(t);
+ },
+ };
+}
+"""
+
+# Perpendicular deviation of a horizontal path from its own chord: the one
+# number that separates a wandering flake from a drifting sheet.
+_DEVIATE = """
+const deviate = (pts) => {
+ const a = pts[0], b = pts[pts.length - 1];
+ const dx = b[0] - a[0], dz = b[1] - a[1];
+ const len = Math.hypot(dx, dz);
+ if (len < 1e-9) return 0;
+ let m = 0;
+ for (const p of pts) {
+ m = Math.max(m, Math.abs((p[0] - a[0]) * dz - (p[1] - a[1]) * dx) / len);
+ }
+ return m;
+};
+const jumped = (pts, lim) => {
+ for (let i = 1; i < pts.length; i++) {
+ if (Math.hypot(pts[i][0] - pts[i - 1][0],
+ pts[i][1] - pts[i - 1][1]) > lim) return true;
+ }
+ return false;
+};
+"""
+
+_PROBE = """
+import * as THREE from 'three';
+import { makeRainVeil, makeSnowfall, makeMotes } from './lib/veils.js';
+
+const fields = {
+ veil: [makeRainVeil({ extent: 90, height: 40, direction: [4, 2],
+ seed: 3 }), 'RainSheets'],
+ snow: [makeSnowfall({ extent: 36, height: 16, seed: 4 }), 'Snowflakes'],
+ mote: [makeMotes({ extent: 5, height: 3, count: 400, seed: 6 }),
+ 'DustMotes'],
+};
+
+const out = { fromHelper: true, outChunks: true, blending: {}, guard: {},
+ tick: {}, radius: {}, centre: {}, uniforms: {} };
+for (const [k, [g, name]] of Object.entries(fields)) {
+ const m = g.getObjectByName(name);
+ if (!m.material.userData.astraShader) out.fromHelper = false;
+ const fs = m.material.fragmentShader;
+ if (!fs.includes('tonemapping_fragment')
+ || !fs.includes('colorspace_fragment')) out.outChunks = false;
+ out.blending[k] = [m.material.blending === THREE.NormalBlending,
+ !!m.material.transparent, !!m.material.depthWrite];
+ out.guard[k] = [!!m.userData.astraNoOverride, m.castShadow === true];
+ out.radius[k] = m.geometry.boundingSphere.radius;
+ out.centre[k] = m.geometry.boundingSphere.center.toArray();
+ out.uniforms[k] = Object.keys(m.material.uniforms).sort();
+ const u = m.material.uniforms;
+ const at0 = u.uTime.value;
+ const n = g.userData.tick(4.25);
+ out.tick[k] = { at0, n, after: u.uTime.value };
+}
+console.log(JSON.stringify(out));
+"""
+
+# One fake renderer frame per case: the light probe hangs off
+# onBeforeRender, which is the only place a Mesh is handed its scene.
+_LIGHT = """
+import * as THREE from 'three';
+import { makeRainVeil, makeSnowfall, makeMotes } from './lib/veils.js';
+import { sunRig } from './lib/environment.js';
+
+const R = { info: { render: { frame: 0 } } };
+const draw = (obj, scene, frame) => {
+ R.info.render.frame = frame;
+ obj.traverse((o) => {
+ if (o.isMesh && o.onBeforeRender) {
+ o.onBeforeRender(R, scene, null, o.geometry, o.material, null);
+ }
+ });
+};
+const rigScene = (elev, fog) => {
+ const s = new THREE.Scene();
+ const rig = sunRig({ azimuth: 215, elevation: elev });
+ s.add(rig.sun); s.add(rig.fill);
+ s.fog = new THREE.FogExp2(fog, 0.0035);
+ return s;
+};
+const lit = (mesh) => mesh.material.uniforms.uLight.value.toArray();
+const col = (mesh) => mesh.material.uniforms.uColor.value.toArray();
+const hsl = (mesh) => {
+ const o = { h: 0, s: 0, l: 0 };
+ mesh.material.uniforms.uColor.value.getHSL(o);
+ return [o.h, o.s, o.l];
+};
+
+const out = {};
+
+// 1. daylight, the rig the normalisation is calibrated against
+const day = rigScene(38, 0xcfd8e6);
+const dayVeil = makeRainVeil({ extent: 70 });
+day.add(dayVeil);
+draw(dayVeil, day, 100);
+out.dayVeil = lit(dayVeil.children[0]);
+
+// 2. the same field under the moon
+const night = rigScene(-20, 0x0b0f1a);
+const nightVeil = makeRainVeil({ extent: 70 });
+const nightSnow = makeSnowfall({ extent: 30, height: 14 });
+const nightMote = makeMotes({ extent: 5, height: 3 });
+nightMote.position.set(1.2, 0, 2.4);
+night.add(nightVeil); night.add(nightSnow); night.add(nightMote);
+night.updateMatrixWorld(true);
+draw(nightVeil, night, 200);
+draw(nightSnow, night, 200);
+draw(nightMote, night, 200);
+out.nightVeil = lit(nightVeil.children[0]);
+out.nightSnow = lit(nightSnow.children[0]);
+out.nightMote = lit(nightMote.children[0]);
+// and the fog hue it adopted, against the untouched default
+out.nightVeilHsl = hsl(nightVeil.children[0]);
+out.dayVeilHsl = hsl(dayVeil.children[0]);
+out.plainHsl = (() => {
+ const o = { h: 0, s: 0, l: 0 };
+ new THREE.Color(0xb9c6d4).getHSL(o);
+ return [o.h, o.s, o.l];
+})();
+out.fogHue = (() => {
+ const o = { h: 0, s: 0, l: 0 };
+ night.fog.color.getHSL(o);
+ return o.h;
+})();
+
+// 3. the same night, with a lamp two metres from the mote volume
+const lampScene = rigScene(-20, 0x0b0f1a);
+const lamp = new THREE.PointLight(0xffd2a0, 90, 34, 2);
+lamp.position.set(3.6, 4.6, 3.4);
+lampScene.add(lamp);
+const lampMote = makeMotes({ extent: 5, height: 3 });
+lampMote.position.set(1.2, 0, 2.4);
+const farMote = makeMotes({ extent: 5, height: 3 });
+farMote.position.set(-40, 0, -40);
+lampScene.add(lampMote); lampScene.add(farMote);
+lampScene.updateMatrixWorld(true);
+draw(lampMote, lampScene, 300);
+draw(farMote, lampScene, 300);
+out.lampMote = lit(lampMote.children[0]);
+out.farMote = lit(farMote.children[0]);
+
+// 4. a scene with no lights at all — an asset preview, or the shader
+// check's own fixture: the veil must stay exactly as authored
+const bare = new THREE.Scene();
+const bareVeil = makeRainVeil({ extent: 70 });
+bare.add(bareVeil);
+draw(bareVeil, bare, 400);
+out.bareVeil = lit(bareVeil.children[0]);
+out.bareColor = col(bareVeil.children[0]);
+
+// 5. a colour the caller gave is a statement, not a default
+const given = rigScene(-20, 0x0b0f1a);
+const givenVeil = makeRainVeil({ extent: 70, color: 0x88ff44 });
+given.add(givenVeil);
+draw(givenVeil, given, 500);
+out.givenColor = col(givenVeil.children[0]);
+out.wantGiven = new THREE.Color(0x88ff44).toArray();
+
+console.log(JSON.stringify(out));
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch of _PROBE, shared by every test that reads it."""
+ return measure(_PROBE, _LIBS)
+
+
[email protected](scope="module")
+def light() -> dict:
+ """One node launch of _LIGHT: the scene-light probe under four rigs."""
+ return measure(_LIGHT, _RIG_LIBS)
+
+
+# --- the reference's laws, kept ---------------------------------------
+
+
+def test_the_stated_bounding_sphere_covers_each_field():
+ """`position` is all zeros, so the sphere is the only thing three can
+ cull these fields by: state it too small and the whole field vanishes
+ the moment the origin leaves frame, state it huge and a field long out
+ of shot is drawn every frame."""
+ out = measure("""
+import { makeRainVeil, makeSnowfall, makeMotes } from './lib/veils.js';
+
+const cross = (a, b) => [a[1] * b[2] - a[2] * b[1],
+ a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+const unit = (v) => {
+ const l = Math.hypot(v[0], v[1], v[2]);
+ return [v[0] / l, v[1] / l, v[2] / l];
+};
+
+const veil = makeRainVeil({ extent: 90, height: 40, direction: [4, 2],
+ seed: 3 });
+const vm = veil.getObjectByName('RainSheets');
+const vu = vm.material.uniforms;
+const sheet = vm.geometry.attributes.aSheet.array;
+const ax = [vu.uAxis.value.x, vu.uAxis.value.y, vu.uAxis.value.z];
+const up = [-ax[0], -ax[1], -ax[2]];
+// The quad's width rides on cross(axis, toCamera), which is any unit
+// vector in the plane perpendicular to the axis — so sweep that plane.
+const b1 = unit(cross(ax, Math.abs(ax[0]) > 0.9 ? [0, 0, 1] : [1, 0, 0]));
+const b2 = unit(cross(ax, b1));
+let veilNeed = 0;
+for (let i = 0; i < vm.geometry.instanceCount; i++) {
+ const hw = sheet[i * 4 + 2];
+ for (let k = 0; k <= 70; k++) {
+ const p = veil.userData.sample(i, k * 1.7);
+ for (const c of [0, 1]) {
+ const base = [p.x + up[0] * vu.uLen.value * c,
+ p.y + up[1] * vu.uLen.value * c,
+ p.z + up[2] * vu.uLen.value * c];
+ for (let a = 0; a < 16; a++) {
+ const th = (a / 16) * Math.PI * 2;
+ const c1 = Math.cos(th), s1 = Math.sin(th);
+ veilNeed = Math.max(veilNeed, Math.hypot(
+ base[0] + (b1[0] * c1 + b2[0] * s1) * hw,
+ base[1] + (b1[1] * c1 + b2[1] * s1) * hw,
+ base[2] + (b1[2] * c1 + b2[2] * s1) * hw));
+ }
+ }
+ }
+}
+
+const snow = makeSnowfall({ extent: 36, height: 16, seed: 4 });
+const sm = snow.getObjectByName('Snowflakes');
+const su = sm.material.uniforms;
+const flake = sm.geometry.attributes.aFlake.array;
+let sScale = 0;
+for (let i = 0; i < sm.geometry.instanceCount; i++) {
+ sScale = Math.max(sScale, flake[i * 4]);
+}
+// Worst case a flake is drawn at: full bokeh, corner of its quad.
+const sHalf = su.uSize.value * sScale * (1 + su.uBokeh.value) * Math.SQRT1_2;
+let snowNeed = 0;
+for (let i = 0; i < sm.geometry.instanceCount; i += 5) {
+ for (let k = 0; k < 45; k++) {
+ snowNeed = Math.max(snowNeed,
+ snow.userData.sample(i, k * 0.83).length() + sHalf);
+ }
+}
+
+const motes = makeMotes({ extent: 5, height: 3, count: 400, seed: 6 });
+const mm = motes.getObjectByName('DustMotes');
+const mu = mm.material.uniforms;
+const mote = mm.geometry.attributes.aMote.array;
+let mScale = 0;
+for (let i = 0; i < mm.geometry.instanceCount; i++) {
+ mScale = Math.max(mScale, mote[i * 4]);
+}
+const mHalf = mu.uSize.value * mScale * 1.2 * Math.SQRT1_2;
+let moteNeed = 0;
+for (let i = 0; i < mm.geometry.instanceCount; i += 3) {
+ for (let k = 0; k < 40; k++) {
+ moteNeed = Math.max(moteNeed,
+ motes.userData.sample(i, k * 1.3).length() + mHalf);
+ }
+}
+
+console.log(JSON.stringify({
+ veilRadius: vm.geometry.boundingSphere.radius, veilNeed,
+ snowRadius: sm.geometry.boundingSphere.radius, snowNeed,
+ moteRadius: mm.geometry.boundingSphere.radius, moteNeed,
+}));
+""", _LIBS)
+ assert out["veilRadius"] >= out["veilNeed"], out
+ assert out["snowRadius"] >= out["snowNeed"], out
+ assert out["moteRadius"] >= out["moteNeed"], out
+ # And not a made-up huge number, which keeps a field that left the
+ # frame long ago in every draw call.
+ assert out["veilRadius"] <= out["veilNeed"] * 1.5, out
+ assert out["snowRadius"] <= out["snowNeed"] * 1.15, out
+ assert out["moteRadius"] <= out["moteNeed"] * 1.15, out
+
+
+def test_the_sphere_is_local_because_the_group_carries_the_placement(probe):
+ """A sphere centred anywhere but the field's own origin is culled
+ against the wrong point the moment the caller moves the group."""
+ assert probe["centre"]["veil"] == [0, 0, 0], probe["centre"]
+ assert probe["centre"]["mote"] == [0, 0, 0], probe["centre"]
+
+
+def test_snow_wanders_where_rain_falls_in_a_straight_line():
+ """The one property that separates snow from rain that is white. A
+ drop falls at 9 m/s down a line the wind tilts; a flake falls at under
+ one and its horizontal path is a curve going nowhere. Both claims are
+ measured against the same yardstick — how far the path departs from
+ its own chord."""
+ out = measure(_DEVIATE + """
+import { makeRainVeil, makeSnowfall } from './lib/veils.js';
+
+const veil = makeRainVeil({ extent: 120, height: 50, direction: [4, 2],
+ seed: 3 });
+const rainDev = [];
+for (let i = 0; i < veil.getObjectByName('RainSheets')
+ .geometry.instanceCount; i++) {
+ const pts = [];
+ for (let k = 0; k <= 24; k++) {
+ const p = veil.userData.sample(i, k * 0.4);
+ pts.push([p.x, p.z]);
+ }
+ if (!jumped(pts, 30)) rainDev.push(deviate(pts));
+}
+
+const snow = makeSnowfall({ extent: 40, height: 18, seed: 4 });
+const sm = snow.getObjectByName('Snowflakes');
+const snowDev = [];
+let slowest = 0;
+for (let i = 0; i < 400; i++) {
+ const pts = [];
+ for (let k = 0; k <= 24; k++) {
+ const p = snow.userData.sample(i, k * 0.4);
+ pts.push([p.x, p.z]);
+ }
+ if (!jumped(pts, 10)) snowDev.push(deviate(pts));
+}
+snowDev.sort((a, b) => a - b);
+const fall = sm.material.uniforms.uFall.value;
+const flake = sm.geometry.attributes.aFlake.array;
+for (let i = 0; i < sm.geometry.instanceCount; i++) {
+ slowest = Math.max(slowest, fall * flake[i * 4 + 1]);
+}
+console.log(JSON.stringify({
+ rainMaxDev: Math.max(...rainDev),
+ rainPaths: rainDev.length,
+ snowMedDev: snowDev[Math.floor(snowDev.length / 2)],
+ snowMinDev: snowDev[0],
+ snowPaths: snowDev.length,
+ snowFastestFall: slowest,
+ rainFall: veil.getObjectByName('RainSheets')
+ .material.uniforms.uFall.value,
+}));
+""", _LIBS)
+ # Paths that wrapped inside the window are dropped, so both counts are
+ # floors, not the field size.
+ assert out["rainPaths"] >= 3 and out["snowPaths"] >= 200, out
+ # A sheet travels with the wind: a straight line, to float error.
+ assert out["rainMaxDev"] < 1e-4, out
+ # A flake does not.
+ assert out["snowMedDev"] > 0.08, out
+ assert out["snowMinDev"] > 0.005, out
+ # And it FALLS SLOWLY: even the heaviest flake is far under rain.
+ assert out["snowFastestFall"] < 1.5, out
+ assert out["rainFall"] > 8.9, out
+
+
+def test_the_rain_sheets_slant_with_the_wind_they_are_given():
+ """A vertical curtain reads as a projection screen. The sheet lies
+ along the path a drop actually takes, so its top is UPWIND of its foot
+ — a drop travels downwind as it falls — and the tilt is the wind speed
+ against the 9 m/s fall, not a decorative angle."""
+ out = measure("""
+import { makeRainVeil } from './lib/veils.js';
+const probe = (dir) => {
+ const g = makeRainVeil({ extent: 80, height: 30, direction: dir, seed: 5 });
+ const u = g.getObjectByName('RainSheets').material.uniforms;
+ const a = u.uAxis.value;
+ const foot = g.userData.sample(0, 0);
+ const len = g.userData.length;
+ const top = [foot.x - a.x * len, foot.y - a.y * len, foot.z - a.z * len];
+ const w = Math.hypot(dir[0], dir[1]);
+ return {
+ axis: [a.x, a.y, a.z],
+ // The horizontal part of the axis must lie ALONG the wind.
+ para: (a.x * dir[1] - a.z * dir[0]) / Math.max(w, 1e-9),
+ along: (a.x * dir[0] + a.z * dir[1]) / Math.max(w, 1e-9),
+ tilt: Math.hypot(a.x, a.z) / -a.y,
+ want: w / 9,
+ lean: [top[0] - foot.x, top[2] - foot.z],
+ rise: top[1] - foot.y,
+ height: u.uLen.value * -a.y,
+ };
+};
+console.log(JSON.stringify({
+ east: probe([4.5, 0]), skew: probe([3, -5]), calm: probe([0, 0]),
+}));
+""", _LIBS)
+ for name in ("east", "skew"):
+ p = out[name]
+ assert p["axis"][1] < -0.5, (name, p)
+ assert abs(p["para"]) < 1e-6, (name, p)
+ assert p["along"] > 0, (name, p)
+ # tan(tilt) is the wind against the fall, to a percent.
+ assert abs(p["tilt"] - p["want"]) < 0.01 * p["want"] + 1e-6, p
+ # Top upwind of foot, and the sheet still spans the height it was
+ # asked for however far it leans.
+ assert p["lean"][0] * p["axis"][0] < 0, (name, p)
+ assert p["rise"] > 0, (name, p)
+ assert abs(p["height"] - 30) < 0.05, (name, p)
+ # No wind is a plumb curtain, not a division by zero.
+ assert out["calm"]["axis"] == [0, -1, 0], out["calm"]
+ assert out["calm"]["tilt"] == 0, out["calm"]
+
+
+def test_motes_stay_inside_the_volume_they_state():
+ """Dust HANGS. The wander is what stops it reading as a dot screen,
+ so it is real — but it is bounded, and a mote that leaves the box the
+ caller was promised is a speck floating outside the shaft it was
+ placed in. It must also FILL that box, or the guarantee is met by a
+ field that never moves at all."""
+ out = measure("""
+import { makeMotes } from './lib/veils.js';
+const g = makeMotes({ extent: 6, height: 4, count: 500, seed: 6 });
+const n = g.getObjectByName('DustMotes').geometry.instanceCount;
+let outside = 0, maxX = 0, maxZ = 0, maxY = 0, minY = 1e9, fastest = 0;
+for (let i = 0; i < n; i++) {
+ for (let k = 0; k <= 60; k++) {
+ const t = k * 1.7;
+ const p = g.userData.sample(i, t);
+ if (Math.abs(p.x) > 3 + 1e-6 || Math.abs(p.z) > 3 + 1e-6
+ || p.y < -1e-6 || p.y > 4 + 1e-6) outside++;
+ maxX = Math.max(maxX, Math.abs(p.x));
+ maxZ = Math.max(maxZ, Math.abs(p.z));
+ maxY = Math.max(maxY, p.y);
+ minY = Math.min(minY, p.y);
+ // Step over a short interval, so the settle wrap is not a speed.
+ const q = g.userData.sample(i, t + 0.5);
+ if (Math.abs(q.y - p.y) < 1) {
+ fastest = Math.max(fastest,
+ Math.hypot(q.x - p.x, q.y - p.y, q.z - p.z) / 0.5);
+ }
+ }
+}
+console.log(JSON.stringify({ outside, maxX, maxZ, maxY, minY, fastest,
+ volume: g.userData.volume }));
+""", _LIBS)
+ assert out["volume"] == {"extent": 6, "height": 4}
+ assert out["outside"] == 0, out
+ # It uses the box it claims, rather than hiding in the middle.
+ assert out["maxX"] > 2.4 and out["maxZ"] > 2.4, out
+ assert out["maxY"] > 3.6 and out["minY"] < 0.4, out
+ # Near-still: dust hangs. Anything faster is snow.
+ assert out["fastest"] < 0.3, out
+
+
+def test_the_same_seed_builds_the_same_field():
+ """These ship into scenes rendered again and again from the same code;
+ a field that resamples is a scene that will not reproduce, and a seed
+ that changes nothing is not a seed."""
+ out = measure("""
+import { makeRainVeil, makeSnowfall, makeMotes } from './lib/veils.js';
+const dump = (mesh, names) => names.map((k) =>
+ Array.from(mesh.geometry.attributes[k].array));
+const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
+const veil = (s) => dump(makeRainVeil({ extent: 70, seed: s })
+ .getObjectByName('RainSheets'), ['aSheet', 'aVeil']);
+const snow = (s) => dump(makeSnowfall({ extent: 20, seed: s })
+ .getObjectByName('Snowflakes'), ['aPos', 'aFlake', 'aSwing']);
+const mote = (s) => dump(makeMotes({ count: 60, seed: s })
+ .getObjectByName('DustMotes'), ['aPos', 'aMote', 'aSwing']);
+console.log(JSON.stringify({
+ veilSame: same(veil(11), veil(11)), veilDiff: !same(veil(11), veil(12)),
+ snowSame: same(snow(11), snow(11)), snowDiff: !same(snow(11), snow(12)),
+ moteSame: same(mote(11), mote(11)), moteDiff: !same(mote(11), mote(12)),
+}));
+""", _LIBS)
+ for k, v in out.items():
+ assert v, k
+
+
+def test_tick_advances_every_material_in_every_field(probe):
+ """Everything that makes these three read as weather rather than as
+ geometry lives in `uTime` — the filaments travelling down a sheet, the
+ wander, the twinkle. One missed material is one frozen field."""
+ for k, r in probe["tick"].items():
+ assert r["at0"] == 0, (k, r)
+ assert r["n"] == 1, (k, r)
+ assert r["after"] == 4.25, (k, r)
+
+
+def test_none_of_the_three_adds_light(probe):
+ """The module's own argument, and the reason the light probe below is
+ a multiply rather than a lift: rain and snow SCATTER — they lower the
+ contrast of the ridge behind them — and a mote is a speck of matter,
+ not a lamp. Additive blending turns every one of them into a white
+ slab over a daylight sky at any strength worth having."""
+ for k, (normal, transparent, depth_write) in probe["blending"].items():
+ assert normal, f"{k} does not blend normally"
+ assert transparent and not depth_write, (k, transparent, depth_write)
+
+
+def test_the_whole_field_compiles_on_the_real_renderer():
+ """A custom shader that fails to compile is discarded with no error at
+ all — the effect is simply absent. Both scenes have to be checked:
+ asset mode builds an UNFOGGED scene, so `USE_FOG` is never defined and
+ the fog branch of every shader here is never compiled, and these veils
+ ship into fogged scenes."""
+ fogged = _SCENE.replace(
+ "__FOG__", "scene.fog = new THREE.FogExp2(0xc9d6e0, 0.004);")
+ code, out = compile_scene(fogged, _LIBS)
+ assert code == 0, out
+ assert '"custom_materials":3' in out.replace(" ", ""), out
+ assert "WARN" not in out, out
+ code, out = compile_scene(_SCENE.replace("__FOG__", ""), _LIBS)
+ assert code == 0, out
+ assert "WARN" not in out, out
+
+
+# --- the port's own laws ----------------------------------------------
+
+
+def test_every_material_is_assembled_by_the_shader_helper(probe):
+ """This host has NO post chain: ACES and the sRGB transfer happen in
+ the fragment tail, from the two chunks three appends to its own
+ shaders. A hand-built ShaderMaterial that skips them renders on a
+ different curve from every built-in beside it."""
+ assert probe["fromHelper"], "a veil material was not built by shader.js"
+ assert probe["outChunks"], (
+ "a veil fragment shader is missing tonemapping_fragment / "
+ "colorspace_fragment")
+
+
+def test_no_veil_is_a_wall_to_a_depth_or_shadow_pass(probe):
+ """GTAOPass rebuilds depth and normals through `scene.overrideMaterial`,
+ which is opaque: a stack of rain sheets is a stack of solid floors in
+ that buffer, occluding the ridge it hangs in front of. Every other
+ veil in this library (rain, godrays, watermist, waterfall, flock,
+ neon) is guarded; these three were not, which is a defect that only
+ appears the day the post chain lands."""
+ for k, (guarded, casts) in probe["guard"].items():
+ assert guarded, f"{k} is not kept out of override passes"
+ assert not casts, f"{k} casts a shadow"
+
+
+def test_a_veil_carries_the_light_of_the_scene_it_hangs_in(light):
+ """THE PORT'S LAW. An unlit pale card is the brightest thing in any
+ frame that is not daylight — measured, a moonlit rain curtain adding
+ +0.189 luminance at peaks of 0.523 over a scene whose mean was 0.170.
+ The probe answers with the irradiance where the field hangs,
+ normalised so the library's own day rig is 1.0."""
+ day = light["dayVeil"]
+ night = light["nightVeil"]
+ # Daylight is the calibration point: the whole corpus of daylight
+ # frames must look exactly as it did.
+ for c in day:
+ assert 0.85 <= c <= 1.25, day
+ # Moonlight is a different scene, and the veil has to know.
+ assert max(night) < 0.55 * min(day), (day, night)
+ # ... in the night's own blue, not in grey.
+ assert night[2] > night[0] * 1.3, night
+ # Snow and dust read the same probe.
+ assert max(light["nightSnow"]) < 0.55 * min(day), light["nightSnow"]
+ assert max(light["nightMote"]) < 0.7 * min(day), light["nightMote"]
+
+
+def test_a_lamp_pools_on_the_dust_standing_in_it(light):
+ """The half of the probe a hemisphere cannot give: dust in a lamp's
+ beam is the thing motes exist for, and a scene-wide average would
+ light the specks forty metres away exactly as brightly."""
+ near, far = light["lampMote"], light["farMote"]
+ assert near[0] > far[0] * 1.6, (near, far)
+ # A tungsten practical is warm, so the dust standing in it turns warm
+ # against the blue the same night leaves on the field across the
+ # valley — the ratio, not the channel, because the moonlight is still
+ # in both of them.
+ assert near[0] / near[2] > (far[0] / far[2]) * 1.8, (near, far)
+ # The field across the valley is left in the moonlight it stands in.
+ assert far[2] > far[0] * 1.3, far
+
+
+def test_a_scene_with_no_lights_leaves_the_veil_exactly_as_authored(light):
+ """An asset preview and the shader check both build a scene with no
+ lights in it. A probe that answered zero there would deliver an
+ invisible effect and a green test run."""
+ assert light["bareVeil"] == [1, 1, 1], light["bareVeil"]
+
+
+def test_an_untouched_default_takes_the_fog_hue_and_a_given_colour_does_not(
+ light):
+ """A veil the scene's own haze does not agree with reads as a card in
+ FRONT of the weather. The default takes the fog's hue at its own
+ lightness — taking its value as well would send the veil to black in
+ a night scene the light probe has already dimmed — and a colour the
+ caller passed is a statement that is left alone."""
+ night_h, night_s, night_l = light["nightVeilHsl"]
+ plain_h, _, plain_l = light["plainHsl"]
+ assert abs(night_h - light["fogHue"]) < 0.02, (night_h, light["fogHue"])
+ assert abs(night_h - plain_h) > 0.01, (night_h, plain_h)
+ # Its own lightness, to the round trip through HSL.
+ assert abs(night_l - plain_l) < 1e-6, (night_l, plain_l)
+ assert light["nightVeilHsl"][1] <= 0.30 + 1e-9, light["nightVeilHsl"]
+ for got, want in zip(light["givenColor"], light["wantGiven"], strict=True):
+ assert abs(got - want) < 1e-6, (light["givenColor"],
+ light["wantGiven"])
diff --git a/harness/tests/scene_runtime/lib/test_water.py b/harness/tests/scene_runtime/lib/test_water.py
new file mode 100644
index 00000000..a6acc4d2
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_water.py
@@ -0,0 +1,463 @@
+"""Water ships as the addon shader, a procedural normal map, and a REGRADE.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference test. Its
+geometry half survives intact: npm three ships no waternormals.jpg, so
+``makeWaterNormals()`` IS the waves, and it has to tile, stay wavy and
+stay deterministic or a fix round re-renders a different ocean.
+
+The shading half is OURS. The addon's own fragment tail hardcodes
+``rf0 = 0.3`` and adds a flat ``vec3(0.1)`` veil to the mirror, i.e. it
+has no Fresnel: measured on this harness's showcase pool (fx/out/water/
+before), the surface came back at mean_lum 0.732 looked steeply INTO and
+0.732 at a grazing angle — one pale value, the same milk at every angle,
+and at night a slab of mean_lum 0.40 lying in a frame whose mean was
+0.196. ``_regrade`` splices a physical Fresnel, a scene-lit body with a
+turbidity hue field, an additive glitter track and a distortion ceiling
+over that tail; ``_readScene`` then points the whole thing at the key
+light the scene actually has, at the first render. The tests below pin
+that as hard as they pin the wave map.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401
+
+_LIBS = ("water.js",)
+
+
+# A stub renderer is enough to drive `onBeforeRender`: everything the
+# addon touches on it is a setter or a no-op, and the scene sniff runs
+# BEFORE the mirror pass. This is what lets the auto-wiring be tested
+# off the GPU, in the same probe as everything else.
+_STUB_RENDERER = """
+const stubRenderer = () => ({
+ extensions: { has: () => true },
+ capabilities: { isWebGL2: true },
+ xr: { enabled: false },
+ shadowMap: { autoUpdate: true },
+ autoClear: true,
+ getRenderTarget: () => null,
+ setRenderTarget() {},
+ state: { buffers: { depth: { setMask() {} } }, viewport() {} },
+ clear() {}, render() {},
+});
+"""
+
+_PROBE = _STUB_RENDERER + """
+import * as THREE from 'three';
+import { makeOcean, makeWaterNormals } from './lib/water.js';
+
+// The normal map: tiling, wavy, deterministic.
+const size = 64;
+const t1 = makeWaterNormals(size), t2 = makeWaterNormals(size);
+const d = t1.image.data;
+let identical = true;
+for (let i = 0; i < d.length; i++) {
+ if (d[i] !== t2.image.data[i]) { identical = false; break; }
+}
+// Per-channel stats + seam vs interior adjacency deltas (R channel).
+let rSum = 0, r2Sum = 0, bMin = 255;
+let maxSeam = 0, maxInterior = 0;
+const px = (x, y) => d[(y * size + x) * 4];
+for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const r = px(x, y);
+ rSum += r; r2Sum += r * r;
+ bMin = Math.min(bMin, d[(y * size + x) * 4 + 2]);
+ if (x > 0) maxInterior = Math.max(maxInterior, Math.abs(r - px(x - 1, y)));
+ if (y > 0) maxInterior = Math.max(maxInterior, Math.abs(r - px(x, y - 1)));
+ }
+ maxSeam = Math.max(maxSeam, Math.abs(px(0, y) - px(size - 1, y)));
+}
+for (let x = 0; x < size; x++) {
+ maxSeam = Math.max(maxSeam, Math.abs(px(x, 0) - px(x, size - 1)));
+}
+const n = size * size;
+const rStd = Math.sqrt(r2Sum / n - (rSum / n) * (rSum / n));
+
+// The ocean mesh: graded defaults must reach the shader.
+const o = makeOcean(120, 80, {});
+const u = o.material.uniforms;
+o.geometry.computeBoundingBox();
+const bb = o.geometry.boundingBox;
+const t0 = u.time.value;
+o.userData.update(2.5);
+const tAfter = u.time.value;
+
+// sunDir passthrough: what the caller aims is what the shader gets.
+const dir = new THREE.Vector3(3, 4, 0);
+const o2 = makeOcean(10, 10, { sunDir: dir, rttSize: 128 });
+
+// Wave tiling vs plane extent: pool, pond, harbor, explicit override.
+const oPool = makeOcean(18, 14, { rttSize: 64 });
+const oPond = makeOcean(150, 150, { rttSize: 64 });
+const nPond = makeWaterNormals(32, { broadband: false });
+const nWide = makeWaterNormals(32, { broadband: true });
+let spectrumDiffers = false;
+for (let i = 0; i < nPond.image.data.length; i++) {
+ if (nPond.image.data[i] !== nWide.image.data[i]) {
+ spectrumDiffers = true; break;
+ }
+}
+const oHarbor = makeOcean(2800, 2800, { rttSize: 64 });
+const oForced = makeOcean(2800, 2800, { rttSize: 64, size: 5 });
+
+// The regrade, and the addon tail it replaced.
+const fs = o.material.fragmentShader;
+const oLegacy = makeOcean(20, 20, { rttSize: 64, legacyShader: true });
+
+console.log(JSON.stringify({
+ identical,
+ wraps: t1.wrapS === THREE.RepeatWrapping
+ && t1.wrapT === THREE.RepeatWrapping,
+ mipmapped: t1.generateMipmaps === true
+ && t1.minFilter === THREE.LinearMipmapLinearFilter,
+ aniso: t1.anisotropy,
+ rStd, bMin, maxSeam, maxInterior,
+ rotX: o.rotation.x,
+ time: t0, timeAfter: tAfter,
+ distortion: u.distortionScale.value,
+ waterColor: u.waterColor.value.getHex(),
+ sunLen: u.sunDirection.value.length(),
+ rtt: u.mirrorSampler.value.image.width,
+ spanX: bb.max.x - bb.min.x, spanY: bb.max.y - bb.min.y,
+ sun2Custom: [o2.material.uniforms.sunDirection.value.x,
+ o2.material.uniforms.sunDirection.value.y],
+ rtt2: o2.material.uniforms.mirrorSampler.value.image.width,
+ sizePool: oPool.material.uniforms.size.value,
+ sizePond: oPond.material.uniforms.size.value,
+ sizeHarbor: oHarbor.material.uniforms.size.value,
+ sizeForced: oForced.material.uniforms.size.value,
+ turbPool: oPool.material.uniforms.turbScale.value,
+ turbHarbor: oHarbor.material.uniforms.turbScale.value,
+ spectrumDiffers,
+ poolUsesNarrow: oPool.material.uniforms.normalSampler.value
+ .image.data[0] === makeWaterNormals(256,
+ { broadband: false }).image.data[0],
+ rf0: u.rf0.value,
+ glitterScale: u.glitterScale.value,
+ hasVeil: fs.indexOf('vec3( 0.1 ) + reflectionSample') >= 0,
+ hasFixedRf0: fs.indexOf('float rf0 = 0.3') >= 0,
+ declaresRf0: fs.indexOf('uniform float rf0') >= 0,
+ keepsToneMap: fs.indexOf('tonemapping_fragment') >= 0
+ && fs.indexOf('colorspace_fragment') >= 0,
+ gatedGlitter: fs.indexOf('reflectionSample * specularLight') >= 0,
+ legacyVeil: oLegacy.material.fragmentShader.indexOf(
+ 'vec3( 0.1 ) + reflectionSample') >= 0,
+ legacyExtras: oLegacy.material.uniforms.rf0 !== undefined,
+}));
+"""
+
+_SNIFF = _STUB_RENDERER + """
+import * as THREE from 'three';
+import { makeOcean } from './lib/water.js';
+
+// A night rig: the sun is BELOW the horizon, the moon is what casts, and
+// the hemisphere is a dim blue. Water built before the scene existed
+// must end up lit by the moon, not by the noon default it shipped with.
+const scene = new THREE.Scene();
+const moon = new THREE.DirectionalLight(0xb5c7e8, 2.2);
+// A moved TARGET: the light aims from its position at this, so a sniff
+// that read `position` alone would hand the glitter a direction the
+// shadows do not use.
+moon.position.set(-40, 60, 30);
+moon.target.position.set(0, 20, 0);
+scene.add(moon);
+scene.add(moon.target);
+const stray = new THREE.DirectionalLight(0xff0000, 0.2);
+stray.position.set(10, 1, 0);
+scene.add(stray);
+const hemi = new THREE.HemisphereLight(0x3f5378, 0x2a2a33, 1.0);
+scene.add(hemi);
+scene.fog = new THREE.FogExp2(0x0b0f1a, 0.0035);
+
+const auto = makeOcean(40, 40, { rttSize: 64 });
+const before = auto.material.uniforms.sunDirection.value.clone();
+const pinnedDir = new THREE.Vector3(1, 0, 0);
+const pinned = makeOcean(40, 40, {
+ rttSize: 64, sunDir: pinnedDir, sunColor: 0x00ff00, ambient: 0x101010 });
+
+const r = stubRenderer(), cam = new THREE.PerspectiveCamera();
+scene.updateMatrixWorld(true); // what a renderer does before the frame
+cam.position.set(0, 10, 30); cam.lookAt(0, 0, 0); cam.updateMatrixWorld();
+auto.updateMatrixWorld(); pinned.updateMatrixWorld();
+auto.onBeforeRender(r, scene, cam);
+pinned.onBeforeRender(r, scene, cam);
+// a second frame must not re-sniff (and must not throw)
+auto.onBeforeRender(r, scene, cam);
+
+const ua = auto.material.uniforms, up = pinned.material.uniforms;
+const moonDir = moon.position.clone().sub(moon.target.position).normalize();
+console.log(JSON.stringify({
+ beforeY: before.y,
+ autoDir: [ua.sunDirection.value.x, ua.sunDirection.value.y,
+ ua.sunDirection.value.z],
+ moonDir: [moonDir.x, moonDir.y, moonDir.z],
+ autoSun: [ua.sunColor.value.r, ua.sunColor.value.g, ua.sunColor.value.b],
+ moonColor: [moon.color.r, moon.color.g, moon.color.b],
+ autoKey: [ua.keyColor.value.r, ua.keyColor.value.g, ua.keyColor.value.b],
+ autoAmb: [ua.ambientColor.value.r, ua.ambientColor.value.g,
+ ua.ambientColor.value.b],
+ hemiCol: [hemi.color.r, hemi.color.g, hemi.color.b],
+ mirrorType: ua.mirrorSampler.value.type,
+ halfFloat: THREE.HalfFloatType,
+ pinnedDir: [up.sunDirection.value.x, up.sunDirection.value.y,
+ up.sunDirection.value.z],
+ pinnedSun: [up.sunColor.value.r, up.sunColor.value.g, up.sunColor.value.b],
+ pinnedAmb: [up.ambientColor.value.r, up.ambientColor.value.g,
+ up.ambientColor.value.b],
+}));
+"""
+
+# One ocean, one lit bank, real fog: the whole `lights: true` +
+# shadowmap + fog permutation of the regraded program, on the GPU.
+_SCENE = """
+import * as THREE from 'three';
+import { makeOcean } from './lib/water.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 8, 20] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ const sun = new THREE.DirectionalLight(0xfff0d8, 5.4);
+ sun.position.set(-40, 40, -28);
+ sun.castShadow = true;
+ scene.add(sun);
+ scene.add(new THREE.HemisphereLight(0x9db8e8, 0x8a7f6a, 1.4));
+ const kerb = new THREE.Mesh(
+ new THREE.BoxGeometry(24, 1.2, 2),
+ new THREE.MeshStandardMaterial({ color: 0x8d8578, roughness: 0.86 }));
+ kerb.position.set(0, 0.6, -9);
+ kerb.castShadow = kerb.receiveShadow = true;
+ scene.add(kerb);
+ const sea = makeOcean(18, 14, { sunDir: sun.position.clone().normalize() });
+ sea.position.y = 0.95;
+ scene.add(sea);
+ const cameras = [
+ { name: 'graze', position: [5, 2.2, 7], lookAt: [0, 1.4, 0], fov: 40 },
+ ];
+ return { scene, cameras, update(t) { sea.userData.update(t); } };
+}
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch, shared by every test that reads it."""
+ return measure(_PROBE, _LIBS)
+
+
[email protected](scope="module")
+def sniff() -> dict:
+ """One node launch of the first-render scene sniff."""
+ return measure(_SNIFF, _LIBS)
+
+
+def test_normal_map_is_wavy_tiling_and_deterministic(probe) -> None:
+ """No image assets ship with npm three, so this synthesized map IS
+ the waves: a flat map gives a mirror-still ocean, a seam prints a
+ grid across it, and non-determinism breaks fix-round re-renders."""
+ m = probe
+ assert m["identical"], "two builds of the normal map differ"
+ assert m["wraps"], "not RepeatWrapping"
+ assert m["mipmapped"], (
+ "wave normals unfiltered — a DataTexture defaults to Nearest "
+ "with no mipmaps and dithers across any water seen at distance")
+ assert m["aniso"] >= 8, m["aniso"]
+ assert m["rStd"] > 8, f"normal map nearly flat: rStd {m['rStd']}"
+ assert m["bMin"] > 127, f"a normal points below horizon: {m['bMin']}"
+ assert m["maxSeam"] <= m["maxInterior"] * 1.5 + 2, (
+ f"wrap seam ({m['maxSeam']}) jumps harder than the interior "
+ f"({m['maxInterior']}) — the ocean would show tile lines")
+
+
+def test_ocean_ships_the_graded_defaults(probe) -> None:
+ """Graded defaults (rtt 512, distortion 2.8, colour 0x0e3f5c, time
+ frozen mid-wave, plane flat) must reach the shader — dropping one
+ silently re-runs the experiment on every scene.
+
+ rtt was 256 until the reference's 2026-08-04 gallery audit found the
+ mirror tearing into stair-stepped blocks in 9 frames across six
+ scenes; it is one extra scene pass and still the cheapest thing in
+ the frame.
+ """
+ m = probe
+ assert abs(m["rotX"] + 1.5707963) < 1e-6, f"not flat: {m['rotX']}"
+ assert 6.5 < m["time"] < 7.6, f"time not frozen mid-wave: {m['time']}"
+ assert abs(m["distortion"] - 2.8) < 1e-9, m["distortion"]
+ assert m["waterColor"] == 0x0E3F5C, hex(m["waterColor"])
+ assert m["rtt"] == 512, f"rtt default drifted: {m['rtt']}"
+ assert m["rtt2"] == 128, "rttSize override ignored"
+ assert (m["spanX"], m["spanY"]) == (120, 80), "w/d not honored"
+
+
+def test_wave_tiling_scales_with_the_plane(probe) -> None:
+ """One wave period is ~103/size metres, so a size graded on a pond
+ tiles hundreds of times across a harbor and moires into radial
+ stripes. Measured by the reference on a 2800 m harbor at golden
+ hour: 1.2 unusable, 0.70 striped, 0.44 clean.
+
+ The law used to be capped at 6, which froze it for every plane under
+ 206 m — an 18 m pool got ONE wave period across the whole basin, an
+ ocean swell in a bathtub. Measured here on the showcase pool
+ (fx/out/water/sz*): ripple local contrast 1.22 at size 6, 1.73 at 14,
+ 2.51 at 30, 3.11 at 68 — and 68 speckles the far band into per-pixel
+ sparkle at a 1024 px grazing close-up. Cap 30, law unchanged.
+ """
+ m = probe
+ assert m["sizePool"] == 30, (
+ f"an 18 m pool got wave size {m['sizePool']} — the cap is what "
+ "keeps a basin from carrying one 17 m swell")
+ assert abs(m["sizePond"] - 8.24) < 0.05, (
+ f"a 150 m pond got {m['sizePond']}, not the law's extent/12")
+ assert abs(m["sizeHarbor"] - 0.441) < 0.01, (
+ f"2800 m harbor wave size {m['sizeHarbor']} — measured clean at "
+ "0.44, striped from 0.70 up")
+ assert m["sizeForced"] == 5, "an explicit size must win over the law"
+
+
+def test_the_turbidity_field_is_sized_in_metres_not_texels(probe) -> None:
+ """The body's hue field is a slow read of the wave map, and its
+ period has to be METRES of the plane. Pinned to a constant it was
+ the same texel everywhere on a small pool and the whole basin came
+ out one colour — the exact flatness the term exists to break."""
+ m = probe
+ assert abs(m["turbPool"] - 8.0) < 1e-6, (
+ f"an 18 m pool's turbidity period is {m['turbPool']} m — under "
+ "the 8 m floor the colour field competes with the waves")
+ assert abs(m["turbHarbor"] - 1120.0) < 1e-6, m["turbHarbor"]
+
+
+def test_wide_water_gets_the_broadband_wave_spectrum(probe) -> None:
+ """Eight pure tones read as corduroy banding at a grazing angle —
+ it is the periodicity of the SET that shows, and no wave size hides
+ it. Spreading 28 directions at 1/f^2 kills it but calms the
+ surface, so only water wide enough to be seen edge-on pays for it."""
+ m = probe
+ assert m["spectrumDiffers"], (
+ "broadband:true returned the same normal map — the option is "
+ "not reaching the wave table")
+ assert m["poolUsesNarrow"], "a pool paid for the broadband spectrum"
+
+
+def test_update_drives_the_wave_phase_and_sundir_reaches_the_shader(
+ probe) -> None:
+ """tick animates water ONLY through userData.update(t); and the
+ glitter track must sit where the caller's key light is, or sun and
+ specular disagree on screen."""
+ m = probe
+ assert abs(m["timeAfter"] - (m["time"] + 2.5)) < 1e-9, (
+ f"update(t) did not advance the phase: {m['time']} -> "
+ f"{m['timeAfter']}")
+ assert abs(m["sunLen"] - 1) < 1e-6, "default sunDir not normalized"
+ x, y = m["sun2Custom"]
+ assert abs(x - 0.6) < 1e-6 and abs(y - 0.8) < 1e-6, (
+ f"passed sunDir was not normalized through: {m['sun2Custom']}")
+
+
+def test_the_regrade_replaces_the_addon_tail(probe) -> None:
+ """The addon's tail is what makes stock Water read as milk: a
+ hardcoded rf0 = 0.3 (30% mirror looked straight down into), a flat
+ +0.1 veil over the reflection, and a specular multiplied BY the
+ reflection so a sun track cannot appear on dark water. Measured on
+ the showcase pool, that tail gave mean_lum 0.732 steeply AND 0.732
+ at grazing — one value at every angle, which is no Fresnel at all.
+ """
+ m = probe
+ assert not m["hasFixedRf0"], "the addon's rf0 = 0.3 survived"
+ assert not m["hasVeil"], "the flat +0.1 milk veil survived"
+ assert not m["gatedGlitter"], (
+ "the specular is still gated behind the mirror sample")
+ assert m["declaresRf0"], "rf0 is no longer a uniform"
+ assert abs(m["rf0"] - 0.02) < 1e-9, (
+ f"F0 {m['rf0']} is not dielectric water")
+ assert m["glitterScale"] == 1
+
+
+def test_the_regrade_keeps_our_pipelines_fragment_tail(probe) -> None:
+ """We have no post chain: ACES and the sRGB encode happen in the
+ fragment tail, so a splice that dropped three's two closing chunks
+ would render the water dark next to every built-in material."""
+ assert probe["keepsToneMap"], "tonemapping/colorspace chunks lost"
+
+
+def test_legacy_shader_opts_all_the_way_out(probe) -> None:
+ """An escape hatch has to be a real one: `legacyShader` must ship the
+ addon's own tail, uniforms and all, for a scene graded against it."""
+ m = probe
+ assert m["legacyVeil"], "legacyShader did not restore the addon tail"
+ assert not m["legacyExtras"], (
+ "legacyShader still declared the regrade's uniforms")
+
+
+def test_first_render_points_the_water_at_the_scenes_own_key(sniff) -> None:
+ """Water is built before the scene exists, so its light is a guess
+ until the first frame. Left as the shipped guess, a night pool
+ glitters for a noon sun in a colour nothing else in the frame is lit
+ by — and it picks the BRIGHTEST directional, not the first one.
+
+ The probe's moon aims at a MOVED target, so a sniff that read the
+ light's `position` alone fails here.
+ """
+ m = sniff
+ assert m["beforeY"] > 0.5, "the shipped default is not the day axis"
+ for got, want in zip(m["autoDir"], m["moonDir"], strict=True):
+ assert abs(got - want) < 1e-6, (
+ f"key direction {m['autoDir']} is not the moon's "
+ f"{m['moonDir']}")
+ # hue only: the glitter lobes are graded values, not radiometry, so
+ # they must be tinted by the key and never scaled by its watts.
+ peak = max(m["moonColor"])
+ for got, want in zip(m["autoSun"], m["moonColor"], strict=True):
+ assert abs(got - want / peak) < 1e-6, (
+ f"glitter colour {m['autoSun']} is not the moon's hue")
+ assert max(m["autoSun"]) == pytest.approx(1.0, abs=1e-6)
+
+
+def test_first_render_reads_irradiance_the_way_a_standard_material_does(
+ sniff) -> None:
+ """The body is a Lambert term, so it has to sit on the same 1/PI
+ scale as every MeshStandardMaterial around it — otherwise the water
+ is lit by a different sun than the bank it touches."""
+ m = sniff
+ inv_pi = 1.0 / 3.141592653589793
+ for got, want in zip(m["autoKey"], m["moonColor"], strict=True):
+ assert abs(got - want * 2.2 * inv_pi) < 1e-5, (
+ f"key irradiance {m['autoKey']} is not colour*intensity/PI")
+ for got, want in zip(m["autoAmb"], m["hemiCol"], strict=True):
+ assert abs(got - want * 1.0 * inv_pi) < 1e-5, (
+ f"ambient {m['autoAmb']} is not the hemisphere's sky/PI")
+
+
+def test_the_mirror_target_goes_half_float(sniff) -> None:
+ """The mirror target is 8-bit LINEAR — three turns tone mapping and
+ the sRGB encode off when rendering to a non-sRGB target — so the
+ bottom of its range quantises to a handful of steps and a night sky
+ at ~0.002 linear reflects as two flat bands. Half-float costs two
+ bytes a texel on ONE 512 px target."""
+ m = sniff
+ assert m["mirrorType"] == m["halfFloat"], (
+ f"mirror target type {m['mirrorType']} is not HalfFloat")
+
+
+def test_pinned_options_are_never_overwritten_by_the_sniff(sniff) -> None:
+ """A caller who names a sun direction, a sun colour or an ambient has
+ made a decision; the first frame must not quietly undo it."""
+ m = sniff
+ assert m["pinnedDir"] == [1, 0, 0], m["pinnedDir"]
+ assert m["pinnedSun"] == [0, 1, 0], m["pinnedSun"]
+ r, g, b = m["pinnedAmb"]
+ assert r == g == b and 0 < r < 0.02, m["pinnedAmb"]
+
+
+def test_every_regraded_program_compiles_on_the_gpu() -> None:
+ """The regrade is a string splice into an addon shader: it either
+ compiles with `lights: true`, the shadow-mask chunks and fog, or the
+ pool renders as a black hole. Nothing but a real compile proves it.
+ """
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_waterfall.py b/harness/tests/scene_runtime/lib/test_waterfall.py
new file mode 100644
index 00000000..3bbdcff6
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_waterfall.py
@@ -0,0 +1,352 @@
+"""A waterfall has to read as one from angles nobody framed for it.
+
+Every model attempt at this brief built a flat plane, which is a line
+edge-on; the reference build that convinced was the one with a swept
+closed section, a projectile path, and threads that accelerate. Those
+four properties are the reference's, ported 2026-09-01 from
+scene_multifile_graphics (tests/test_waterfall_lib.py), and they are held
+here as they stood.
+
+THE PORT'S OWN LAWS — each one a frame rendered on our host under
+fx/out/waterfall/, looked at, and measured against the same frame with
+the reference module in place:
+
+1. A FALL IS NOT A WHITE CURTAIN. Every pixel of the sheet was mixed
+ toward one near-white value: measured on the close camera, mean
+ saturation 0.099 with 24.2% of the sheet's pixels above 0.85
+ luminance. Everything in the shader now rides one AERATION ramp —
+ coherent green-blue glass at the lip, torn spray by the foot — which
+ takes that to 0.118 saturation and 0.14% near-white, with the lip
+ reading as water rather than as frosted glass.
+
+2. THE LIGHT IS THE SCENE'S. All three materials are unlit, so every
+ photon in them is a decision, and the reference's were daylight
+ constants. Measured on this harness's night rig, the old sheet came
+ back at luminance 0.344 over a frame whose mean was 0.168 — a sheet
+ of white plastic hanging in the dark. It reads the key light, the
+ hemisphere fill and the fog at the first render (0.174 over 0.144
+ now), and `keepOutOfDepthPasses` has already claimed `onBeforeRender`
+ there, so the adoption CHAINS onto that guard rather than replacing
+ it.
+
+3. THE PLUNGE POOL IS WATER, NOT MILK. The disc mixed 85% of its noise
+ straight to foam over its whole radius — a lid of grey milk on the
+ dirt, with the deep colour never appearing at all. Foam now belongs
+ to the boil and travels outward as streaks in (angle, radius - time).
+"""
+
+from __future__ import annotations
+
+from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "waterfall.js")
+
+# A scene the way `sunRig` builds one: a key directional light, a
+# hemisphere fill and fog. `adoptSceneLight` runs off `onBeforeRender`,
+# which a probe can call directly — no GPU needed to prove what it read.
+# The guard `keepOutOfDepthPasses` installed runs FIRST in that chain and
+# touches the geometry, so the call carries the real geometry and
+# material three would hand it.
+_LIT_SCENE = """
+function litScene(THREE, opts) {
+ const o = opts || {};
+ const scene = new THREE.Scene();
+ const key = new THREE.DirectionalLight(o.sunHex || 0xfff0d8,
+ o.sunI === undefined ? 5.4 : o.sunI);
+ // Direction is position -> target, so a light at +y+x shines DOWN and
+ // the adopted uSun must point back up at it.
+ key.position.set(30, 40, -10);
+ scene.add(key);
+ const hemi = new THREE.HemisphereLight(o.skyHex || 0x9db8e8, 0x8a7f6a,
+ o.fillI === undefined ? 1.4 : o.fillI);
+ scene.add(hemi);
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ return scene;
+}
+const adopt = (g, scene) => {
+ const m = g.getObjectByName('Sheet');
+ m.onBeforeRender(null, scene, null, m.geometry, m.material);
+ return m.material.uniforms;
+};
+const rgb = (c) => [+c.r.toFixed(4), +c.g.toFixed(4), +c.b.toFixed(4)];
+const lum = (c) => +(0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b).toFixed(4);
+"""
+
+
+def test_the_sheet_is_a_body_not_a_plane():
+ """A flat sheet vanishes edge-on: the section must have real depth,
+ and it must follow a parabola rather than a straight drop."""
+ out = measure("""
+import { makeWaterfall } from './lib/waterfall.js';
+const g = makeWaterfall({ height: 8, width: 3.2 });
+const sheet = g.getObjectByName('Sheet');
+const p = sheet.geometry.attributes.position.array;
+let minX = 1e9, maxX = -1e9, minY = 1e9, maxY = -1e9, minZ = 1e9, maxZ = -1e9;
+// The mid-height row tells a parabola from a ramp: half the drop is
+// reached well before half the throw.
+let zAtHalfDrop = 0, bestDy = 1e9;
+for (let i = 0; i < p.length; i += 3) {
+ minX = Math.min(minX, p[i]); maxX = Math.max(maxX, p[i]);
+ minY = Math.min(minY, p[i + 1]); maxY = Math.max(maxY, p[i + 1]);
+ minZ = Math.min(minZ, p[i + 2]); maxZ = Math.max(maxZ, p[i + 2]);
+ const dy = Math.abs(p[i + 1] - 4.0); // nearest sample to half drop
+ if (dy < bestDy) { bestDy = dy; zAtHalfDrop = p[i + 2]; }
+}
+console.log(JSON.stringify({
+ width: +(maxX - minX).toFixed(2),
+ drop: +(maxY - minY).toFixed(2),
+ depth: +(maxZ - minZ).toFixed(2),
+ throwTotal: +maxZ.toFixed(2),
+ zAtHalfDrop: +zAtHalfDrop.toFixed(2),
+ names: g.children.map((c) => c.name).sort(),
+ hasTick: typeof g.userData.tick === 'function',
+}));
+""", _LIBS)
+ assert out["drop"] == 8.0 and 3.0 <= out["width"] <= 3.3
+ # Depth is the whole point: a plane would measure ~0 here.
+ assert out["depth"] > 1.2, out
+ # Free fall: half the height is gone by ~70% of the way down, so the
+ # sheet is still well short of the landing point there.
+ assert out["zAtHalfDrop"] < out["throwTotal"] * 0.75, out
+ assert out["names"] == ["Mist", "PlungePool", "Sheet"]
+ assert out["hasTick"]
+
+
+def test_the_mist_keeps_position_at_the_origin():
+ """GTAOPass redraws with an override material that ignores custom
+ vertex shaders, so a billboard that keeps its quad in `position`
+ burns a black rectangle at the world origin."""
+ out = measure("""
+import { makeWaterfall } from './lib/waterfall.js';
+const mist = makeWaterfall({ mist: 40 }).getObjectByName('Mist');
+const pos = Array.from(mist.geometry.attributes.position.array);
+console.log(JSON.stringify({
+ posAllZero: pos.every((v) => v === 0),
+ hasCorner: !!mist.geometry.attributes.aCorner,
+ instances: mist.geometry.instanceCount,
+ seeded: mist.geometry.attributes.iSeed.count,
+}));
+""", _LIBS)
+ assert out["posAllZero"] and out["hasCorner"]
+ assert out["instances"] == 40 and out["seeded"] == 40
+
+
+def test_two_waterfalls_with_one_seed_are_identical():
+ """Determinism is the contract for every shipped factory: a re-run
+ that reshuffles the mist is a re-run nobody can compare against."""
+ out = measure("""
+import { makeWaterfall } from './lib/waterfall.js';
+const seedOf = (s) => Array.from(
+ makeWaterfall({ seed: s, mist: 24 })
+ .getObjectByName('Mist').geometry.attributes.iSeed.array);
+const a = seedOf(5), b = seedOf(5), c = seedOf(9);
+console.log(JSON.stringify({
+ same: JSON.stringify(a) === JSON.stringify(b),
+ differs: JSON.stringify(a) !== JSON.stringify(c),
+}));
+""", _LIBS)
+ assert out["same"] and out["differs"]
+
+
+def test_tick_advances_every_material_in_the_group():
+ out = measure("""
+import { makeWaterfall } from './lib/waterfall.js';
+const g = makeWaterfall({ mist: 12 });
+g.userData.tick(2.5);
+const times = [];
+g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.uniforms && m.uniforms.uTime) times.push(m.uniforms.uTime.value);
+ }
+});
+console.log(JSON.stringify({ times }));
+""", _LIBS)
+ assert out["times"] and all(v == 2.5 for v in out["times"])
+
+
+def test_the_sheet_normal_is_world_space_like_everything_it_meets():
+ """three's `normalMatrix` is the inverse transpose of the modelVIEW
+ matrix, so it yields a VIEW-space normal. Both consumers here —
+ astraFresnel-style rim work and astraFacing for the silhouette fade —
+ are handed `cameraPosition - vW`, which is world space. Mixing the
+ two keys the rim and the fade to where the camera is POINTING rather
+ than to how the sheet is turned, so they swim as the camera orbits a
+ stationary waterfall."""
+ out = measure(r"""
+import { makeWaterfall } from './lib/waterfall.js';
+const g = makeWaterfall({ height: 6, width: 3, seed: 2 });
+const mats = [];
+g.traverse((o) => { if (o.material && o.material.vertexShader) mats.push(o.material); });
+const bad = mats.filter((m) =>
+ /normalMatrix\s*\*\s*normal/.test(m.vertexShader)
+ && /cameraPosition/.test(m.fragmentShader));
+console.log(JSON.stringify({
+ materials: mats.length,
+ mixedSpaces: bad.length,
+ worldNormals: mats.filter((m) =>
+ /mat3\(modelMatrix\)\s*\*\s*normal/.test(m.vertexShader)).length,
+}));
+""", _LIBS)
+ assert out["materials"] >= 1
+ assert out["mixedSpaces"] == 0, (
+ "a view-space normal is being dotted with a world-space view "
+ "vector")
+ assert out["worldNormals"] >= 1
+
+
+def test_the_light_is_the_scene_s_and_one_bundle_feeds_all_three():
+ """LAW 2. The sheet, the pool and the mist must agree about where
+ the sun is and what colour it is — three unlit materials with three
+ private sets of daylight constants are three separate objects
+ standing in the same place — so they share ONE uniform bundle, and
+ one adoption off the sheet updates every one of them."""
+ out = measure(_LIT_SCENE + """
+import * as THREE from 'three';
+import { makeWaterfall } from './lib/waterfall.js';
+const g = makeWaterfall({ mist: 8 });
+const before = rgb(g.getObjectByName('Sheet').material.uniforms.uSunCol.value);
+const u = adopt(g, litScene(THREE, { sunHex: 0xff9060 }));
+const pool = g.getObjectByName('PlungePool').material.uniforms;
+const mist = g.getObjectByName('Mist').material.uniforms;
+console.log(JSON.stringify({
+ before,
+ sun: [+u.uSun.value.x.toFixed(3), +u.uSun.value.y.toFixed(3),
+ +u.uSun.value.z.toFixed(3)],
+ sunCol: rgb(u.uSunCol.value),
+ // One bundle: the pool's and the mist's uniforms are the SAME objects.
+ poolShares: pool.uSunCol === u.uSunCol && pool.uSun === u.uSun,
+ mistShares: mist.uSunCol === u.uSunCol && mist.uAmb === u.uAmb,
+ // ... and every material still has its OWN uTime, or one tick would
+ // be three writes to one number.
+ ownTime: u.uTime !== pool.uTime && pool.uTime !== mist.uTime,
+}));
+""", _LIBS)
+ # The key is up and to the +x/-z side; the adopted vector points at it.
+ assert out["sun"][1] > 0.7 and out["sun"][0] > 0.4 and out["sun"][2] < 0
+ # A warm key really arrives: red climbs away from green and blue.
+ assert out["sunCol"][0] > out["sunCol"][2] * 2.5, out
+ assert out["sunCol"] != out["before"]
+ assert out["poolShares"] and out["mistShares"] and out["ownTime"], out
+
+
+def test_a_caller_who_pins_the_light_keeps_it():
+ """Adoption is a default, not a policy: a scene that hands the fall
+ its own key must not have it taken away at the first render."""
+ out = measure(_LIT_SCENE + """
+import * as THREE from 'three';
+import { makeWaterfall } from './lib/waterfall.js';
+const g = makeWaterfall({
+ mist: 0, sunDir: new THREE.Vector3(0, 1, 0), sunColor: 0x00ff00,
+ sky: 0xff0000, ambient: 0x0000ff,
+});
+const u = adopt(g, litScene(THREE));
+console.log(JSON.stringify({
+ sun: [+u.uSun.value.x.toFixed(3), +u.uSun.value.y.toFixed(3)],
+ sunCol: rgb(u.uSunCol.value),
+ sky: rgb(u.uSky.value),
+ amb: rgb(u.uAmb.value),
+}));
+""", _LIBS)
+ assert out["sun"] == [0.0, 1.0]
+ assert out["sunCol"][1] > 0.9 and out["sunCol"][0] < 0.01
+ assert out["sky"][0] > 0.9 and out["amb"][2] > 0.9
+
+
+def test_a_moonlit_fall_is_not_a_daylight_one():
+ """LAW 2, the half a render caught: what is adopted is the key's
+ strength RELATIVE to daylight, so the night rig's 2.2 moon arrives
+ as ~0.41 of the 5.4 sun instead of as the same white sheet."""
+ out = measure(_LIT_SCENE + """
+import * as THREE from 'three';
+import { makeWaterfall } from './lib/waterfall.js';
+const day = adopt(makeWaterfall({ mist: 0 }), litScene(THREE));
+const dayL = lum(day.uSunCol.value), dayA = lum(day.uAmb.value);
+const night = adopt(makeWaterfall({ mist: 0 }), litScene(THREE, {
+ sunHex: 0xb5c7e8, sunI: 2.2, skyHex: 0x3f5378, fillI: 1.0 }));
+console.log(JSON.stringify({
+ dayKey: dayL, nightKey: lum(night.uSunCol.value),
+ dayAmb: dayA, nightAmb: lum(night.uAmb.value),
+}));
+""", _LIBS)
+ assert out["nightKey"] < out["dayKey"] * 0.5, out
+ assert out["nightAmb"] < out["dayAmb"] * 0.5, out
+ # Dark, but never off: an unlit material at zero is a black hole.
+ assert out["nightKey"] > 0.02 and out["nightAmb"] > 0.005, out
+
+
+def test_adopting_the_light_does_not_disarm_the_override_guard():
+ """`keepOutOfDepthPasses` guards the sheet by owning
+ `onBeforeRender`, and `adoptSceneLight` wants the same hook: the
+ adoption CHAINS. Replacing it would put a double-sided transparent
+ shell back into the ambient-occlusion pass as a solid wall — 50/255
+ of darkening on ground it never touched, which is the measurement
+ that put the guard there in the first place."""
+ out = measure(_LIT_SCENE + """
+import * as THREE from 'three';
+import { makeWaterfall } from './lib/waterfall.js';
+const g = makeWaterfall({ mist: 4 });
+const scene = litScene(THREE);
+const sheet = g.getObjectByName('Sheet');
+const own = sheet.material;
+const override = new THREE.MeshDepthMaterial();
+// three's own call shape, once with the mesh's material and once with
+// the override an AO or shadow pass substitutes.
+sheet.onBeforeRender(null, scene, null, sheet.geometry, own);
+const drawnNormally = sheet.geometry.drawRange.count;
+sheet.onBeforeRender(null, scene, null, sheet.geometry, override);
+const drawnInOverride = sheet.geometry.drawRange.count;
+sheet.onAfterRender(null, scene, null, sheet.geometry);
+console.log(JSON.stringify({
+ drawnNormally: drawnNormally === Infinity ? -1 : drawnNormally,
+ drawnInOverride,
+ restored: sheet.geometry.drawRange.count === Infinity,
+ casts: sheet.castShadow,
+ adopted: +sheet.material.uniforms.uSun.value.y.toFixed(3),
+}));
+""", _LIBS)
+ assert out["drawnNormally"] == -1 # Infinity: drawn in full
+ assert out["drawnInOverride"] == 0 # and skipped by the AO pass
+ assert out["restored"] and not out["casts"]
+ assert out["adopted"] > 0.7 # the chain still adopted
+
+
+_SCENE = """
+import * as THREE from 'three';
+import { tickShaders } from './lib/shader.js';
+import { makeWaterfall } from './lib/waterfall.js';
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ // Fogged, because the mist is one custom shader on the RAW route and
+ // the fog chunk is exactly what a hand-written shader forgets.
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ const key = new THREE.DirectionalLight(0xfff0d8, 5.4);
+ key.position.set(30, 40, -10);
+ scene.add(key);
+ scene.add(new THREE.HemisphereLight(0x9db8e8, 0x8a7f6a, 1.4));
+ const fall = makeWaterfall({ height: 8, width: 3.2, seed: 3, mist: 40 });
+ scene.add(fall);
+ // A camera, because the host reports a scene with none as not booted
+ // and never reaches the compile stage at all.
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [9, 4, 12], lookAt: [0, 3, 0],
+ fov: 45 }],
+ update(t) { tickShaders(scene, t); fall.userData.tick(t); },
+ };
+}
+"""
+
+
+def test_the_whole_waterfall_compiles_on_our_gpu():
+ """Three custom shaders, one of them on the raw route with its own
+ billboard projection — the depth, fog and tone-map chunks are
+ hand-carried there, and only the GPU can say whether that was done
+ right. The raw route also gets no GLSL_UTIL, which is why the mist's
+ value noise is written out inside it."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "every program compiled" in out
+ # Sheet, pool and mist: three, or one of them silently never built.
+ assert '"custom_materials":3' in out.replace(" ", ""), out
+ assert "WARN" not in out, out
diff --git a/harness/tests/scene_runtime/lib/test_watermist.py b/harness/tests/scene_runtime/lib/test_watermist.py
new file mode 100644
index 00000000..da401810
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_watermist.py
@@ -0,0 +1,525 @@
+"""watermist.js: the air over moving water, and the drops it throws.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_watermist_lib.py). Their laws are kept as they stood — mist has
+to read as AIR and spray as WATER IN FLIGHT, and both fail the same way: the
+mist becomes a stack of visible cards and the spray a static puff of dots.
+Many faint overlapping cards no wider than the bank is deep, a launch solved
+from gravity rather than animated by hand, one seed one field. Their GPU
+compile runs through `_probe.compile_scene`, which stages the fixture as a
+workspace `src/scene.js` — and this module needs a real scene anyway,
+because both shaders read `fogColor` behind `#ifdef USE_FOG` and that
+branch only exists in a fogged one.
+
+THE PORT'S OWN LAWS — each one a frame rendered on our host under
+fx/out/watermist/, looked at, and measured against a control render of the
+same weir with the mist group removed (fx/out/watermist/nomist):
+
+1. MIST IS NOT A COLOUR, IT IS AN ALBEDO TIMES WHAT REACHES IT. Both
+ materials emitted a fixed pale blue-grey. In daylight that is nearly
+ right by luck; at night it made the bank a GLOWING white slab over a
+ black weir and the droplets white confetti (close view mean_lum 0.197
+ against a 0.124 base scene). `uColor` is now multiplied by the scene's
+ own `fogColor` — which IS the skylight at ground level — plus a small
+ floor, so the same call reads pale at noon and a dim blue-grey at night
+ with nothing said by the caller: 0.130 close, dark_frac 0.10, nothing
+ blown. A scene with no fog keeps the old look through the white
+ fallback the `#ifdef` leaves behind.
+
+2. IT SCATTERS THE SUN FORWARD. Nothing in the module knew where the light
+ was. The lobe is Henyey-Greenstein (g = 0.55) and not a power of the
+ cosine, because the power form only fires within ~30 degrees of the sun:
+ with the showcase's own rig (mu = +0.64 mid, +0.68 close) `pow(mu, 3)`
+ moved the veil 2% against a control with the sun mirrored across the
+ scene, which is no coupling at all. The lobe moves it 7.7% brighter and
+ 20% warmer (R-B 2.82 against 2.36) at the same angles.
+
+3. NO STRAIGHT EDGE, NO LID. The card envelope faded late (0.62 of the
+ half-height), so on a camera near the top of the bank every card's upper
+ rim landed in one screen band — visible as horizontal ribbons right
+ across the night frame, which is the one failure this effect's own
+ header says must never happen. The fade starts at 0.16 now, and the
+ per-card alpha constant went 9 -> 16 to keep `density` meaning the same
+ thickness (veil contribution over the wall 5.3/255 against the old
+ 5.9). The top edge's steepest row-to-row step fell 18.7 -> 15.3.
+
+4. STRUCTURE HAS TO BE METRES ACROSS TO SURVIVE THE RAY. A view ray
+ crosses ~85 cards spread over metres of xz, so the integral averages any
+ pattern shorter than itself down to its mean: the wisp scale lives
+ inside one card and vanishes from the sum, and the first render came out
+ a flat-topped slab. A second, coarse octave of thickness carries most
+ of the swing now — along-bank strength variation 0.203 -> 0.260.
+
+5. DITHER PER CARD, NOT PER FRAGMENT. A ramp this smooth over this many
+ pixels bands in 8 bits and a dozen cards stack the SAME ramp. A flat
+ 0.004 of alpha put a coarse speckle across the whole bank, because a
+ dozen independent draws sum as a random walk; the amplitude is divided
+ by the root of the stack depth.
+"""
+
+from __future__ import annotations
+
+from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "watermist.js")
+
+# The scene our check_shaders.mjs boots. Fog, because both shaders read
+# `fogColor` under `#ifdef USE_FOG` and that branch is only compiled when
+# the scene has some; a camera, because a scene with none is reported as
+# not booted and never reaches the compile stage at all.
+_SCENE = """
+import * as THREE from 'three';
+import { makeWaterMist, makeSpray } from './lib/watermist.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 20, 20] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ const mist = makeWaterMist({ extent: 8, height: 2, density: 0.6,
+ sunDir: [-0.65, 0.62, -0.45], seed: 5 });
+ const drops = makeSpray({ origin: [0, 0, 0], radius: 0.7,
+ sunDir: [-0.65, 0.62, -0.45], seed: 3 });
+ scene.add(mist);
+ scene.add(drops);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [6, 2, 8], lookAt: [0, 1, 0],
+ fov: 45 }],
+ update(t) { mist.userData.tick(t); drops.userData.tick(t); },
+ };
+}
+"""
+
+
+def test_both_effects_compile_on_the_real_renderer():
+ """Two custom shaders, both billboarded, both transparent, both reading
+ the scene's fog colour out of a preprocessor branch. The fog and depth
+ chunks decide whether they are drawn at all and whether they recede with
+ the scene; only the GPU can say."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "OK every program compiled" in out, out
+ # A WARN here is the fog trap or the override-pass trap, either of
+ # which ships an effect that looks wrong rather than one that errors.
+ assert "WARN" not in out, out
+
+
+def test_billboards_keep_position_at_the_origin():
+ """A pass that redraws with an override material ignores custom vertex
+ shaders, so a billboard field that keeps its quad in `position` burns a
+ black rectangle at the world origin."""
+ out = measure("""
+import { makeWaterMist, makeSpray } from './lib/watermist.js';
+const mist = makeWaterMist({ extent: 10, height: 2, seed: 4 })
+ .getObjectByName('MistCards');
+const drops = makeSpray({ radius: 0.6, rate: 90, seed: 7 })
+ .getObjectByName('SprayDroplets');
+const report = (m) => {
+ const g = m.geometry;
+ return {
+ posAllZero: Array.from(g.attributes.position.array)
+ .every((v) => v === 0),
+ hasCorner: !!g.attributes.aCorner,
+ instances: g.instanceCount,
+ };
+};
+console.log(JSON.stringify({
+ mist: report(mist),
+ spray: report(drops),
+ mistPerCard: mist.geometry.attributes.aPuff.count,
+ sprayPerDrop: drops.geometry.attributes.aVel.count,
+}));
+""", _LIBS)
+ for part in ("mist", "spray"):
+ assert out[part]["posAllZero"], out
+ assert out[part]["hasCorner"], out
+ assert out["mist"]["instances"] == out["mistPerCard"]
+ assert out["spray"]["instances"] == out["sprayPerDrop"]
+
+
+def test_the_stated_bounding_sphere_covers_both_fields():
+ """`position` is all zeros, so the sphere is the only thing three can
+ cull by: state it too small and the whole field disappears the moment
+ the origin leaves frame."""
+ out = measure("""
+import { makeWaterMist, makeSpray } from './lib/watermist.js';
+
+const mist = makeWaterMist({ extent: 12, height: 2.2, seed: 4 })
+ .getObjectByName('MistCards');
+const mg = mist.geometry;
+const puff = mg.attributes.aPuff.array;
+const card = mg.attributes.aCard.array;
+const size = mist.material.uniforms.uSize.value;
+let needMist = 0;
+for (let i = 0; i < mg.attributes.aPuff.count; i++) {
+ const c = Math.hypot(puff[i * 4], puff[i * 4 + 3], puff[i * 4 + 1]);
+ // The card turns to face the camera, so it sweeps its own diagonal.
+ const half = 0.5 * Math.hypot(size.x * card[i * 2],
+ size.y * card[i * 2 + 1]);
+ needMist = Math.max(needMist, c + half);
+}
+
+const spray = makeSpray({ origin: [3, 1, -2], radius: 0.8, speed: 5,
+ size: 0.06, rate: 100, seed: 7 });
+const drops = spray.getObjectByName('SprayDroplets');
+const dg = drops.geometry;
+const vel = dg.attributes.aVel.array;
+const ph = dg.attributes.aPhase.array;
+let needSpray = 0;
+for (let i = 0; i < dg.attributes.aVel.count; i++) {
+ const flight = (2 * vel[i * 3 + 1]) / 9.81;
+ for (let k = 0; k <= 16; k++) {
+ const p = spray.userData.sample(i, (k / 16) * flight);
+ needSpray = Math.max(needSpray, p.length() + 0.06 * ph[i * 2 + 1]);
+ }
+}
+console.log(JSON.stringify({
+ mistRadius: mg.boundingSphere.radius,
+ mistNeed: needMist,
+ mistCentre: mg.boundingSphere.center.toArray(),
+ sprayRadius: dg.boundingSphere.radius,
+ sprayNeed: needSpray,
+ sprayGroupAt: spray.position.toArray(),
+}));
+""", _LIBS)
+ # Local, because the group carries the placement: a sphere centred
+ # anywhere else is culled against the wrong point.
+ assert out["mistCentre"] == [0, 0, 0]
+ assert out["sprayGroupAt"] == [3, 1, -2]
+ assert out["mistRadius"] >= out["mistNeed"], out
+ assert out["sprayRadius"] >= out["sprayNeed"], out
+ # And not a made-up huge number, which would keep a field that has
+ # long left the frame in every draw call.
+ assert out["mistRadius"] <= out["mistNeed"] * 1.5, out
+ assert out["sprayRadius"] <= out["sprayNeed"] * 2.5, out
+
+
+def test_spray_droplets_fly_a_ballistic_arc():
+ """The one property that separates spray from a puff of dust: a droplet
+ is THROWN, so its height rises, stops and falls, and the curve is
+ gravity's, not an animator's ease."""
+ out = measure("""
+import { makeSpray } from './lib/watermist.js';
+const g = makeSpray({ radius: 0.5, speed: 4.5, rate: 80, seed: 11 });
+const drops = g.getObjectByName('SprayDroplets');
+const vel = drops.geometry.attributes.aVel.array;
+const ph = drops.geometry.attributes.aPhase.array;
+const N = 24;
+const arcs = [];
+for (const i of [0, 5, 17]) {
+ const flight = (2 * vel[i * 3 + 1]) / 9.81;
+ // Start each droplet at its own launch, so one whole arc is sampled.
+ const t0 = (1 - ph[i * 2]) * flight;
+ const ys = [], xs = [];
+ for (let k = 0; k <= N; k++) {
+ const p = g.userData.sample(i, t0 + (k / N) * flight * 0.999);
+ ys.push(p.y);
+ xs.push(Math.hypot(p.x, p.z));
+ }
+ let rises = 0, falls = 0, peak = 0;
+ for (let k = 1; k <= N; k++) {
+ if (ys[k] > ys[k - 1]) rises++; else falls++;
+ if (ys[k] > ys[peak]) peak = k;
+ }
+ // Second difference of a free fall is -g*dt^2, constant.
+ const dt = flight / N;
+ const dd = [];
+ for (let k = 1; k < N; k++) {
+ dd.push((ys[k + 1] - 2 * ys[k] + ys[k - 1]) / (dt * dt));
+ }
+ arcs.push({
+ rises, falls, peakAt: peak / N,
+ apex: ys[peak] - ys[0],
+ endY: ys[N] - ys[0],
+ gMin: Math.min(...dd), gMax: Math.max(...dd),
+ outward: xs[N] - xs[0],
+ });
+}
+console.log(JSON.stringify({ arcs }));
+""", _LIBS)
+ for arc in out["arcs"]:
+ assert arc["rises"] > 0 and arc["falls"] > 0, arc
+ # Up then down, once: the peak sits at mid-flight.
+ assert 0.40 <= arc["peakAt"] <= 0.60, arc
+ assert arc["apex"] > 0.1, arc
+ # Back to where it was launched by the end of its own flight.
+ assert abs(arc["endY"]) < arc["apex"] * 0.06, arc
+ # Gravity, not an ease: the curvature is constant at -g.
+ assert -10.0 < arc["gMin"] <= arc["gMax"] < -9.6, arc
+ # Thrown out of the impact, not straight up.
+ assert arc["outward"] > 0.05, arc
+
+
+def test_the_shader_flies_the_same_arc_the_cpu_mirror_does():
+ """`userData.sample` is only worth having if it is the same ballistics
+ the vertex shader runs; the constant and the closed form tie them
+ together."""
+ out = measure("""
+import { makeSpray } from './lib/watermist.js';
+const m = makeSpray({ seed: 2 })
+ .getObjectByName('SprayDroplets').material;
+const vs = m.vertexShader;
+console.log(JSON.stringify({
+ g: m.uniforms.uG.value,
+ flight: vs.includes('float flight = 2.0 * aVel.y / uG;'),
+ drop: vs.includes('c.y += aVel.y * age - 0.5 * uG * age * age;'),
+ relaunch: vs.includes('fract(aPhase.x + uTime / flight)'),
+}));
+""", _LIBS)
+ assert out["g"] == 9.81
+ assert out["flight"] and out["drop"] and out["relaunch"], out
+
+
+def test_no_single_card_can_be_seen_in_the_mist():
+ """A card is only invisible while it is faint and while several of them
+ are stacked along every ray. One card wide enough to cover the bank
+ paints its own noise raw, and that ribbon IS the card."""
+ out = measure("""
+import { makeWaterMist } from './lib/watermist.js';
+const probe = (o) => {
+ const mesh = makeWaterMist(o).getObjectByName('MistCards');
+ const u = mesh.material.uniforms;
+ const n = mesh.geometry.instanceCount;
+ return {
+ alpha: u.uAlpha.value,
+ cardW: u.uSize.value.x,
+ height: u.uTop.value,
+ dither: u.uDither.value,
+ // Cards a horizontal ray across the bank meets.
+ hits: (n * u.uSize.value.x) / o.extent,
+ count: n,
+ };
+};
+console.log(JSON.stringify({
+ small: probe({ extent: 8, height: 2, density: 0.6 }),
+ wide: probe({ extent: 40, height: 2.5, density: 0.6 }),
+ shallow: probe({ extent: 14, height: 0.8, density: 0.9 }),
+}));
+""", _LIBS)
+ for name, p in out.items():
+ assert p["alpha"] <= 0.6, (name, p)
+ assert p["hits"] >= 8, (name, p)
+ assert p["cardW"] <= max(1.0, p["height"] * 1.2) + 1e-6, (name, p)
+ # LAW 5. The dither is drawn once per CARD and the cards stack, so
+ # a flat amplitude sums as a random walk of sqrt(hits) times it —
+ # 0.004 flat was a visible speckle across the whole bank at 85 deep.
+ # What must stay constant is the amplitude the SUM carries.
+ assert abs(p["dither"] * (p["hits"] ** 0.5) - 0.010) < 1e-6, (name, p)
+
+
+def test_the_mist_lies_along_the_current_and_follows_the_water():
+ """This is the MOVING-water bank, not `makeHeightFog`: the drift sets
+ the direction the wisps lie in and the speed they travel, and
+ `heightAt` puts the foot of the bank on the water, not on y = 0."""
+ out = measure("""
+import { makeWaterMist } from './lib/watermist.js';
+const heightAt = (x, z) => 0.4 + Math.sin(x * 0.3) * 0.25 - z * 0.05;
+const g = makeWaterMist({ extent: 10, height: 2, drift: [0, 0.6],
+ heightAt, seed: 6 });
+const mesh = g.getObjectByName('MistCards');
+const u = mesh.material.uniforms;
+const p = mesh.geometry.attributes.aPuff.array;
+let baseErr = 0, aboveBase = 0, n = mesh.geometry.attributes.aPuff.count;
+for (let i = 0; i < n; i++) {
+ const want = heightAt(p[i * 4], p[i * 4 + 1]);
+ baseErr = Math.max(baseErr, Math.abs(p[i * 4 + 2] - want));
+ if (p[i * 4 + 3] >= p[i * 4 + 2] - 1e-6) aboveBase++;
+}
+const still = makeWaterMist({ drift: 0 }).getObjectByName('MistCards');
+console.log(JSON.stringify({
+ flow: u.uFlow.value.toArray(),
+ speed: u.uSpeed.value,
+ baseErr, aboveBase, n,
+ stillSpeed: still.material.uniforms.uSpeed.value,
+ name: g.name,
+ hasTick: typeof g.userData.tick === 'function',
+}));
+""", _LIBS)
+ assert out["flow"] == [0, 1] and abs(out["speed"] - 0.6) < 1e-6
+ assert out["baseErr"] < 1e-6, out
+ assert out["aboveBase"] == out["n"], out
+ assert out["stillSpeed"] == 0
+ assert out["name"] == "WaterMist" and out["hasTick"]
+
+
+def test_one_seed_gives_one_field():
+ """A re-run that reshuffles the mist or the droplets is a re-run nobody
+ can compare a render against."""
+ out = measure("""
+import { makeWaterMist, makeSpray } from './lib/watermist.js';
+const mistOf = (s) => Array.from(makeWaterMist({ extent: 8, seed: s })
+ .getObjectByName('MistCards').geometry.attributes.aPuff.array);
+const sprayOf = (s) => Array.from(makeSpray({ rate: 60, seed: s })
+ .getObjectByName('SprayDroplets').geometry.attributes.aVel.array);
+const eq = (a, b) => JSON.stringify(a) === JSON.stringify(b);
+console.log(JSON.stringify({
+ mistSame: eq(mistOf(5), mistOf(5)),
+ mistDiffers: !eq(mistOf(5), mistOf(9)),
+ spraySame: eq(sprayOf(3), sprayOf(3)),
+ sprayDiffers: !eq(sprayOf(3), sprayOf(8)),
+}));
+""", _LIBS)
+ assert all(out.values()), out
+
+
+def test_tick_advances_both_materials():
+ out = measure("""
+import { makeWaterMist, makeSpray } from './lib/watermist.js';
+const mist = makeWaterMist({ extent: 6 });
+const spray = makeSpray({ rate: 40 });
+mist.userData.tick(2.5);
+spray.userData.tick(2.5);
+const times = [];
+for (const g of [mist, spray]) {
+ g.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (m && m.uniforms && m.uniforms.uTime) {
+ times.push([m.name, m.uniforms.uTime.value]);
+ }
+ }
+ });
+}
+console.log(JSON.stringify({ times }));
+""", _LIBS)
+ assert len(out["times"]) == 2, out
+ assert all(v == 2.5 for _, v in out["times"]), out
+ assert sorted(n for n, _ in out["times"]) == [
+ "SprayDroplets", "WaterMistCards"]
+
+
+def test_neither_effect_paints_its_own_colour():
+ """LAW 1. Both emitted a fixed pale blue-grey, which made the bank a
+ glowing white slab and the droplets white confetti over a black weir at
+ night. What a scattering medium shows is its albedo times what reaches
+ it, and `fogColor` — the ONE light the renderer hands a raw
+ ShaderMaterial — is the skylight at ground level."""
+ out = measure("""
+import { makeWaterMist, makeSpray } from './lib/watermist.js';
+const mist = makeWaterMist({ extent: 8 })
+ .getObjectByName('MistCards').material;
+const drops = makeSpray({ rate: 60 })
+ .getObjectByName('SprayDroplets').material;
+const reads = (m) => {
+ const fs = m.fragmentShader;
+ // The read has to sit inside the guard: `fogColor` is only DECLARED
+ // under USE_FOG, so an unguarded one fails to compile in a fogless
+ // scene — and the fallback is what keeps that scene looking as before.
+ const at = fs.indexOf('sky = fogColor;');
+ const guard = fs.lastIndexOf('#ifdef USE_FOG', at);
+ const end = fs.indexOf('#endif', at);
+ return {
+ fogGuarded: at > 0 && guard > 0 && end > at,
+ fallbackWhite: fs.includes('vec3 sky = vec3(1.0);'),
+ // Multiplied, never emitted.
+ litByColor: fs.includes('uColor * (sky * uSkyGain'),
+ fogEnabled: m.fog === true && !!m.uniforms.fogColor,
+ };
+};
+console.log(JSON.stringify({ mist: reads(mist), spray: reads(drops) }));
+""", _LIBS)
+ for part in ("mist", "spray"):
+ assert out[part]["fogGuarded"], (part, out)
+ assert out[part]["fallbackWhite"], (part, out)
+ assert out[part]["litByColor"], (part, out)
+ assert out[part]["fogEnabled"], (part, out)
+
+
+def test_the_sun_below_the_horizon_delivers_nothing():
+ """LAW 1 again, from the other side. A sun gain that ignores elevation
+ is what put a lit bank into a night frame; `sunRig` keeps reporting the
+ authored sun after it has set, so the module has to read the height."""
+ out = measure("""
+import { makeWaterMist, makeSpray } from './lib/watermist.js';
+const gain = (dir) => [
+ makeWaterMist({ sunDir: dir }).getObjectByName('MistCards')
+ .material.uniforms.uSunGain.value,
+ makeSpray({ rate: 60, sunDir: dir }).getObjectByName('SprayDroplets')
+ .material.uniforms.uSunGain.value,
+];
+const dirOf = (o) => o.getObjectByName('MistCards')
+ .material.uniforms.uSunDir.value.toArray();
+console.log(JSON.stringify({
+ high: gain([-0.65, 0.62, -0.45]),
+ grazing: gain([-0.8, 0.06, -0.6]),
+ set: gain([-0.6, -0.34, -0.72]),
+ none: gain(undefined),
+ noneDir: dirOf(makeWaterMist({})),
+ unit: dirOf(makeWaterMist({ sunDir: [0, 4, 3] })),
+}));
+""", _LIBS)
+ assert out["set"] == [0, 0], out
+ assert all(g > 0.5 for g in out["high"]), out
+ # A grazing sun delivers a fraction, not all of it and not none.
+ for a, b in zip(out["grazing"], out["high"], strict=True):
+ assert 0 < a < b, out
+ # No rig to hand: top lit at full strength, which is the old look.
+ assert out["none"] == out["high"], out
+ assert out["noneDir"] == [0, 1, 0], out
+ assert abs(sum(v * v for v in out["unit"]) - 1.0) < 1e-6, out
+
+
+def test_the_forward_lobe_is_broad_enough_to_matter():
+ """LAW 2. `pow(mu, 3)` only fires within ~30 degrees of the sun: at the
+ showcase rig's own angles (mu = +0.64 and +0.68) it moved the veil 2%
+ against a sun-mirrored control, which is no coupling at all. The
+ Henyey-Greenstein lobe is what makes an ordinary framing read."""
+ out = measure("""
+import { makeWaterMist } from './lib/watermist.js';
+const fs = makeWaterMist({ extent: 8 })
+ .getObjectByName('MistCards').material.fragmentShader;
+// The same lobe the fragment runs, evaluated here: 0.2929 / den^1.5 with
+// den = 1 + g*g - 2*g*mu at g = 0.55, clamped the way the shader clamps.
+const hg = (mu) => Math.min(2.0, Math.max(0.14,
+ 0.2929 / Math.max(Math.pow(1.3025 - 1.10 * mu, 1.5), 1e-3)));
+console.log(JSON.stringify({
+ hasLobe: fs.includes('float den = 1.3025 - 1.10 * mu;'),
+ usesView: fs.includes('normalize(vP - cameraPosition)'),
+ back: hg(-0.85), side: hg(0.0), showcase: hg(0.64), sun: hg(1.0),
+}));
+""", _LIBS)
+ assert out["hasLobe"] and out["usesView"], out
+ # Monotone from back-scatter to the sun, and normalised so side-scatter
+ # sits where the old power form's floor was.
+ assert out["back"] < out["side"] < out["showcase"] < out["sun"], out
+ assert abs(out["side"] - 0.20) < 0.01, out
+ # The point of the lobe: at the angle a camera actually stands at, the
+ # sun term is already worth twice its side-scatter value.
+ assert out["showcase"] > 2.0 * out["side"], out
+ # And bounded, so looking straight into the sun through a thick bank
+ # is a bright veil rather than a white hole.
+ assert out["sun"] <= 2.0, out
+
+
+def test_the_bank_has_no_lid_and_no_straight_edge():
+ """LAWS 3 and 4. A late card fade landed every card's upper rim in one
+ screen band — horizontal ribbons across the night frame — and a single
+ noise scale shorter than the view ray integrated away to a flat top."""
+ out = measure("""
+import { makeWaterMist } from './lib/watermist.js';
+const fs = makeWaterMist({ extent: 16, height: 2.4, density: 0.62 })
+ .getObjectByName('MistCards').material.fragmentShader;
+const num = (re) => {
+ const m = fs.match(re);
+ return m ? parseFloat(m[1]) : null;
+};
+console.log(JSON.stringify({
+ fadeX: num(/smoothstep\\(([0-9.]+), 1\\.0, e\\.x\\)/),
+ fadeY: num(/smoothstep\\(([0-9.]+), 1\\.0, e\\.y\\)/),
+ coarse: num(/astraFbm2\\(q0 \\* ([0-9.]+) \\+ vec2\\(11\\.3/),
+ // The thickness field: a floor plus a fine octave plus a coarse one.
+ lift: fs.match(/float lift = ([^;]+);/)[1],
+}));
+""", _LIBS)
+ # LAW 3. Both axes fade from inside the middle of the card, so no two
+ # rims can agree on a screen row.
+ assert 0 < out["fadeY"] <= 0.30, out
+ assert 0 < out["fadeX"] <= 0.40, out
+ # LAW 4. The coarse octave is read at a fraction of the wisp
+ # frequency — structure metres across is the only kind a ray integral
+ # of a dozen cards leaves standing.
+ assert 0 < out["coarse"] <= 0.35, out
+ lift = out["lift"]
+ assert "astraFbm2(q0, 3)" in lift and "coarse" in lift, out
diff --git a/harness/tests/scene_runtime/lib/test_waterside.py b/harness/tests/scene_runtime/lib/test_waterside.py
new file mode 100644
index 00000000..aaaa4000
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_waterside.py
@@ -0,0 +1,711 @@
+"""waterside.js: the contact where ground, rock and water meet.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_waterside_lib.py). Their renderer-contract assertions are
+dropped; the physics claims, the shared-name contract and the
+option-is-a-uniform law are kept, and the grading this port added is pinned
+here so a later edit cannot flatten it back.
+
+A bank that meets water at a flat cut reads as two slabs intersecting, and
+every way these three patches can fail is SILENT: two of them routinely land
+on the same ground material, so a chain that drops one leaves foam on dry
+sand; a local declared twice in one injected main takes the whole material
+down; and a patch on the addon Water's raw ShaderMaterial finds no
+`<color_fragment>` hook and does nothing at all.
+
+THE PORT'S OWN LAWS, each one a defect measured on OUR renderer (ACES,
+exposure 1.0, no post chain, baked environment) in the fx showcase:
+
+1. `gloss` retunes the WHOLE material, and a shore ground is mostly dry.
+ The reference default of 0.45 took `MAT.soil()` from roughness 0.95 to
+ 0.4275 — the entire beach turned to satin and the frame came back at
+ mean_lum 0.85 with the waterline invisible inside it. The default is
+ now a light 0.85, and the wet gleam is a per-pixel fresnel sheen inside
+ the band instead.
+2. Wetting darkens AND saturates. Beach saturation went 0.039 -> 0.143
+ and luminance 0.774 -> 0.638 on the same frame.
+3. A band in world Y covers `band / slope` metres of ground, so on the one
+ surface that is exactly level — a water plane — it covered the entire
+ reach (contact 0.59 at t = 1.5) and laid streamers to the horizon. The
+ foam now fades out past its own footprint.
+4. No effect here may be one flat value: foam carries a lace break, a thin
+ tail and a hue break; the shoal carries a hue break that dies out with
+ depth; and the shallow default is a muted jade, because the reference's
+ pale sage (0.40-0.57 linear) came back off this renderer as white paint.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from _probe import LIB_DIR, compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "waterside.js")
+_LIB_SRC = (LIB_DIR / "waterside.js").read_text(encoding="utf-8")
+
+# The two hooks patchStandard injects into, as a material three would.
+_FAKE_SHADER = """
+const fake = () => ({
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+});
+"""
+
+
+def _measure(script: str) -> dict:
+ return measure(_FAKE_SHADER + script, _LIBS)
+
+
+def test_the_wet_band_fades_above_the_line_instead_of_cutting_it():
+ """Wet ground is darker ground — the whole cue. What makes it a shore
+ rather than a painted stripe is that the darkening survives fully BELOW
+ the waterline and fades out over the band above it, and that the line
+ itself wanders: a level contour is a ruled edge no bank has."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShoreWet } from './lib/waterside.js';
+const sh = fake();
+const m = patchShoreWet(new THREE.MeshStandardMaterial());
+m.onBeforeCompile(sh);
+const u = (k) => m.userData.uniforms[k].value;
+const t = patchShoreWet(new THREE.MeshStandardMaterial(),
+ { level: 3.5, band: 0.8, darken: 1.4 });
+console.log(JSON.stringify({
+ fs: sh.fragmentShader, vs: sh.vertexShader,
+ level: u('uWetY'), band: u('uWetBand'), darken: u('uWetDark'),
+ tunedLevel: t.userData.uniforms.uWetY.value,
+ tunedDark: t.userData.uniforms.uWetDark.value,
+}));
+""")
+ assert out["level"] == 0 and out["band"] == 0.25
+ assert out["darken"] == 0.45
+ assert out["tunedLevel"] == 3.5
+ # A darken over 1 would INVERT the albedo (1 - darken < 0) and paint the
+ # bank with negative light, so it is clamped where it is set.
+ assert out["tunedDark"] == 1.0
+ fs = out["fs"]
+ # Height above the water, not a UV: the bank has no useful one.
+ assert "float wtH = vAstraWorld.y - uWetY;" in fs
+ assert "astraContact(wtH, uWetBand)" in fs, "1 below the line, 0 above"
+ assert "astraFbm2(vAstraWorld.xz * 0.7, 3)" in fs, "the line must wander"
+ # The world position arrives from the vertex stage, instance transform
+ # folded in, or every scattered rock takes the origin's waterline.
+ assert "#ifdef USE_INSTANCING" in out["vs"]
+ assert "wsP = instanceMatrix * wsP;" in out["vs"]
+
+
+def test_wet_ground_is_darkened_and_deepened_then_gleams_at_the_grazing_edge():
+ """A water film is not a grey multiply. It drops the albedo, DEEPENS
+ the colour already there, and gleams where the view grazes it — and it
+ is the second of those that separates wet sand from sand in shadow
+ (measured on the showcase frame: beach saturation 0.039 -> 0.143 with
+ luminance 0.774 -> 0.638).
+
+ The sheen has to be per pixel, because the material-wide `gloss` cannot
+ tell the wet band from the dry beach behind it. Its colour is the
+ scene's own fog — the one sky-family colour a `<color_fragment>` patch
+ can reach — under `#ifdef USE_FOG`, since `fogColor` does not exist in
+ an unfogged program and reading it there fails every material at once.
+ """
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShoreWet } from './lib/waterside.js';
+const sh = fake();
+const m = patchShoreWet(new THREE.MeshStandardMaterial());
+m.onBeforeCompile(sh);
+const u = (k) => m.userData.uniforms[k].value;
+const t = patchShoreWet(new THREE.MeshStandardMaterial(),
+ { saturate: 0.9, sheen: 0.04 });
+const tu = (k) => t.userData.uniforms[k].value;
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ sat: u('uWetSat'), sheen: u('uWetSheen'),
+ tSat: tu('uWetSat'), tSheen: tu('uWetSheen'),
+}));
+""")
+ assert out["sat"] == 0.35 and out["sheen"] == 0.22
+ assert out["tSat"] == 0.9 and out["tSheen"] == 0.04
+ fs = out["fs"]
+ assert "vec3 wtDry = diffuseColor.rgb;" in fs
+ assert "float wtL = dot(wtDry, vec3(0.2126, 0.7152, 0.0722));" in fs
+ # Saturating pushes AWAY from the fragment's own luminance, so the mix
+ # factor is over 1 — and the darkening still scales the whole thing.
+ assert "mix(vec3(wtL), wtDry, 1.0 + uWetSat)" in fs
+ assert "* (1.0 - uWetDark);" in fs
+ # A big `saturate` on a nearly-grey pixel can overshoot below zero, and
+ # a negative albedo is a black hole in the middle of a beach.
+ assert "mix(wtDry, max(wtWet, vec3(0.0)), wtK);" in fs
+ # The sheen: world-space fresnel off the base's own normal, no extra
+ # varying (cameraPosition is a three built-in in both stages).
+ assert "vec3 wtV = normalize(cameraPosition - vAstraWorld);" in fs
+ assert "float wtF = astraFresnel(vAstraWorldN, wtV, 4.0);" in fs
+ assert "diffuseColor.rgb += wtSky * (wtF * wtK * uWetSheen);" in fs
+ # Guarded, with a fallback: an unfogged scene must still compile.
+ head = fs[fs.index("vec3 wtSky = vec3("):fs.index("vec3 wtV =")]
+ assert "#ifdef USE_FOG" in head and "wtSky = fogColor;" in head
+ assert "#endif" in head
+ assert fs.count("fogColor") == 1, "only under the guard"
+
+
+def test_wet_gloss_is_a_light_touch_because_a_shore_is_mostly_dry():
+ """patchStandard's only fragment hook runs after `<color_fragment>`,
+ which is BEFORE `<roughnessmap_fragment>` declares roughnessFactor — so
+ per-pixel roughness is unreachable and writing to it would be a compile
+ error on a line in three's assembled source. The gloss therefore lands
+ on the material, computed from the DRY value so that re-applying the
+ patch cannot compound it down to a mirror.
+
+ Which is exactly why the default is light. A waterline goes on the
+ SHORE GROUND, and the reference's 0.45 took `MAT.soil()` (roughness
+ 0.95) to 0.4275 across the whole beach: on this renderer that is satin
+ dirt reflecting the sky, and the showcase frame came back at mean_lum
+ 0.85 with the wet band lost inside the wash. 0.85 keeps the dry sand
+ above 0.8; a bank with a material of its own can still ask for 0.45."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShoreWet } from './lib/waterside.js';
+const sh = fake();
+const m = new THREE.MeshStandardMaterial({ roughness: 0.8 });
+patchShoreWet(m);
+const once = m.roughness;
+patchShoreWet(m);
+patchShoreWet(m);
+const thrice = m.roughness;
+patchShoreWet(m, { gloss: 1 });
+const undone = m.roughness;
+const soil = new THREE.MeshStandardMaterial({ roughness: 0.95 });
+patchShoreWet(soil);
+const dedicated = new THREE.MeshStandardMaterial({ roughness: 0.95 });
+patchShoreWet(dedicated, { gloss: 0.45 });
+const glossy = new THREE.MeshStandardMaterial({ roughness: 0.02 });
+patchShoreWet(glossy, { gloss: 0 });
+const basic = new THREE.MeshBasicMaterial();
+patchShoreWet(basic);
+patchShoreWet(m).onBeforeCompile(sh);
+console.log(JSON.stringify({
+ once, thrice, undone, soil: soil.roughness,
+ dedicated: dedicated.roughness, floor: glossy.roughness,
+ basicOk: basic.userData.astraPatches.length,
+ fs: sh.fragmentShader,
+}));
+""")
+ assert abs(out["once"] - 0.8 * 0.85) < 1e-9
+ assert out["thrice"] == out["once"], "a retune must not compound"
+ assert out["undone"] == 0.8, "gloss 1 restores the dry roughness"
+ assert out["soil"] > 0.8, "a patched beach stays dirt, not satin"
+ assert abs(out["dedicated"] - 0.95 * 0.45) < 1e-9, "still available"
+ assert out["floor"] > 0, "a zero roughness is a black mirror, not wet"
+ # A material without a roughness at all (Basic) must still take the
+ # patch: the darkening is the cue that matters.
+ assert out["basicOk"] == 2
+ # Nothing in the GLSL may reach for roughnessFactor: it does not exist
+ # yet at this hook.
+ assert "roughnessFactor" not in out["fs"]
+
+
+def test_foam_streamers_run_along_the_shore_not_across_it():
+ """A field ranked ACROSS the shore gives contours parallel to the waves,
+ which march at the viewer as bands. So the noise is built in a frame
+ taken from the surface itself — a bank tilts its normal up-slope, so the
+ horizontal normal is the across-shore axis and its perpendicular is the
+ shore — and stretched several-fold ALONG the shore into streamers. A
+ dead-flat surface has no shore direction to find, and a divide by its
+ zero length would take the material with it, so it falls back to the
+ world X axis."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShoreFoam } from './lib/waterside.js';
+const sh = fake();
+patchShoreFoam(new THREE.MeshStandardMaterial()).onBeforeCompile(sh);
+console.log(JSON.stringify({ fs: sh.fragmentShader }));
+""")
+ fs = out["fs"]
+ assert "vec2 fmNx = vAstraWorldN.xz;" in fs, "the frame is the surface's"
+ assert "vec2 fmA = fmL > 1e-3 ? fmNx / fmL : vec2(1.0, 0.0);" in fs
+ assert "vec2 fmB = vec2(-fmA.y, fmA.x);" in fs, "along = across turned 90"
+ assert "float fmU = dot(vAstraWorld.xz, fmB);" in fs
+ assert "float fmV = dot(vAstraWorld.xz, fmA);" in fs
+ # The anisotropy IS the effect: slow along the shore (fmU), fast across
+ # it (fmV), so the tear elongates into streamers.
+ assert "fmU * 0.30" in fs and "fmV * 2.10" in fs
+ along = float(fs.split("fmU * ")[1].split(" ")[0])
+ across = float(fs.split("fmV * ")[1].split(" ")[0])
+ assert across > along * 4, (along, across)
+
+
+def test_foam_breathes_and_hands_over_to_both_sides_of_the_line():
+ """An effect hands over to its neighbours instead of ending: the band is
+ strongest AT the waterline and fades both up the bank and down under the
+ surface, and the tear is a smoothstep, not a threshold. It breathes by
+ moving the LINE — two decorrelated swells, because one sine is a
+ metronome — which is what makes the foam run up and drain rather than
+ blink. uTime must reach the fragment stage DECLARED; patchStandard adds
+ that only because the declaration pass runs after the bodies are
+ injected."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShoreFoam, patchShoreWet } from './lib/waterside.js';
+const sh = fake();
+const m = patchShoreFoam(new THREE.MeshStandardMaterial());
+m.onBeforeCompile(sh);
+const u = (k) => m.userData.uniforms[k].value;
+const t = patchShoreFoam(new THREE.MeshStandardMaterial(),
+ { color: 0x223344, speed: 2.5, strength: 0.4, band: 1.2, level: -1 });
+const tu = (k) => t.userData.uniforms[k].value;
+const still = patchShoreWet(new THREE.MeshStandardMaterial());
+const stillSh = fake();
+still.onBeforeCompile(stillSh);
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ band: u('uFoamBand'), speed: u('uFoamSpeed'), amt: u('uFoamAmt'),
+ color: u('uFoamColor').getHex(), level: u('uFoamY'),
+ tColor: tu('uFoamColor').getHex(), tSpeed: tu('uFoamSpeed'),
+ tAmt: tu('uFoamAmt'), tBand: tu('uFoamBand'), tLevel: tu('uFoamY'),
+ timeDecls: (sh.fragmentShader.match(/uniform float uTime;/g) || []).length,
+ wetIsStill: !/\\buTime\\b/.test(stillSh.fragmentShader),
+ hasUniform: !!sh.uniforms.uFoamColor,
+}));
+""")
+ assert out["band"] == 0.35 and out["speed"] == 0.6
+ assert out["amt"] == 0.85 and out["level"] == 0
+ assert out["tColor"] == 0x223344 and out["tSpeed"] == 2.5
+ assert out["tAmt"] == 0.4 and out["tBand"] == 1.2 and out["tLevel"] == -1
+ fs = out["fs"]
+ assert "astraContact(abs(fmH), uFoamBand)" in fs, "strongest AT the line"
+ assert "fmK *= smoothstep(0.24, 0.62, fmN);" in fs, "torn, not thresholded"
+ # The swell moves the line itself, and two terms at incommensurate rates
+ # keep it off a metronome.
+ assert "sin(fmT) * 0.35 + sin(fmT * 0.63 + 1.7) * 0.22" in fs
+ assert "vAstraWorld.y - uFoamY - fmS * uFoamBand" in fs
+ assert "float fmT = uTime * uFoamSpeed;" in fs
+ assert out["timeDecls"] == 1, "read undeclared, uTime is a compile error"
+ assert out["wetIsStill"], "only the animated patch pays for uTime"
+ assert out["hasUniform"], "the patch's uniforms reach the program"
+
+
+def test_foam_is_lace_and_a_thin_tail_not_one_poured_white():
+ """Foam is bubbles. One field tears the band into streamers, a second
+ much finer one breaks the churn inside it, only the churn goes bright
+ (the tail is a thin film that still shows what is under it), and a hue
+ break keeps any two square metres of it off the same white.
+
+ The default white is graded DOWN as well: 0xeef4f5 runs 0.87 linear in
+ blue, over the 0.8 ceiling this project holds non-emissive albedos to,
+ and it is the first thing to clip when a bloom pass lands."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShoreFoam } from './lib/waterside.js';
+const sh = fake();
+const m = patchShoreFoam(new THREE.MeshStandardMaterial());
+m.onBeforeCompile(sh);
+const c = m.userData.uniforms.uFoamColor.value;
+console.log(JSON.stringify({
+ fs: sh.fragmentShader, hex: c.getHex(),
+ linear: [c.r, c.g, c.b],
+}));
+""")
+ fs = out["fs"]
+ assert out["hex"] == 0xdfe6e4
+ # THREE.Color holds the working (linear) value; the ceiling is the
+ # point of the regrade, so measure it rather than trusting the hex.
+ assert max(out["linear"]) < 0.8, out["linear"]
+ assert min(out["linear"]) > 0.7, "still reads as foam, not grey"
+ # The lace: a second field, finer across the shore than the streamers
+ # and drifting faster.
+ assert "float fmD = astraFbm2(vec2(fmU * 1.70," in fs
+ assert "fmV * 6.40 - fmT * 0.60), 2);" in fs
+ assert "fmK *= 0.55 + 0.45 * smoothstep(0.18, 0.72, fmD);" in fs
+ # The tail keeps most of the wet colour; only the churn is white.
+ assert "vec3 fmC = mix(uFoamColor * 0.70, uFoamColor," in fs
+ assert "smoothstep(0.30, 0.88, fmN));" in fs
+ assert "fmC = astraHueBreak(fmC, vAstraWorld.xz, 1.7, 0.14);" in fs
+ assert "mix(diffuseColor.rgb, fmC," in fs
+
+
+def test_foam_fades_off_a_surface_too_level_to_hold_a_band():
+ """A band of `band` metres in world Y covers `band * Ny / |Nxz|` metres
+ of GROUND, so the flatter the surface the wider it spreads — and on the
+ one surface that is exactly level, a water plane, it spreads over the
+ whole reach. Measured in the showcase: a foam patch on a flat reach hit
+ every fragment of it (contact 0.59 at t = 1.5) and laid streamers out to
+ the horizon.
+
+ So the band fades once its own footprint passes `reach`. This runs the
+ SHIPPED lines — they are scalar GLSL, which is valid JS once the type
+ keywords go — on a level plane, a 5-degree beach and a mooring pile."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShoreFoam } from './lib/waterside.js';
+const sh = fake();
+const m = patchShoreFoam(new THREE.MeshStandardMaterial());
+m.onBeforeCompile(sh);
+const fs = sh.fragmentShader;
+const from = fs.indexOf(' float fmSpan =');
+const tail = 'uFoamReach * 2.5, fmSpan);';
+const to = fs.indexOf(tail) + tail.length;
+const src = fs.slice(from, to).replace(/\\bfloat\\b/g, 'let');
+const run = (ny, nxz, band, reach) => {
+ const f = new Function(
+ 'vAstraWorldN', 'fmL', 'uFoamBand', 'uFoamReach', 'fmK',
+ 'abs', 'max', 'smoothstep',
+ src + '\\nreturn fmK;');
+ return f({ y: ny }, nxz, band, reach, 1,
+ Math.abs, Math.max,
+ (e0, e1, x) => {
+ const t = Math.min(1, Math.max(0, (x - e0) / (e1 - e0)));
+ return t * t * (3 - 2 * t);
+ });
+};
+console.log(JSON.stringify({
+ src,
+ reach: m.userData.uniforms.uFoamReach.value,
+ tuned: patchShoreFoam(new THREE.MeshStandardMaterial(), { reach: 40 })
+ .userData.uniforms.uFoamReach.value,
+ level: run(1, 0, 0.35, 3),
+ beach5deg: run(0.9962, 0.0872, 0.35, 3),
+ bank20deg: run(0.9397, 0.3420, 0.35, 3),
+ pile: run(0.0, 1.0, 0.35, 3),
+ levelOptOut: run(1, 0, 0.35, 1e9),
+}));
+""")
+ assert out["reach"] == 3 and out["tuned"] == 40
+ assert "uFoamBand * abs(vAstraWorldN.y) / max(fmL, 1e-4)" in out["src"]
+ assert out["level"] == 0, "a level plane holds no band of its own"
+ assert out["pile"] == 1, "a vertical face is all waterline"
+ assert out["bank20deg"] == 1, "a real bank is untouched"
+ # A 5-degree beach spreads 4 m, just past the default: it keeps most of
+ # its foam, and losing the last of it is the point of the ramp.
+ assert 0.8 < out["beach5deg"] < 1.0, out["beach5deg"]
+ # The opt-out is a uniform, so a caller who WANTS a wash over a whole
+ # reach can still have one without a second compiled program.
+ assert out["levelOptOut"] == 1
+
+
+def test_shallow_water_takes_its_depth_from_a_bed_fitted_on_the_cpu():
+ """Depth is the whole patch, and there are only two ways to get it in a
+ fragment shader here. World Y against a bedLevel is ONE number over a
+ flat water plane, so it paints the reach a single colour; a true bedAt
+ per fragment needs the heightfield as a texture or a depth prepass, and
+ this engine runs neither. So bedAt is fitted on the CPU to a tilted
+ plane — exact for a bed that slopes, which is what a bank is — and
+ shipped as three floats in one uniform."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShallowWater } from './lib/waterside.js';
+const sh = fake();
+const bedAt = (x, z) => -1.25 + 0.05 * x - 0.02 * z;
+const m = patchShallowWater(new THREE.MeshStandardMaterial(), {
+ bedAt, bounds: [-30, -20, 30, 40], deep: 0x102030,
+ shallow: new THREE.Color(0xccbb99), range: 3.5,
+});
+m.onBeforeCompile(sh);
+const u = (k) => m.userData.uniforms[k].value;
+// A bed that is not a plane still has to give a sane average slope.
+const bowl = patchShallowWater(new THREE.MeshStandardMaterial(),
+ { bedAt: (x, z) => -4 + 0.002 * (x * x + z * z),
+ bounds: [-20, -20, 20, 20] });
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ bed: u('uShoalBed'), range: u('uShoalRange'),
+ deep: u('uShoalDeep').getHex(), shallow: u('uShoalShallow').getHex(),
+ bowl: bowl.userData.uniforms.uShoalBed.value,
+}));
+""")
+ bed = out["bed"]
+ assert abs(bed["x"] - -1.25) < 1e-6, bed
+ assert abs(bed["y"] - 0.05) < 1e-9 and abs(bed["z"] - -0.02) < 1e-9
+ assert out["range"] == 3.5
+ assert out["deep"] == 0x102030 and out["shallow"] == 0xccbb99
+ # A symmetric bowl has no net tilt, and its mean sits above its lowest
+ # point — the fit is least squares, not a corner sample.
+ assert abs(out["bowl"]["y"]) < 1e-9 and abs(out["bowl"]["z"]) < 1e-9
+ assert -4 < out["bowl"]["x"] < -3
+ fs = out["fs"]
+ assert "uniform vec3 uShoalBed;" in fs, "three floats, not a sampler"
+ assert "sampler2D" not in fs, "no texture upload, no extra pass"
+ assert "uShoalBed.y * vAstraWorld.x" in fs
+ assert "uShoalBed.z * vAstraWorld.z" in fs
+ assert "float swD = vAstraWorld.y - swBed;" in fs
+ assert "mix(uShoalShallow, uShoalDeep, swK)" in fs
+ # The shoal edge wanders, or the ramp rules a contour across open water
+ # in exactly the way a real one never does.
+ assert "astraFbm2(vAstraWorld.xz * 0.35, 3)" in fs
+
+
+def test_shallow_water_without_a_bed_falls_back_to_a_constant_level():
+ """The documented degenerate case: no bedAt means a flat bed at
+ bedLevel, which on a flat surface is one depth for the whole reach. It
+ must still be a valid plane (zero tilt), never a NaN — a NaN colour
+ renders the water black."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShallowWater } from './lib/waterside.js';
+const d = patchShallowWater(new THREE.MeshStandardMaterial());
+const l = patchShallowWater(new THREE.MeshStandardMaterial(),
+ { bedLevel: -6.5 });
+const bad = patchShallowWater(new THREE.MeshStandardMaterial(),
+ { bedAt: () => NaN, bedLevel: -3 });
+const u = (m) => m.userData.uniforms.uShoalBed.value;
+console.log(JSON.stringify({
+ def: u(d), lev: u(l), bad: u(bad),
+ range: d.userData.uniforms.uShoalRange.value,
+ deep: d.userData.uniforms.uShoalDeep.value.getHex(),
+}));
+""")
+ assert out["def"] == {"x": -2, "y": 0, "z": 0}
+ assert out["lev"] == {"x": -6.5, "y": 0, "z": 0}
+ assert out["bad"] == {"x": -3, "y": 0, "z": 0}, "a NaN bed falls back"
+ assert out["range"] == 2
+ # The deep end defaults to water.js's graded waterColor, so a reach
+ # beside the scene's one RTT ocean agrees with it.
+ assert out["deep"] == 0x0e3f5c
+
+
+def test_shallow_water_is_a_graded_reach_not_a_two_colour_ramp():
+ """Three things separate water from a painted ramp, and the reference
+ shipped one of them. The wander is theirs. This port adds the hue
+ break — silt, weed and bed patches move the colour at metre scale, and
+ they do it in the SHALLOWS, where the bed shows through, while the deep
+ end holds still — and the alpha fade, so thin water is see-through
+ water and the bed under the shoal edge says where the bank goes.
+
+ The shallow default is regraded too: the reference's pale sage ran
+ 0.40-0.57 linear and came back off this renderer (ACES, exposure 1.0)
+ as white paint on the water. A muted jade at ~0.27 reads as water."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShallowWater } from './lib/waterside.js';
+const sh = fake();
+const m = new THREE.MeshStandardMaterial({ transparent: true, opacity: 0.9 });
+patchShallowWater(m);
+m.onBeforeCompile(sh);
+const shallow = m.userData.uniforms.uShoalShallow.value;
+const opaque = new THREE.MeshStandardMaterial();
+patchShallowWater(opaque);
+const asked = new THREE.MeshStandardMaterial({ transparent: true });
+patchShallowWater(asked, { edgeFade: 0.2 });
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ hex: shallow.getHex(), linear: [shallow.r, shallow.g, shallow.b],
+ fade: m.userData.uniforms.uShoalFade.value,
+ opaqueFade: opaque.userData.uniforms.uShoalFade.value,
+ askedFade: asked.userData.uniforms.uShoalFade.value,
+ key: m.customProgramCacheKey(),
+ opaqueKey: opaque.customProgramCacheKey(),
+}));
+""")
+ assert out["hex"] == 0x6fa392
+ assert 0.15 < max(out["linear"]) < 0.4, out["linear"]
+ fs = out["fs"]
+ assert "vec3 swC = mix(uShoalShallow, uShoalDeep, swK);" in fs
+ assert "swC = astraHueBreak(swC, vAstraWorld.xz, 0.09," in fs
+ # The break dies out with depth: 1 - swK * 0.8 is the shallow weight.
+ assert "0.34 * (1.0 - swK * 0.8));" in fs
+ assert "diffuseColor.a *= mix(uShoalFade, 1.0, swK);" in fs
+ assert out["fade"] == 0.55, "a transparent reach thins at its edge"
+ assert out["opaqueFade"] == 1, "three discards alpha on an opaque one"
+ assert out["askedFade"] == 0.2
+ # The fade is a UNIFORM, never a second source variant: the cache key
+ # names the patch, and the first material to compile a key decides the
+ # GLSL for every material that shares it.
+ assert out["key"] == out["opaqueKey"]
+
+
+def test_the_three_patches_chain_on_one_material():
+ """Two of these land on the same ground material as a matter of course,
+ so the chain is the load-bearing case. patchStandard chains by name:
+ the shared world-space base must be injected ONCE however many patches
+ ask for it, every body must survive, the cache key must name the whole
+ chain in order (the first material to compile a key decides the source
+ for all of them), and no local may be declared twice in one main."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShoreWet, patchShoreFoam, patchShallowWater }
+ from './lib/waterside.js';
+const sh = fake();
+const m = new THREE.MeshStandardMaterial();
+patchShoreWet(m, { level: 0.4 });
+patchShoreFoam(m, { level: 0.4 });
+patchShallowWater(m, { bedLevel: -1 });
+patchShoreWet(m, { level: 0.5 }); // retune, not a fourth patch
+m.onBeforeCompile(sh);
+const fs = sh.fragmentShader, vs = sh.vertexShader;
+const count = (s, re) => (s.match(re) || []).length;
+// Only what the bodies declare INSIDE main: the util block's own helpers
+// are functions, each with its own scope.
+const locals = {};
+const mains = fs.slice(fs.indexOf('void main')) + '\\n' +
+ vs.slice(vs.indexOf('void main'));
+const decl = /^\\s+(?:float|vec2|vec3|vec4)\\s+(\\w+)/gm;
+for (const hit of mains.match(decl) || []) {
+ const name = hit.trim().split(/\\s+/)[1];
+ locals[name] = (locals[name] || 0) + 1;
+}
+console.log(JSON.stringify({
+ key: m.customProgramCacheKey(),
+ wet: fs.includes('uWetDark'),
+ foam: fs.includes('mix(diffuseColor.rgb, fmC,'),
+ shallow: fs.includes('mix(uShoalShallow, uShoalDeep, swK)'),
+ order: fs.indexOf('wtK') < fs.indexOf('fmK') &&
+ fs.indexOf('fmK') < fs.indexOf('swK'),
+ level: m.userData.uniforms.uWetY.value,
+ uniforms: ['uWetY', 'uWetSheen', 'uFoamY', 'uFoamReach', 'uShoalBed',
+ 'uShoalFade', 'uTime'].every((k) => !!sh.uniforms[k]),
+ baseOnce: count(vs, /vAstraWorld = /g),
+ varyingVs: count(vs, /varying vec3 vAstraWorld;/g),
+ varyingFs: count(fs, /varying vec3 vAstraWorld;/g),
+ utilOnce: count(fs, /float astraFbm2\\(/g),
+ timeOnce: count(fs, /uniform float uTime;/g),
+ dupLocals: Object.keys(locals).filter((k) => locals[k] > 1),
+}));
+""")
+ assert out["wet"] and out["foam"] and out["shallow"], out
+ assert out["order"], "bodies run in call order"
+ assert out["key"] == ("astra:waterside:base+waterside:shoreWet"
+ "+waterside:shoreFoam+waterside:shallow")
+ assert out["level"] == 0.5, "re-applying retunes in place"
+ assert out["uniforms"], "every patch's uniforms reach the program"
+ assert out["baseOnce"] == 1, "the shared world body is injected once"
+ assert out["varyingVs"] == 1 and out["varyingFs"] == 1
+ assert out["utilOnce"] == 1 and out["timeOnce"] == 1
+ # One redeclared local is a GLSL redefinition that takes the whole
+ # material down — the reason each patch prefixes its own.
+ assert out["dupLocals"] == [], out["dupLocals"]
+
+
+def test_a_hookless_material_is_reported_instead_of_doing_nothing():
+ """The addon Water from water.js is a raw ShaderMaterial: it has no
+ `<color_fragment>` and no `<begin_vertex>`, so patching it is a no-op
+ with no error — the exact silent failure this library exists to avoid.
+ Say so, and only there: a built-in must stay quiet."""
+ out = _measure("""
+import * as THREE from 'three';
+import { patchShallowWater, patchShoreFoam } from './lib/waterside.js';
+const said = [];
+console.warn = (msg) => said.push(String(msg));
+patchShallowWater(new THREE.ShaderMaterial({ name: 'Ocean' }));
+const quiet = said.length;
+patchShoreFoam(new THREE.MeshStandardMaterial());
+patchShallowWater(new THREE.MeshPhysicalMaterial());
+console.log(JSON.stringify({ said, quiet, after: said.length }));
+""")
+ assert out["quiet"] == 1 and out["after"] == 1
+ said = out["said"][0]
+ assert "Ocean" in said and "color_fragment" in said
+
+
+def test_the_shipped_module_is_deterministic_and_stage_safe():
+ """A waterline must come back identical on a re-render, and its GLSL
+ ships into the VERTEX stage as well: a fragment-only builtin there
+ fails every program in the engine at once."""
+ src = _LIB_SRC
+ assert "Math.random" not in src
+ assert "Date.now" not in src
+ assert "fwidth" not in src
+ for name in ("patchShoreWet", "patchShoreFoam", "patchShallowWater"):
+ assert f"export function {name}" in src, name
+ # Three exports, no more: the library is the contact transitions.
+ assert src.count("\nexport ") == 3
+ assert max(len(ln) for ln in src.splitlines()) <= 80
+
+
+_SCENE = """
+import * as THREE from 'three';
+import { patchShoreWet, patchShoreFoam, patchShallowWater }
+ from './lib/waterside.js';
+import { tickShaders } from './lib/shader.js';
+
+const LEVEL = 0.4;
+const bedAt = (x, z) => -0.9 + 0.03 * x - 0.02 * z;
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ // FOGGED, because the wet sheen reads fogColor under #ifdef USE_FOG and
+ // an unfogged compile never touches that branch.
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);
+ scene.add(new THREE.DirectionalLight(0xffffff, 2.4));
+ scene.add(new THREE.HemisphereLight(0xbfd4ea, 0x6b5a44, 0.7));
+
+ // The bank: two patches on ONE material, the routine case.
+ const bank = new THREE.Mesh(
+ new THREE.PlaneGeometry(60, 40, 32, 24),
+ new THREE.MeshStandardMaterial({ color: 0x6f6250, roughness: 0.92 }));
+ bank.rotation.x = -Math.PI / 2.2;
+ bank.receiveShadow = true;
+ bank.name = 'Bank';
+ patchShoreWet(bank.material, { level: LEVEL, band: 0.3 });
+ patchShoreFoam(bank.material, { level: LEVEL });
+ scene.add(bank);
+
+ // Rocks: instanced, so the USE_INSTANCING branch has to compile.
+ const rocks = new THREE.InstancedMesh(
+ new THREE.IcosahedronGeometry(0.8, 1),
+ new THREE.MeshStandardMaterial({ color: 0x7d766c }), 8);
+ const m4 = new THREE.Matrix4();
+ for (let i = 0; i < 8; i++) {
+ m4.makeTranslation(-12 + i * 3, LEVEL - 0.2, 2 + (i % 3));
+ rocks.setMatrixAt(i, m4);
+ }
+ rocks.castShadow = true;
+ rocks.name = 'ShoreRocks';
+ patchShoreWet(rocks.material, { level: LEVEL, gloss: 0.5 });
+ patchShoreFoam(rocks.material, { level: LEVEL, strength: 0.7 });
+ scene.add(rocks);
+
+ // The reach: a plain standard material, never the addon Water.
+ const water = new THREE.Mesh(
+ new THREE.PlaneGeometry(60, 40),
+ new THREE.MeshStandardMaterial({
+ color: 0xffffff, roughness: 0.18, metalness: 0,
+ transparent: true, opacity: 0.9 }));
+ water.rotation.x = -Math.PI / 2;
+ water.position.y = LEVEL;
+ water.name = 'Reach';
+ patchShallowWater(water.material, { bedAt, range: 1.6 });
+ patchShoreFoam(water.material, { level: LEVEL, strength: 0.6 });
+ scene.add(water);
+
+ // A camera is not decoration: the host reports `ok: false` with an EMPTY
+ // error when `cameras` is empty, so a scene with none fails the compile
+ // preflight before a program is built.
+ return {
+ scene,
+ cameras: [{ name: 'hero', position: [9, 4, 11], lookAt: [0, 1, 0],
+ fov: 45 }],
+ update(t) { tickShaders(scene, t); },
+ };
+}
+"""
+
+
+def test_the_whole_waterline_compiles_on_the_gpu_in_a_fogged_scene():
+ """The only witness that counts. Everything above reads a string;
+ whether the GPU accepts the GLSL — the instancing branch, the shore
+ frame's divide, the fogColor branch of the sheen, three chained bodies
+ in one main, a vec3 uniform carrying a fitted plane — cannot be
+ asserted from source, and a patch that does not compile is worth
+ nothing. Runs the same preflight the authoring agent runs."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out
+ report = json.loads(out.strip().splitlines()[-1])
+ assert report["ok"] and report["errors"] == [], report
+ # Patched built-ins carry the built-in's own depth and fog chunks, so
+ # nothing here may be flagged as discardable or unfogged.
+ assert report["warnings"] == [], report["warnings"]
+ # bank, rocks (one key, two programs with the instanced one), reach.
+ assert report["compile"]["custom_materials"] >= 3, report
+ assert report["compile"]["gpu"], report
+ # And the OTHER side of the guard: with no fog in the scene there is no
+ # `fogColor` in the program at all, and the sheen has to fall back to
+ # its constant rather than fail every material that wears it.
+ code, out = compile_scene(
+ _SCENE.replace("scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);",
+ "// unfogged: the sheen falls back to its constant"),
+ _LIBS)
+ assert code == 0, out
+ assert json.loads(out.strip().splitlines()[-1])["ok"], out
diff --git a/harness/tests/scene_runtime/lib/test_wetground.py b/harness/tests/scene_runtime/lib/test_wetground.py
new file mode 100644
index 00000000..9d261e0f
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_wetground.py
@@ -0,0 +1,280 @@
+"""wetground.js: a planar reflection under a rough overlay, on OUR renderer.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_wetground_lib.py). Their three battery-measured laws are kept
+exactly as they stood — the mirror is a REAL Reflector at the graded 512 px
+RTT, the overlay sits millimetres up at the graded opacity because a faked
+floor renders near-black and a bare Reflector reads as marble, and the
+puddle mask is seeded so a run reproduces — because none of them are about
+their renderer.
+
+THE PORT'S OWN LAWS, each one a frame rendered on our host at
+fx/out/wetground/, looked at, and measured against the same fixture before
+the change:
+
+1. A WATER FILM IS NOT A CONSTANT BLEND. The stock Reflector returns the
+ reflection at full strength whatever the view angle, so the shipped pair
+ put the sky on the floor 1:1: the near half of a 30 x 22 m plaza came
+ back at mean luminance 0.687 with p95 0.884 — a blown milky sheet
+ brighter than the ground around it. Fresnel now decides how much of the
+ mirror a pixel sees, and it composites ONCE, in the overlay's alpha
+ (`a = 1 - F * (1 - a0)`): attenuating the mirror layer as WELL squared
+ the falloff and put the night plaza at dark_frac 0.14, a black hole
+ where the near floor should show lit wet asphalt. Same fixture after:
+ near half 0.523 mean / 0.647 p95, night dark_frac 0.001.
+
+2. THE FILM'S SLOPE IS WHAT READS AS WATER, NOT ITS UV. Sliding the
+ reflection's UV is invisible over a smooth sky; tilting the normal is
+ not, because Fresnel is steep in it. One shared field does both, so the
+ highlight rides the wobble that made it, and it fades with distance
+ because a per-pixel noise with no mip chain shimmers at range.
+
+3. THE MIRROR IS PART OF THE SCENE. A ShaderMaterial opts out of fog and
+ dithering, which left the one surface in the frame that never fogged
+ while everything around it did — and a 20 m sky reflection is exactly
+ the smooth gradient that bands in 8 bits.
+
+4. WET GROUND IS NOT ONE GREY. Looking straight down, Fresnel has admitted
+ almost no reflection, so the near field IS the albedo: pools are half
+ the albedo of the crests beside them, with a warm/cool cast that follows
+ the same field. The roughness map only nudges — dropping the substrate
+ to 0.45 double-counts the film's own specular and measured +20/255 of
+ flat sky sheen across the whole plaza.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401
+
+_LIBS = ("wetground.js", "noise.js")
+
+
+def _measure(script: str) -> dict:
+ return measure(script, _LIBS)
+
+
+_PROBE = """
+import * as THREE from 'three';
+import { Reflector } from 'three/addons/objects/Reflector.js';
+import { makeMirrorFloor } from './lib/wetground.js';
+
+const g = makeMirrorFloor(30, 20);
+const mirror = g.getObjectByName('MirrorSurface');
+const overlay = g.getObjectByName('GroundOverlay');
+
+const chan = (tex, c) => tex
+ ? Array.from(tex.image.data.filter((_, i) => i % 4 === c))
+ : null;
+const alphaBytes = (grp) =>
+ chan(grp.getObjectByName('GroundOverlay').material.alphaMap, 0);
+const p1 = alphaBytes(makeMirrorFloor(10, 10, { puddleMask: true }));
+const p2 = alphaBytes(makeMirrorFloor(10, 10, { puddleMask: true }));
+const p3 = alphaBytes(
+ makeMirrorFloor(10, 10, { puddleMask: true, seed: 9 }));
+let sameSeed = true, otherSeed = false;
+let aMin = 255, aMax = 0;
+for (let i = 0; i < p1.length; i++) {
+ if (p1[i] !== p2[i]) sameSeed = false;
+ if (p1[i] !== p3[i]) otherSeed = true;
+ aMin = Math.min(aMin, p1[i]);
+ aMax = Math.max(aMax, p1[i]);
+}
+
+const custom = makeMirrorFloor(10, 10, {
+ rttSize: 128, overlayOpacity: 0.8 });
+
+// The damp field drives alpha, albedo and roughness together, so the
+// wettest texel of the mask must also be the darkest and the smoothest.
+const pud = makeMirrorFloor(10, 10, { puddleMask: true, seed: 3 });
+const pMat = pud.getObjectByName('GroundOverlay').material;
+const mask = chan(pMat.alphaMap, 0);
+const lum = chan(pMat.map, 1);
+const rough = chan(pMat.roughnessMap, 1);
+let wettest = 0, driest = 0;
+for (let i = 0; i < mask.length; i++) {
+ if (mask[i] < mask[wettest]) wettest = i;
+ if (mask[i] > mask[driest]) driest = i;
+}
+// Hue spread over the albedo map: red-minus-blue, in bytes.
+const mr = chan(pMat.map, 0), mb = chan(pMat.map, 2);
+let rbMin = 255, rbMax = -255;
+for (let i = 0; i < mr.length; i++) {
+ const rb = mr[i] - mb[i];
+ rbMin = Math.min(rbMin, rb);
+ rbMax = Math.max(rbMax, rb);
+}
+
+const flat = makeMirrorFloor(10, 10, { detail: 0 });
+const stock = makeMirrorFloor(10, 10, { fresnel: 0 });
+const patchNames = (o) => (o.getObjectByName('GroundOverlay')
+ .material.userData.astraPatches || []).map((p) => p.name);
+const filmUniform = (o, k) => o.getObjectByName('GroundOverlay')
+ .material.userData.uniforms[k].value;
+
+console.log(JSON.stringify({
+ isReflector: mirror instanceof Reflector,
+ rttW: mirror.getRenderTarget().width,
+ customRttW: custom.getObjectByName('MirrorSurface')
+ .getRenderTarget().width,
+ mirrorFlat: Math.abs(mirror.rotation.x + Math.PI / 2) < 1e-6,
+ planeW: mirror.geometry.parameters.width,
+ planeH: mirror.geometry.parameters.height,
+ mirrorFog: mirror.material.fog === true,
+ mirrorDither: mirror.material.dithering === true,
+ mirrorHasRipple: 'uRipple' in mirror.material.uniforms,
+ overlayY: overlay.position.y,
+ overlayFlat: Math.abs(overlay.rotation.x + Math.PI / 2) < 1e-6,
+ opacity: overlay.material.opacity,
+ customOpacity: custom.getObjectByName('GroundOverlay')
+ .material.opacity,
+ transparent: overlay.material.transparent === true,
+ rough: overlay.material.roughness,
+ receivesShadow: overlay.receiveShadow === true,
+ defaultHasMask: !!overlay.material.alphaMap,
+ puddleHasMask: p1 !== null,
+ sameSeed, otherSeed, aMin, aMax,
+ patches: patchNames(g),
+ fresnelOn: filmUniform(g, 'uWgFresnel'),
+ fresnelOff: filmUniform(stock, 'uWgFresnel'),
+ hasMaps: !!overlay.material.map && !!overlay.material.roughnessMap,
+ flatMaps: !!flat.getObjectByName('GroundOverlay').material.map,
+ flatStillPatched: patchNames(flat).length,
+ poolLum: lum[wettest], crestLum: lum[driest],
+ poolRough: rough[wettest], crestRough: rough[driest],
+ roughMax: Math.max(...rough),
+ rbMin, rbMax,
+}));
+"""
+
+# The scene our check_shaders.mjs boots. Fog, because the mirror's shader
+# carries fog branches that only compile once USE_FOG is defined; a light,
+# because the overlay is a lit material; and a camera, because a scene with
+# none is reported as not booted and never reaches the compile stage.
+_SCENE = """
+import * as THREE from 'three';
+import { makeMirrorFloor } from './lib/wetground.js';
+
+export const BOUNDS = { min: [-20, 0, -20], max: [20, 20, 20] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xc9d6e0, 0.02);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 0.9));
+ const block = new THREE.Mesh(
+ new THREE.BoxGeometry(2, 3, 2),
+ new THREE.MeshStandardMaterial({ color: 0x8a5a3c, roughness: 0.9 }));
+ block.position.set(0, 1.5, -3);
+ scene.add(block);
+ // Every branch of the module, because each is a different program:
+ // masked + detailed, and the flat stock-blend fallback.
+ const wet = makeMirrorFloor(24, 18, { puddleMask: true, seed: 3 });
+ scene.add(wet);
+ const dry = makeMirrorFloor(6, 6, { fresnel: 0, detail: 0, ripple: 0 });
+ dry.position.set(14, 0, 0);
+ scene.add(dry);
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [8, 3, 10], lookAt: [0, 1, 0],
+ fov: 45 }],
+ update() {},
+ };
+}
+"""
+
+
[email protected](scope="module")
+def probe() -> dict:
+ """One node launch of _PROBE, shared by every test that reads it."""
+ return _measure(_PROBE)
+
+
+def test_mirror_is_a_real_reflector_at_the_measured_rtt_size(probe):
+ """The whole point is a REAL planar reflection: a Reflector with an
+ RTT target at the battery-graded 512 (cost-contained, quality
+ graded), sized to the requested footprint and laid flat."""
+ m = probe
+ assert m["isReflector"], "MirrorSurface is not a Reflector"
+ assert m["rttW"] == 512, f"default RTT size drifted: {m['rttW']}"
+ assert m["customRttW"] == 128, "rttSize option is dead"
+ assert m["mirrorFlat"], "mirror plane is not horizontal"
+ assert (m["planeW"], m["planeH"]) == (30, 20), m
+
+
+def test_overlay_sits_millimetres_up_at_the_graded_opacity(probe):
+ """The overlay turns marble into asphalt: rough, transparent, at the
+ battery opacity, millimetres above the mirror — a visible air gap or
+ an opaque overlay each kill the shipped look."""
+ m = probe
+ assert 0.0005 <= m["overlayY"] <= 0.01, f"gap: {m['overlayY']}"
+ assert m["overlayFlat"], "overlay not horizontal"
+ assert m["transparent"] and abs(m["opacity"] - 0.65) < 1e-6, m
+ assert abs(m["customOpacity"] - 0.8) < 1e-6, "overlayOpacity dead"
+ assert m["rough"] == 1, "overlay must be fully rough"
+ assert m["receivesShadow"], "overlay must receive shadows"
+
+
+def test_puddle_mask_is_seeded_and_actually_breaks_the_sheet(probe):
+ """puddleMask must cut real holes (alpha spans puddle-to-dry),
+ reproduce bit-identically per seed, and move for a new seed — a
+ dead seed silently degrades to plain overlay."""
+ m = probe
+ assert not m["defaultHasMask"], "default must have no alphaMap"
+ assert m["puddleHasMask"], "puddleMask produced no alphaMap"
+ assert m["aMin"] < 80 and m["aMax"] > 200, \
+ f"mask does not span puddle-to-dry: {m['aMin']}..{m['aMax']}"
+ assert m["sameSeed"], "same seed produced a different mask"
+ assert m["otherSeed"], "different seed changed nothing"
+
+
+def test_the_film_is_view_dependent_and_composites_exactly_once(probe):
+ """LAW 1. The Fresnel lives in the overlay's alpha — one patch,
+ applied through patchStandard so a `patch*` module can still chain
+ onto the same floor — and `fresnel: 0` puts the shipped constant
+ blend back for polished indoor stone."""
+ m = probe
+ assert m["patches"] == ["WetGroundFilm"], m["patches"]
+ assert m["fresnelOn"] == 1, m
+ assert m["fresnelOff"] == 0, "fresnel option does not reach the shader"
+ # The mirror layer must NOT attenuate as well: it carries the ripple
+ # and the tint, never a second Fresnel.
+ assert m["mirrorHasRipple"], "mirror lost its ripple uniform"
+
+
+def test_the_mirror_joins_the_scene_it_reflects(probe):
+ """LAW 3. A ShaderMaterial opts out of fog and dithering by
+ default, which leaves the floor crisp in a fogged frame and banded
+ across its sky gradient."""
+ m = probe
+ assert m["mirrorFog"], "mirror does not take scene fog"
+ assert m["mirrorDither"], "mirror does not dither its gradient"
+
+
+def test_pools_are_darker_smoother_and_cooler_than_the_crests(probe):
+ """LAW 4. Looking down, the albedo IS the puddle. One damp field
+ drives mask, colour and roughness, so the wettest texel must also be
+ the darkest and the smoothest — and the map has to carry a real
+ warm/cool spread, not one die-cut grey."""
+ m = probe
+ assert m["hasMaps"], "detail maps missing"
+ assert not m["flatMaps"], "detail: 0 must leave a flat sheet"
+ assert m["flatStillPatched"] == 1, "detail: 0 dropped the film patch"
+ # Water traps light: the pool is well under the crest beside it.
+ assert m["poolLum"] < m["crestLum"] * 0.75, m
+ # ... and it is smoother, but only a nudge: the water surface is the
+ # mirror layer, not this one.
+ assert m["poolRough"] < m["crestRough"], m
+ assert m["roughMax"] > 0.85 * 255, \
+ f"substrate polished into a second mirror: {m['roughMax']}"
+ # Warm crests, cool pools: red-minus-blue has to swing both ways.
+ assert m["rbMin"] < -12 and m["rbMax"] > 12, \
+ f"albedo map carries no hue spread: {m['rbMin']}..{m['rbMax']}"
+
+
+def test_every_program_compiles_on_the_gpu():
+ """Both branches ship raw GLSL — a whole Reflector shader and a
+ patched MeshStandardMaterial — so the compile is the test."""
+ code, out = compile_scene(_SCENE, _LIBS)
+ assert code == 0, out
diff --git a/harness/tests/scene_runtime/lib/test_windows.py b/harness/tests/scene_runtime/lib/test_windows.py
new file mode 100644
index 00000000..3ea76ea4
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_windows.py
@@ -0,0 +1,583 @@
+"""windows.js: a lit window has to be a ROOM, or a night city is decals.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_windows_lib.py). Their laws are kept as they stood — the pane
+is a shallow box traced from the view direction, the tangent frame comes
+from screen derivatives taken in UNIFORM control flow, a cell that is not
+window-sized keeps its own surface, a lit room lifts radiance and not only
+albedo, an unlit cell is dark glass and never a hole, every tunable is a
+uniform so one patch kind compiles once, the pattern is seeded and still,
+and the convenience finds the facade slot without patching the shared
+material `materials.js` handed the rest of the city.
+
+THE PORT'S OWN LAWS — each one a frame rendered on our host at
+fx/out/windows/, looked at, and measured:
+
+1. THE CELL ID MUST LIVE ON A WHOLE-NUMBER LATTICE. `vWinKey` is one
+ constant handed to every vertex, but a perspective-correct varying is
+ (sum w/q)/(sum 1/q) and comes back a few ULPs apart per pixel. The
+ original hashed that raw key into `winB` and then hashed `winB` into
+ the cell id: two chained astraHash21 calls, each amplifying an input
+ wobble by about a thousand (measured in float32: one ULP at coordinate
+ 120 moves the hash 0.008). On this GPU that turned `winOn` into a
+ per-pixel coin flip and every facade rendered as STATIC — measured over
+ the pane pixels of fx/out/windows/before/close_t1p5.png, mean
+ |laplacian| 0.1584 with 19.4% of pixels past 0.06. Rounding the key,
+ the face weight and the hash draw to integers makes the id bit-exact
+ per cell: 0.0102 and 3.8% after, a 15.5x drop, and the same hash on an
+ integer lattice inside +-700 is still well spread (mean 0.504, sigma
+ 0.291, adjacent |dh| 0.333).
+
+2. AN UNLIT PANE IS RADIANCE, NOT ALBEDO. The reflected sky was written
+ to `diffuseColor` only, where it is multiplied by the light landing on
+ the wall — and at night that is nothing, so every dark pane collapsed
+ to the hole in the facade the term exists to prevent (7.3% of the close
+ facade crop under luminance 0.045, p05 0.027). Adding it to
+ `totalEmissiveRadiance` as well puts it at 0.9% and p05 0.103, with
+ blown_frac still 0.
+
+3. THE SKY A PANE MIRRORS IS THE SCENE'S. It was the `cool` uniform flat,
+ so a facade reflected the same pale blue at midnight as at noon. It
+ now reads `fogColor` where the scene has fog — the horizon's own hue —
+ and splits at the reflected ray's horizon, so glass takes the darker
+ ground below and the sky above. `cool` stays as the floor for a scene
+ with no fog.
+
+4. HUE AND BRIGHTNESS VARIANCE INSIDE THE EFFECT. A warm/cool lerp gives
+ a facade exactly two bulbs and one level. Each cell now draws its own
+ small hue rotation, saturation and brightness, and about a third are
+ dressed with a blind or a drawn curtain. Measured over the lit pixels
+ of the close crop, circular hue spread 0.597 -> 0.901.
+
+5. NO RAZOR LINE ACROSS A PANE. The blind was a hard `step` at one height
+ on every floor of the building, which is the tell of a decal; it is a
+ smoothstep hem now, and the shallow room ramps carry an LSB of hash
+ grain against 8-bit banding.
+"""
+
+from __future__ import annotations
+
+from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure # noqa: F401
+
+_LIBS = ("shader.js", "windows.js")
+_LIB = LIB_DIR / "windows.js"
+
+# The two hooks patchStandard injects into, as a material three would.
+_FAKE_SHADER = """
+const fake = () => ({
+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',
+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',
+ uniforms: {},
+});
+const patched = (opts) => {
+ const sh = fake();
+ patchWindowInteriors(new THREE.MeshStandardMaterial(), opts || {})
+ .onBeforeCompile(sh);
+ return sh;
+};
+"""
+
+_PRELUDE = """
+import * as THREE from 'three';
+import { patchWindowInteriors, makeNightWindows } from './lib/windows.js';
+""" + _FAKE_SHADER
+
+
+def _measure(script: str, libs: tuple[str, ...] = _LIBS) -> dict:
+ return measure(_PRELUDE + script, libs)
+
+
+def test_the_window_is_a_box_interior_traced_from_the_view_direction():
+ """The whole point: a ray from the surface point into a shallow box per
+ cell, shaded where it lands, so the room slides with the camera. The
+ frame it is traced in comes from the screen derivatives because a
+ facade is any box face at any orientation and carries no tangent — and
+ the derivatives are taken in UNIFORM control flow, since dFdx inside a
+ branch is undefined and would tear the frame per pixel."""
+ out = _measure("""
+const sh = patched();
+console.log(JSON.stringify({ fs: sh.fragmentShader, vs: sh.vertexShader }));
+""")
+ fs = out["fs"]
+ # The slab test itself: two walls, one floor/ceiling pair, and a back
+ # wall `depth` behind the glass — the nearest is what is seen.
+ assert "vec3 astraWinRoom(vec3 o, vec3 d, float depth, out vec3 face)" in fs
+ assert "vec3 tHi = (vec3(1.0, 1.0, 0.0) - o) / ds;" in fs
+ assert "vec3 tLo = (vec3(0.0, 0.0, -depth) - o) / ds;" in fs
+ assert "float t = min(min(tm.x, tm.y), tm.z);" in fs
+ assert "face = step(tm, vec3(t));" in fs
+ # The direction is the VIEW ray, in the surface's own frame.
+ assert "vec3 winV = normalize(cameraPosition - vWinW);" in fs
+ assert "mat3 winTbn = astraWinFrame(vWinW, vWinUv, winNn, winMpu);" in fs
+ assert "dot(winV, winTbn[0])" in fs
+ assert "vec3 dp1 = dFdx(p), dp2 = dFdy(p);" in fs
+ # Which wall was hit decides the shade: back wall full, side walls
+ # dimmer, ceiling lit and floor dark.
+ assert "float winShade = winHitFace.z + winHitFace.x * 0.45" in fs
+ assert "mix(0.22, 0.8, step(0.5, winHit.y))" in fs
+ # No branch anywhere: the pane is a mask mixed in at the end, so every
+ # derivative above is taken with the whole quad in step.
+ assert "discard" not in fs
+ assert "if (" not in fs.split("void main")[-1]
+ # The grid is measured in UV and the room is one cell wide.
+ assert "vec2 winG = vWinUv * uWinGrid;" in fs
+ assert "const vec2 ASTRA_WIN_EDGE" in fs
+
+
+def test_a_cell_that_is_not_window_sized_keeps_its_own_surface():
+ """three's BoxGeometry gives EVERY box face a full 0..1 UV whatever its
+ size, so on a facade merged from many boxes — which is what `block()`
+ and `tower()` are — a UV grid paints the whole window pattern onto each
+ 0.34 m mullion and each spandrel band. The shader can tell the
+ difference only by metres per unit of UV, which the tangent frame
+ already has to compute; under about a metre per cell the member is
+ handed back untouched. The same goes once a pixel spans a third of a
+ cell: past that the room can only alias into sparkle."""
+ out = _measure("""
+const sh = patched();
+console.log(JSON.stringify({ fs: sh.fragmentShader }));
+""")
+ fs = out["fs"]
+ assert "float det = max(abs(du1.x * du2.y - du2.x * du1.y), 1e-12);" in fs
+ assert "mpu = vec2(length(dp1 * du2.y - dp2 * du1.y)," in fs
+ assert "length(dp2 * du1.x - dp1 * du2.x)) / det;" in fs
+ assert "winPane *= smoothstep(0.55, 1.0, min(winMpu.x / uWinGrid.x," in fs
+ assert "winPane *= 1.0 - smoothstep(0.3, 0.8, max(winAa.x, winAa.y));" in fs
+
+
+def test_the_cell_id_is_a_whole_number_lattice_or_the_facade_is_static():
+ """PORT LAW 1, and the reason this module did not ship as it arrived.
+
+ `vWinKey` is a constant handed to every vertex of the draw, but a
+ perspective-correct varying is (sum w/q)/(sum 1/q) and comes back a few
+ ULPs apart per pixel. astraHash21 amplifies an input wobble by about a
+ thousand, so hashing the raw key into `winB` and then hashing `winB`
+ into the cell id chains two amplifications and `winOn` — a step() on
+ that hash — becomes a per-pixel coin flip. It rendered as static on
+ this GPU. Every term of the id is therefore rounded: the key, the face
+ weight, and the hash draw off the key. Nothing here is cosmetic; drop
+ one floor() and the facade fizzes again."""
+ out = _measure("""
+const sh = patched();
+console.log(JSON.stringify({ fs: sh.fragmentShader }));
+""")
+ fs = out["fs"]
+ assert "vec3 winKq = floor(vWinKey * 16.0 + 0.5);" in fs
+ assert ("float winFace = dot(floor(winNn * 4.0 + 0.5),"
+ " vec3(11.0, 29.0, 53.0));") in fs
+ assert ("float winB = floor(astraHash21(winKq.xz + winKq.y) * 29.0)"
+ " + winFace;") in fs
+ assert "vec2 winId = floor(winG)" in fs
+ assert "vec2(uWinSeed + winB, floor(uWinSeed * 1.7) - winB);" in fs
+ # The furniture noise enters its lattice through the cell HASHES, not
+ # through the id, so its coordinate stays small enough to interpolate.
+ assert "vec2 winNz = winHit.xy * 3.0 + vec2(winHt, winHl) * 37.0;" in fs
+ assert "winShade *= mix(0.55, 1.0, astraNoise2(winNz));" in fs
+
+
+def test_the_seed_offset_is_a_far_apart_whole_number():
+ """The seed rides the same lattice, so it has to be an integer too — a
+ fractional offset puts every cell id between two lattice points, where
+ the hash is far more sensitive to the last bit of its inputs than to
+ the cell. And it is hashed rather than used raw because seeds 7 and 8
+ offsetting the lattice by one would merely TRANSLATE the pattern by one
+ window, which reads as the same building twice."""
+ out = _measure("""
+const seedOf = (s) => patchWindowInteriors(
+ new THREE.MeshStandardMaterial(), { seed: s })
+ .userData.uniforms.uWinSeed.value;
+const many = [];
+for (let s = 0; s < 64; s++) many.push(seedOf(s));
+console.log(JSON.stringify({
+ same: seedOf(7) === seedOf(7),
+ differs: seedOf(7) !== seedOf(8),
+ gap: Math.abs(seedOf(7) - seedOf(8)),
+ dflt: seedOf(undefined) === seedOf(1),
+ finite: Number.isFinite(seedOf(123456789)),
+ allInt: many.every((v) => Number.isInteger(v)),
+ bigInt: Number.isInteger(seedOf(123456789)),
+ spread: new Set(many).size,
+ max: Math.max(...many),
+}));
+""")
+ assert out["same"], "the same seed must relight the same windows"
+ assert out["differs"] and out["gap"] > 1, "not a one-cell shift"
+ assert out["dflt"], "the default seed is 1, not an unseeded draw"
+ assert out["finite"] and out["bigInt"], "a large seed stays a usable int"
+ assert out["allInt"], "a fractional offset puts the id off the lattice"
+ assert out["spread"] >= 48, "64 seeds must not collapse onto a handful"
+ assert out["max"] < 512, "and the lattice stays where the hash is spread"
+
+
+def test_a_lit_room_lifts_the_radiance_not_only_the_albedo():
+ """`fragmentBody` lands after <color_fragment>, where `diffuseColor` is
+ albedo: a room written there alone can only ever be a pale wall,
+ however bright the number. The lift therefore also goes on
+ `totalEmissiveRadiance` — legal at this hook only because three
+ declares it BEFORE the hook and (without an emissive map) never
+ overwrites it after. A three upgrade that moves that line breaks the
+ effect with no error, so the order is asserted on three's own source."""
+ out = _measure("""
+import { ShaderLib, ShaderChunk } from 'three';
+const src = ShaderLib.standard.fragmentShader;
+const sh = patched();
+console.log(JSON.stringify({
+ fs: sh.fragmentShader,
+ declaredBeforeHook: src.indexOf('vec3 totalEmissiveRadiance = emissive;')
+ < src.indexOf('#include <color_fragment>'),
+ emissiveMapOnly: /#ifdef USE_EMISSIVEMAP[^]*?totalEmissiveRadiance \\*=/
+ .test(ShaderChunk.emissivemap_fragment),
+ usedAfterHook: src.indexOf('#include <color_fragment>')
+ < src.lastIndexOf('totalEmissiveRadiance'),
+}));
+""")
+ assert out["declaredBeforeHook"], "the hook is too late to declare it"
+ assert out["usedAfterHook"], "and it must still reach outgoingLight"
+ assert out["emissiveMapOnly"], "only an emissive map may rescale it"
+ fs = out["fs"]
+ assert "totalEmissiveRadiance += max(winRoom + winGrain, 0.0)" in fs
+ assert "* (uWinEmissive * winOn * winPane);" in fs
+ # Gated by both: an unlit room radiates nothing, and neither does the
+ # spandrel between the panes.
+ assert "float winOn = step(astraHash21(winId), uWinLit);" in fs
+ assert "float winPane = winE.x * winE.y;" in fs
+
+
+def test_an_unlit_cell_is_dark_glass_and_never_a_hole():
+ """PORT LAW 2 and 3, on top of theirs. The failure that makes a night
+ facade read as a punched card is the windows that are off going to flat
+ black — and writing the reflection to `diffuseColor` alone IS that
+ failure on a night host, because albedo is multiplied by the light
+ landing on the wall and at night there is none. The reflection is
+ added as radiance as well. The sky it reflects is the scene's own: the
+ fog colour where there is fog, split at the reflected horizon so the
+ pane takes the ground below it and the sky above."""
+ out = _measure("""
+const sh = patched();
+console.log(JSON.stringify({ fs: sh.fragmentShader }));
+""")
+ fs = out["fs"]
+ assert "vec3 winSky = uWinCool;" in fs
+ assert "#ifdef USE_FOG" in fs and "mix(uWinCool, fogColor, 0.7);" in fs
+ assert "vec3 winRefl = reflect(-winV, winNn);" in fs
+ assert "mix(0.34, 1.0, smoothstep(-0.30, 0.30, winRefl.y))" in fs
+ assert "vec3 winDark = winRoom * 0.06 + uWinCool * 0.015" in fs
+ assert "+ winSky * (0.05 + 0.6 * winFr);" in fs
+ # The radiance half, gated on the pane being OFF.
+ assert "totalEmissiveRadiance += (winSky * (0.06 + 0.9 * winFr)" in fs
+ assert "* ((1.0 - winOn) * winPane);" in fs
+ # Lit or unlit, the pane is a MIX over the facade albedo underneath.
+ assert "max(mix(winDark, winRoom * 0.35, winOn) + winGrain * 0.25, 0.0)" in fs
+ assert "discard" not in fs
+ # A reflection off a wall the fog colour cannot be read from must still
+ # be glass, so the `cool` floor is unconditional.
+ assert fs.index("vec3 winSky = uWinCool;") < fs.index("#ifdef USE_FOG")
+
+
+def test_no_two_rooms_are_the_same_room():
+ """PORT LAW 4 and 5. A warm/cool lerp gives a facade exactly two bulbs
+ at one level, which is a stencil however well the ray traced it. Every
+ cell draws its own hue rotation, its own saturation and its own
+ brightness off the tungsten-to-daylight axis, and about a third are
+ dressed — a blind hung over the top of the pane (a smoothstep hem, not
+ the razor line the original cut across every floor at one height), or a
+ curtain drawn right across, which scatters and turns the box into an
+ even panel. Three INDEPENDENT hashes, because reusing one would tie
+ the bright rooms to the warm ones."""
+ out = _measure("""
+const sh = patched();
+console.log(JSON.stringify({ fs: sh.fragmentShader }));
+""")
+ fs = out["fs"]
+ for draw in ("float winHt = astraHash21(winId + 3.3);",
+ "float winHf = astraHash21(winId + 19.7);",
+ "float winHl = astraHash21(winId + 41.1);"):
+ assert draw in fs, draw
+ assert "winTint = astraHueShift(winTint, (winHl - 0.5) * 0.18);" in fs
+ assert "mix(0.72, 1.24, astraHash21(winId + 7.9))" in fs
+ assert ("float winLevel = mix(0.30, 1.15,"
+ " winHl * winHl * (3.0 - 2.0 * winHl));") in fs
+ assert "vec3 winRoom = winTint * (winShade * winLevel);" in fs
+ # The fittings.
+ assert "winShade *= mix(1.0, 0.24, step(0.74, winHf)" in fs
+ assert "* smoothstep(0.46, 0.64, winQ.y));" in fs, "a hem, not a razor"
+ assert "float winCurt = step(winHf, 0.30) * 0.85;" in fs
+ assert "winShade = mix(winShade, 0.52 + 0.34 * (1.0 - winQ.y), winCurt);" in fs
+ # The fitting is on the ceiling, so the room falls off downward.
+ assert "winShade *= mix(0.58, 1.14, smoothstep(0.0, 1.0, winHit.y));" in fs
+ # One LSB of grain against 8-bit banding on those shallow ramps.
+ assert ("vec3 winGrain = vec3((astraHash21(gl_FragCoord.xy) - 0.5)"
+ " * 0.004);") in fs
+
+
+def test_every_tunable_is_a_uniform_with_the_documented_defaults():
+ """Two facades tuned differently must still share one compiled program,
+ which is only true while every option is a uniform: the FIRST material
+ to compile a cache key decides the GLSL for every material that shares
+ it, so a baked-in option value would silently become everybody's. The
+ grid is rounded because a fractional cell count splits the last column
+ at the UV seam."""
+ out = _measure("""
+const val = (m) => {
+ const o = {};
+ for (const k of Object.keys(m.userData.uniforms)) {
+ const v = m.userData.uniforms[k].value;
+ o[k] = (v && v.isColor) ? v.getHex() : ((v && v.isVector2)
+ ? [v.x, v.y] : v);
+ }
+ return o;
+};
+const d = patchWindowInteriors(new THREE.MeshStandardMaterial());
+const t = patchWindowInteriors(new THREE.MeshStandardMaterial(), {
+ rows: 12.4, cols: 5, depth: 1.2, lit: 1.6, emissive: 0.4,
+ warm: new THREE.Color(0x112233), cool: 0x445566,
+});
+const a = patched({ rows: 3, lit: 0.9 });
+const b = patched({ rows: 30, lit: 0.1, depth: 4 });
+console.log(JSON.stringify({
+ d: val(d), t: val(t),
+ sameGlsl: a.fragmentShader === b.fragmentShader
+ && a.vertexShader === b.vertexShader,
+ key: d.customProgramCacheKey(),
+ gridA: a.uniforms.uWinGrid.value.y, gridB: b.uniforms.uWinGrid.value.y,
+ marked: !!d.userData.astraShader,
+}));
+""")
+ assert out["d"]["uWinGrid"] == [6, 8], "cols x rows, per unit of UV"
+ assert out["d"]["uWinDepth"] == 0.6 and out["d"]["uWinLit"] == 0.35
+ assert out["d"]["uWinEmissive"] == 1.6
+ assert out["d"]["uWinWarm"] == 0xffc98a
+ assert out["d"]["uWinCool"] == 0x9fc0e8
+ assert out["t"]["uWinGrid"] == [5, 12], "a fractional cell count rounds"
+ assert out["t"]["uWinDepth"] == 1.2 and out["t"]["uWinEmissive"] == 0.4
+ assert out["t"]["uWinLit"] == 1, "a fraction of the windows, clamped"
+ assert out["t"]["uWinWarm"] == 0x112233
+ assert out["t"]["uWinCool"] == 0x445566
+ assert out["sameGlsl"], "one patch kind must compile to one source"
+ assert out["gridA"] == 3 and out["gridB"] == 30
+ assert out["key"] == "astra:windows:interior"
+ assert out["marked"], "tickShaders finds patches by this flag"
+
+
+def test_the_lit_pattern_is_seeded_and_reproducible():
+ """A re-render must not relight a different set of windows. The pattern
+ is a hash of the cell index offset by the seed, and nothing else: no
+ `uTime` reaches the fragment stage, so it cannot flicker between
+ frames, and no `Math.random` reaches the JS."""
+ out = _measure("""
+const sh = patched({ seed: 7 });
+console.log(JSON.stringify({ fs: sh.fragmentShader }));
+""")
+ fs = out["fs"]
+ assert "vec2 winId = floor(winG)" in fs
+ assert "float winOn = step(astraHash21(winId), uWinLit);" in fs
+ assert "uTime" not in fs, "a seeded pattern may not move with time"
+ src = _LIB.read_text(encoding="utf-8")
+ assert "Math.random" not in src and "Date.now" not in src
+ # Its GLSL head ships only in the FRAGMENT stage; dFdx there would fail
+ # every vertex shader in the engine at once.
+ assert "dFdx" in src and "vertexHead: WIN_VARYINGS" in src
+
+
+def test_buildings_sharing_one_material_still_light_differently():
+ """`materials.js` returns ONE instance to every caller that asked for
+ the same look, so a district of blocks shares a facade material and a
+ per-material seed would light every tower identically. The lit hash
+ also takes the draw's own world origin, which is constant across a mesh
+ and therefore safe to hash per cell, plus the quantised normal so the
+ four faces of one box differ from each other."""
+ out = _measure("""
+const sh = patched();
+const vs = sh.vertexShader, fs = sh.fragmentShader;
+console.log(JSON.stringify({
+ vs, fs,
+ vertexAfterHook: vs.indexOf('#include <begin_vertex>')
+ < vs.indexOf('vWinW ='),
+ fragAfterHook: fs.indexOf('#include <color_fragment>')
+ < fs.indexOf('diffuseColor.rgb ='),
+ fragOnly: !vs.includes('dFdx') && fs.includes('dFdx'),
+ fragDefine: fs.includes('#define ASTRA_FRAG'),
+ vertexDefine: vs.includes('#define ASTRA_FRAG'),
+}));
+""")
+ vs, fs = out["vs"], out["fs"]
+ assert out["vertexAfterHook"] and out["fragAfterHook"]
+ assert out["fragOnly"], "a derivative in the vertex stage breaks all"
+ assert out["fragDefine"] and not out["vertexDefine"]
+ # The per-draw key: the mesh origin in world space, and the instance
+ # origin on an InstancedMesh, where `transformed` is still local.
+ assert "vec4 winO = vec4(0.0, 0.0, 0.0, 1.0);" in vs
+ assert "#ifdef USE_INSTANCING" in vs
+ assert "winP = instanceMatrix * winP;" in vs
+ assert "winO = instanceMatrix * winO;" in vs
+ assert "vWinKey = (modelMatrix * winO).xyz;" in vs
+ assert "astraHash21(winKq.xz + winKq.y)" in fs
+ assert "float winFace = dot(floor(winNn * 4.0 + 0.5)" in fs
+ # A varying declared in one stage only is a link failure whose symptom
+ # is the patch simply not drawing.
+ for decl in ("varying vec2 vWinUv;", "varying vec3 vWinW;",
+ "varying vec3 vWinN;", "varying vec3 vWinKey;"):
+ assert decl in vs and decl in fs, decl
+
+
+def test_the_convenience_finds_the_facade_and_spares_the_shared_material():
+ """A `block()` is a group of merged meshes — walls, trim, glazing,
+ reveals — so a caller reaching for `mesh.material` would window the
+ cornice or miss entirely. And its wall material is the SHARED instance
+ `materials.js` hands to every caller that asked for plaster, so
+ patching it in place would put windows on every plastered surface in
+ the scene. It is cloned first, with its userData reset: clone()
+ deep-copies userData but not `onBeforeCompile`, so a carried-over patch
+ chain would name patches in the cache key that no longer run."""
+ out = _measure("""
+import * as MAT from './lib/materials.js';
+import { block } from './lib/building.js';
+let s = 5;
+const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+const b = block({ w: 14, d: 12, h: 20, style: 'masonry', rand, lit: 0.4 });
+const before = b.getObjectByName('Walls').material;
+const trimBefore = b.getObjectByName('Trim').material;
+let meshes = 0, verts = 0;
+b.traverse((o) => { if (o.isMesh) {
+ meshes++; verts += o.geometry.attributes.position.count; } });
+const same = makeNightWindows(b, { seed: 4 }) === b;
+let after = 0, afterVerts = 0, patchedMats = 0;
+const seen = new Set();
+b.traverse((o) => { if (o.isMesh) {
+ after++; afterVerts += o.geometry.attributes.position.count;
+ for (const m of [].concat(o.material)) {
+ if (seen.has(m.uuid)) continue;
+ seen.add(m.uuid);
+ if (m.userData.astraPatches) patchedMats++;
+ } } });
+const walls = b.getObjectByName('Walls').material;
+console.log(JSON.stringify({
+ same, meshes, after, addedVerts: afterVerts - verts, patchedMats,
+ wallsPatched: !!walls.userData.astraPatches,
+ wallsKey: walls.customProgramCacheKey(),
+ cloned: walls !== before,
+ sharedSpared: !before.userData.astraPatches,
+ cacheSpared: !MAT.plaster().userData.astraPatches,
+ trimUntouched: b.getObjectByName('Trim').material === trimBefore
+ && !trimBefore.userData.astraPatches,
+ cleanUserData: !walls.userData.shared,
+}));
+""", ("shader.js", "windows.js", "materials.js", "building.js"))
+ assert out["same"], "it returns the object, so it can be added inline"
+ assert out["wallsPatched"] and out["wallsKey"] == "astra:windows:interior"
+ assert out["cloned"] and out["cleanUserData"]
+ assert out["sharedSpared"], "the shared instance must not be patched"
+ assert out["cacheSpared"], "nor the next caller asking for plaster"
+ assert out["trimUntouched"], "a cornice does not get windows"
+ assert out["patchedMats"] == 1, "one facade material, one draw call"
+ # No geometry at all: the depth is in the shader, which is the whole
+ # reason this can run over a district.
+ assert out["after"] == out["meshes"] and out["addedVerts"] == 0
+
+
+def test_a_tower_leaves_with_no_more_materials_than_it_arrived_with():
+ """`tower()` stacks `block()` tiers whose walls came from `materials.js`,
+ so several tiers arrive holding the SAME instance. Patching per mesh
+ would clone it per tier and pay a material (and a uniform upload) for
+ each; the convenience patches a source material once and hands the same
+ result to every mesh that had it.
+
+ The reference asserted a count of exactly one here. That is a fact
+ about their `block()`, not about this module: ours tints each tier's
+ wall into one of `materials.js`'s nine hue buckets, so a three-tier
+ tower arrives with two. The law that belongs to windows.js is that the
+ number does not GROW."""
+ out = _measure("""
+import { tower } from './lib/building.js';
+let s = 9;
+const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+const t = tower({ w: 20, d: 18, h: 90, style: 'glass', rand, lit: 0.5 });
+const wallsOf = () => {
+ const out = [];
+ t.traverse((o) => { if (o.isMesh && /Walls/.test(o.name)) {
+ out.push(o.material); } });
+ return out;
+};
+const before = new Set(wallsOf().map((m) => m.uuid)).size;
+makeNightWindows(t, { seed: 2 });
+const walls = wallsOf();
+console.log(JSON.stringify({
+ tiers: walls.length,
+ before,
+ after: new Set(walls.map((m) => m.uuid)).size,
+ patched: walls.every((m) => !!m.userData.astraPatches),
+}));
+""", ("shader.js", "windows.js", "materials.js", "building.js"))
+ assert out["tiers"] >= 3, "a tower steps in, so it has tiers"
+ assert out["before"] < out["tiers"], "tiers do share their wall material"
+ assert out["after"] == out["before"], "one patch per source material"
+ assert out["patched"], "and every tier's wall carries it"
+
+
+# The scene our check_shaders.mjs boots: fog, so USE_FOG is defined and the
+# `winSky` branch actually compiles, and a camera, because a scene with none
+# is reported as not booted and never reaches the compile stage at all.
+_SCENE = """
+import * as THREE from 'three';
+import { block, tower } from './lib/building.js';
+import { makeNightWindows, patchWindowInteriors } from './lib/windows.js';
+
+export const BOUNDS = { min: [-60, 0, -60], max: [60, 100, 60] };
+export function heightAt() { return 0; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0x0b0f1a, 0.004);
+ scene.add(new THREE.HemisphereLight(0x22304a, 0x0a0c10, 0.6));
+ let s = 11;
+ const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+
+ const b = block({ w: 16, d: 12, h: 24, style: 'masonry', rand, lit: 0.4 });
+ makeNightWindows(b, { rows: 9, cols: 7, lit: 0.45, seed: 3 });
+ b.position.set(-30, 0, 0);
+ scene.add(b);
+
+ const t = tower({ w: 20, d: 18, h: 90, style: 'glass', rand, lit: 0.5 });
+ makeNightWindows(t, { depth: 0.9, seed: 8, emissive: 2.4,
+ warm: new THREE.Color(0xffc07a), cool: 0x8fb4ff });
+ scene.add(t);
+
+ // Instanced, because `transformed` is still object-space at the vertex
+ // hook: the USE_INSTANCING branch has to compile too.
+ const slabs = new THREE.InstancedMesh(new THREE.BoxGeometry(9, 26, 9),
+ new THREE.MeshStandardMaterial({ color: 0x2b3038 }), 6);
+ const m4 = new THREE.Matrix4();
+ for (let i = 0; i < 6; i++) {
+ m4.makeTranslation(30 + i * 12, 13, (rand() - 0.5) * 40);
+ slabs.setMatrixAt(i, m4);
+ }
+ patchWindowInteriors(slabs.material, { seed: 5, rows: 12, cols: 4 });
+ scene.add(slabs);
+
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [40, 20, 70], lookAt: [0, 20, 0],
+ fov: 45 }],
+ update() {},
+ };
+}
+"""
+
+
+def test_it_compiles_on_the_real_renderer_over_a_real_building():
+ """The only witness that counts. Everything above reads a string;
+ whether the GPU accepts a mat3 built from screen derivatives, an `out`
+ parameter, a slab test per fragment, a `reflect` off an interpolated
+ normal, a read of `fogColor` from an injected body and a write to
+ `totalEmissiveRadiance` cannot be asserted from source — and a patch
+ that does not compile is worth nothing. Over a real block(), a real
+ tower() and an InstancedMesh, in a FOGGED scene so the `winSky` branch
+ is the one that gets built."""
+ code, out = compile_scene(
+ _SCENE, ("shader.js", "materials.js", "building.js", "windows.js"))
+ assert code == 0, out
+ assert "OK every program compiled" in out
+ # A patched built-in keeps the built-in's own depth and fog chunks, so
+ # nothing here may be flagged: a WARN means this facade would hold full
+ # contrast while the city recedes.
+ assert "DISCARDED" not in out and "WARN " not in out
diff --git a/harness/tests/scene_runtime/lib/test_woodland.py b/harness/tests/scene_runtime/lib/test_woodland.py
new file mode 100644
index 00000000..e504aeb9
--- /dev/null
+++ b/harness/tests/scene_runtime/lib/test_woodland.py
@@ -0,0 +1,497 @@
+"""woodland.js — bark that runs UP a trunk, and a far field that BELONGS.
+
+Ported 2026-09-01 from the scene_multifile_graphics reference
+(tests/test_woodland_lib.py). Its claims are kept whole: the grain is
+anisotropic, the four kinds are four structures sharing one program, the bark
+BLENDS over what it lands on, the imposter field is one instanced draw call
+seated on the caller's ground inside a stated bounding sphere, it stays out of
+every override pass, and a seed is a promise.
+
+Their compile cases are restored at the end of this file, through
+``_probe.compile_scene`` (16 programs, 3 custom materials). What is asserted
+before them is the STRUCTURE of the GLSL, read back off ``onBeforeCompile`` and
+off the built material; the frames are at fx/out/woodland/ (day and night).
+
+The last four tests are new, and each pins a change the port made:
+
+* the card material is OPAQUE with alpha-to-coverage. Blended, the field is
+ one draw call and therefore unsorted against itself, so a card resolved its
+ soft edge against the sky and then wrote depth — a pale halo traced round
+ every silhouette with another card behind it, measured at 2.5 per mille of
+ the treeline band and gone (0.9) once coverage decides per MSAA sample;
+* the card's light comes from the scene's own ``sunRig`` package, environment
+ bake included, instead of a pair of constants graded for another renderer.
+ Under the moon the reference's constants lit the treeline at 1.54x the real
+ crown standing in it — a daylight wood at midnight;
+* a card is a BALL: the bowed normal hands half of every backlit card a full
+ sun term the geometry beside it does not get (1.41x, measured), and a crown
+ occludes its own interior, which nothing else in this material can supply;
+* the bark tints are albedos. Birch was 0.85 and rendered as a white pole.
+"""
+from __future__ import annotations
+
+import pytest
+from _probe import compile_scene, measure
+
+pytestmark = pytest.mark.node
+
+_LIBS = ("shader.js", "noise.js", "grass.js", "woodland.js")
+
+# Drive onBeforeCompile on a bare standard material and read the GLSL back.
+_COMPILE = """
+const compile = (m) => {
+ const s = { uniforms: {},
+ vertexShader: 'void main() { #include <begin_vertex> }',
+ fragmentShader: '#include <color_fragment>' };
+ m.onBeforeCompile(s);
+ return s;
+};
+"""
+
+
+def test_bark_fissures_run_up_the_trunk_and_not_around_it():
+ """A trunk's grain runs UP. That one asymmetry is the whole claim: an
+ isotropic noise on a cylinder reads as lichen or as stone, never as bark.
+ The library divides the along-axis coordinate by `aniso` and leaves the
+ across-axis alone, so the ratio is measurable in the shipped source and in
+ the uniforms it hands the GPU."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchBark } from './lib/woodland.js';
+const u = (kind) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchBark(m, { kind });
+ const s = compile(m);
+ return { u: s.uniforms, fs: s.fragmentShader };
+};
+const oak = u('oak'), birch = u('birch'), bamboo = u('bamboo');
+console.log(JSON.stringify({
+ oakAniso: oak.u.uBarkAniso ? oak.u.uBarkAniso.value : null,
+ birchAniso: birch.u.uBarkAniso ? birch.u.uBarkAniso.value : null,
+ bambooAniso: bamboo.u.uBarkAniso ? bamboo.u.uBarkAniso.value : null,
+ // The ALONG-axis coordinate is divided by aniso and the ACROSS pair is
+ // not. Read the two lines rather than looking for one spelling.
+ dividesOneAxis: (() => {
+ const along = /float bkH = [^;]*;/.exec(oak.fs);
+ const across = /vec2 bkQ = [^;]*;/.exec(oak.fs);
+ return !!along && !!across
+ && /uBarkAniso/.test(along[0]) && !/uBarkAniso/.test(across[0]);
+ })(),
+ kindIsUniform: oak.fs === birch.fs && oak.fs === bamboo.fs,
+ kindKnob: oak.u.uBarkKind ? oak.u.uBarkKind.value : null,
+}));
+""", _LIBS)
+ for k in ("oakAniso", "birchAniso", "bambooAniso"):
+ assert out[k] is not None, f"{k} is not a uniform"
+ assert out[k] > 2, f"{k} is {out[k]}: that grain is not directional"
+ assert out["dividesOneAxis"], (
+ "the anisotropy must stretch one axis, not scale both")
+ assert out["kindIsUniform"], (
+ "four kinds must share one program: kind is a uniform, not a branch")
+
+
+def test_the_four_kinds_are_four_structures():
+ """pine plates, birch papery bands, oak deep ridges, bamboo smooth nodes.
+ If they differed only in tint they would be one bark with four colours,
+ which is what a palette-only implementation gives."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchBark } from './lib/woodland.js';
+const u = (kind) => {
+ const m = new THREE.MeshStandardMaterial();
+ patchBark(m, { kind });
+ return compile(m).uniforms;
+};
+const k = ['pine', 'birch', 'oak', 'bamboo'].map(u);
+const num = (n) => k.map((x) => (x[n] ? x[n].value : null));
+console.log(JSON.stringify({
+ kinds: num('uBarkKind'),
+ aniso: num('uBarkAniso'),
+ scale: num('uBarkScale'),
+ tints: k.map((x) => x.uBarkTint.value.toArray()),
+}));
+""", _LIBS)
+ assert len(set(out["kinds"])) == 4, "the four kinds share an id"
+ assert len(set(out["aniso"])) > 1 or len(set(out["scale"])) > 1, (
+ "the kinds differ only in tint")
+
+
+def test_a_bark_tint_is_an_albedo():
+ """New here. `tint` is multiplied over the material's own colour and then
+ lit; anything near 1.0 has nowhere left to go under a 5.4 sun and clips
+ before the tone map can shape it. Birch shipped at 0xd8d4c8 and came back
+ as the brightest thing in a daylight frame — luminance 0.746 with a p95 of
+ 0.833, brighter than the sky's own gradient over it."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchBark } from './lib/woodland.js';
+const worst = {};
+for (const kind of ['pine', 'birch', 'oak', 'bamboo']) {
+ const m = new THREE.MeshStandardMaterial();
+ patchBark(m, { kind });
+ const c = compile(m).uniforms.uBarkTint.value;
+ // THREE.Color holds LINEAR working values; the 0.8 ceiling is stated in
+ // the sRGB the table is written in.
+ worst[kind] = Math.max(...new THREE.Color().copyLinearToSRGB(c).toArray());
+}
+console.log(JSON.stringify(worst));
+""", _LIBS)
+ for kind, top in out.items():
+ assert top <= 0.80 + 1e-3, (
+ f"{kind}'s tint peaks at {top:.3f}: that is not an albedo")
+ assert top >= 0.02, f"{kind}'s tint is black"
+
+
+def test_bark_blends_and_never_assigns_over_what_it_lands_on():
+ """A trunk carries edge wear, micro-breakup and often moss before the bark
+ goes on. patchTriplanar and patchSlopeSplat both assigned diffuseColor.rgb
+ and each erased the other for months."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchBark } from './lib/woodland.js';
+const m = new THREE.MeshStandardMaterial();
+patchBark(m, {});
+const fs = compile(m).fragmentShader;
+const body = fs.slice(fs.indexOf('#include <color_fragment>'));
+const assigns = (body.match(/diffuseColor\\.rgb\\s*=(?!=)/g) || []).length;
+const folds = (body.match(
+ /diffuseColor\\.rgb\\s*=\\s*(mix\\(\\s*diffuseColor|diffuseColor)/g)
+ || []).length;
+console.log(JSON.stringify({ assigns, folds,
+ multiplies: (body.match(/diffuseColor\\.rgb\\s*\\*=/g) || []).length }));
+""", _LIBS)
+ assert out["assigns"] == out["folds"], (
+ "bark assigns over the colour it landed on")
+ assert out["multiplies"] >= 1, "the fissures never darken anything"
+
+
+def test_a_fissure_is_dark_and_cool_and_never_black():
+ """New here. The cut used to multiply the albedo by `1 - depth` with a
+ relief floor of 0.45 under it, so a deep oak at depth 0.62 reached 17% of
+ its own colour — paint, not relief, and the first thing to crush on a night
+ frame. What reaches the bottom of a fissure is SKY: dimmer AND cooler than
+ the ridge beside it, which is the depth cue that survives being resolved
+ down to four pixels."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchBark } from './lib/woodland.js';
+const m = new THREE.MeshStandardMaterial();
+patchBark(m, { kind: 'oak', depth: 1.0 });
+const fs = compile(m).fragmentShader;
+// the cut's own multiplier: mix(lit ridge, dark fissure, bkCut)
+const cut = /mix\\(1\\.0 \\+ 0\\.30 \\* uBarkDepth,\\s*([0-9.]+) - ([0-9.]+) \\* uBarkDepth/
+ .exec(fs.replace(/\\s+/g, ' '));
+const lit = /clamp\\(1\\.0 \\+ bkRel \\* [0-9.]+ \\+ bkFlat \\* [0-9.]+, ([0-9.]+),/
+ .exec(fs);
+// a cool tint multiplied in with the cut, blue channel above red
+const cool = /vec3\\(0\\.(\\d+), 0\\.(\\d+), 1\\.(\\d+)\\),\\s*bkCut/
+ .exec(fs.replace(/\\s+/g, ' '));
+console.log(JSON.stringify({
+ floor: cut ? +cut[1] - +cut[2] : null,
+ litFloor: lit ? +lit[1] : null,
+ cool: !!cool,
+}));
+""", _LIBS)
+ assert out["floor"] is not None, "the fissure multiplier is gone"
+ assert out["floor"] >= 0.25, (
+ f"a full-depth fissure lands at {out['floor']:.2f} of the albedo")
+ assert out["litFloor"] is not None and out["litFloor"] >= 0.5, (
+ "the relief can take a facet to half its own colour")
+ assert out["cool"], "the fissure is not cooler than the ridge beside it"
+
+
+def test_a_trunk_is_never_one_flat_colour():
+ """New here. Every effect in this library has to carry hue VARIANCE, and a
+ trunk is the surface a camera gets closest to. The drift is read off the
+ same field as the grain, very coarsely, so it follows the trunk instead of
+ spotting it — and the moss in the cracks takes the same drift."""
+ out = measure(_COMPILE + """
+import * as THREE from 'three';
+import { patchBark } from './lib/woodland.js';
+const m = new THREE.MeshStandardMaterial();
+patchBark(m, {});
+const fs = compile(m).fragmentShader.replace(/\\s+/g, ' ');
+console.log(JSON.stringify({
+ // warm on one channel, cool on the other: a value ramp is not a hue
+ drift: / bkDr = astraBarkFbm\\(bkQ \\* 0\\.\\d+/.test(fs),
+ tintDrifts: /uBarkTint \\* vec3\\(1\\.0 \\+ bkDr[^)]*1\\.0 - bkDr/.test(fs),
+ mossDrifts: /uBarkMossColor \\* \\(1\\.0 \\+ bkDr/.test(fs),
+}));
+""", _LIBS)
+ assert out["drift"], "no coarse colour field on the trunk"
+ assert out["tintDrifts"], "the drift does not move the HUE, only the value"
+ assert out["mossDrifts"], "the moss is one flat green cushion"
+
+
+def test_imposters_are_one_draw_call_seated_on_the_ground():
+ """A forest of imposters that costs a draw call each has bought nothing.
+ And a card floating off the terrain is worse than the real tree it
+ replaced."""
+ out = measure("""
+import { makeImposters } from './lib/woodland.js';
+const bed = (x, z) => 2 + Math.sin(x * 0.2) + Math.cos(z * 0.15);
+const g = makeImposters({ count: 60, extent: 30, heightAt: bed, seed: 4 });
+let meshes = 0, instanced = 0, sphere = null, worstFoot = 0, n = 0;
+let contained = true;
+g.traverse((o) => {
+ if (!o.isMesh) return;
+ meshes++;
+ const geo = o.geometry;
+ if (geo.instanceCount || o.isInstancedMesh) instanced++;
+ const s = geo.boundingSphere;
+ if (s) sphere = s.radius;
+ const p = geo.getAttribute('aPos') || geo.getAttribute('aOff');
+ if (!p) return;
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i), y = p.getY(i), z = p.getZ(i);
+ worstFoot = Math.max(worstFoot, Math.abs(y - bed(x, z)));
+ n++;
+ if (!s) continue;
+ // CONTAINMENT, not a small number: a tidy radius about the wrong
+ // centre culls the field off-screen.
+ const dx = x - s.center.x, dy = y - s.center.y, dz = z - s.center.z;
+ if (Math.sqrt(dx * dx + dy * dy + dz * dz) > s.radius) contained = false;
+ }
+});
+console.log(JSON.stringify({ meshes, instanced, sphere, worstFoot, n,
+ contained }));
+""", _LIBS)
+ assert out["meshes"] == 1, f"{out['meshes']} draw calls for one field"
+ assert out["instanced"] == 1, "the field is not instanced"
+ assert out["contained"], (
+ "the stated sphere does not cover every card: three culls by this "
+ "sphere and by nothing else, because position is all zeros")
+ assert out["sphere"] and out["sphere"] < 1e3, (
+ "the field states no real radius; the 10 km default frames a "
+ "kilometre of empty air")
+ assert out["n"] and out["worstFoot"] < 0.35, (
+ f"an imposter floats {out['worstFoot']:.2f} m off the bed")
+
+
+def test_the_field_is_kept_out_of_the_occlusion_pass():
+ """GTAOPass redraws with an opaque override material, where a transparent
+ card is a solid wall — 50/255 of false darkening — and a billboard tree
+ casting its card's shadow is worse still."""
+ out = measure("""
+import { makeImposters } from './lib/woodland.js';
+const g = makeImposters({ count: 20, extent: 10, seed: 2 });
+const bad = [];
+g.traverse((o) => {
+ if (!o.isMesh) return;
+ if (!o.userData.astraNoOverride) bad.push(o.name + ':unguarded');
+ if (o.castShadow) bad.push(o.name + ':castShadow');
+});
+console.log(JSON.stringify({ bad }));
+""", _LIBS)
+ assert not out["bad"], out["bad"]
+
+
+def test_the_cards_take_coverage_not_blending():
+ """New here. The whole field is ONE draw call, so the cards are not sorted
+ against each other: a blended card resolved its antialiased edge against
+ whatever was already in the buffer — the sky — and then wrote depth, so the
+ card behind it never filled that pixel in. The result was a pale halo
+ traced round every silhouette with another card behind it (2.5 per mille of
+ the treeline band; 0.9 after). Alpha-to-coverage decides per MSAA sample
+ instead, which this renderer has, and moves the field into the opaque
+ queue where it is depth-sorted for free."""
+ out = measure("""
+import { makeImposters } from './lib/woodland.js';
+const g = makeImposters({ count: 12, extent: 10, seed: 1 });
+let m = null;
+g.traverse((o) => { if (o.isMesh) m = o.material; });
+console.log(JSON.stringify({
+ transparent: m.transparent,
+ a2c: !!m.alphaToCoverage,
+ depthWrite: m.depthWrite,
+ // the hard drop is still there for the pixels coverage would waste
+ discards: /discard/.test(m.fragmentShader),
+}));
+""", _LIBS)
+ assert out["a2c"], "no alpha-to-coverage: the silhouettes keep their halo"
+ assert not out["transparent"], (
+ "a blended card in a single unsorted draw call resolves against the "
+ "sky and then writes depth")
+ assert out["depthWrite"], "a card that writes no depth is behind the wood"
+ assert out["discards"], "the empty corners of the quad are still drawn"
+
+
+def test_a_card_is_lit_by_the_scene_it_stands_in():
+ """New here, and it is the port's biggest change. A card does its own
+ lighting — no normals three can light, no place in the shadow map — so the
+ only thing that makes the far field belong to the near one is being handed
+ the same irradiance. The reference's constants (0xfff0d6 * 3.0 and
+ 0x9fb2c4 * 0.85) were graded for another exposure and another post chain;
+ on our rig they put a MIDNIGHT treeline at 1.54x the luminance of the real
+ crown standing in it — a daylight wood under a moon. Reading the rig,
+ environment bake included, that is 0.82."""
+ out = measure("""
+import * as THREE from 'three';
+import { sunRig } from './lib/environment.js';
+import { makeImposters } from './lib/woodland.js';
+const lit = (rig) => {
+ const g = makeImposters({ count: 8, extent: 10, seed: 1, rig });
+ let m = null;
+ g.traverse((o) => { if (o.isMesh) m = o.material; });
+ const lum = (c) => 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
+ return {
+ sun: lum(m.uniforms.uImpSunColor.value),
+ amb: lum(m.uniforms.uImpAmbient.value),
+ dir: m.uniforms.uImpSun.value.toArray().map((v) => +v.toFixed(3)),
+ };
+};
+const day = sunRig({ azimuth: 215, elevation: 38 });
+const night = sunRig({ azimuth: 215, elevation: -20 });
+const bare = makeImposters({ count: 8, extent: 10, seed: 1 });
+let bm = null;
+bare.traverse((o) => { if (o.isMesh) bm = o.material; });
+console.log(JSON.stringify({
+ day: lit(day), night: lit(night),
+ dayDir: day.sunDir.toArray().map((v) => +v.toFixed(3)),
+ bareSun: bm.uniforms.uImpSunColor.value.toArray()
+ .map((v) => +v.toFixed(3)),
+ bareAmb: (() => { const c = bm.uniforms.uImpAmbient.value;
+ return 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b; })(),
+ // an explicit value still wins over the rig
+ override: (() => {
+ const g = makeImposters({ count: 4, extent: 5, rig: day,
+ ambient: 0x000000 });
+ let m = null;
+ g.traverse((o) => { if (o.isMesh) m = o.material; });
+ return m.uniforms.uImpAmbient.value.toArray();
+ })(),
+}));
+""", ("shader.js", "noise.js", "grass.js", "environment.js", "sky.js",
+ "woodland.js"))
+ assert out["day"]["dir"] == out["dayDir"], (
+ "the cards are lit from somewhere other than the rig's own sun")
+ # Night is a moon rig: dimmer key AND a far dimmer indirect.
+ assert out["night"]["sun"] < out["day"]["sun"] * 0.5, (
+ "the moon lights the cards as hard as the sun does")
+ assert out["night"]["amb"] < out["day"]["amb"] * 0.2, (
+ "the night treeline keeps its daylight sky")
+ assert out["night"]["amb"] > 0, "nothing reaches the cards at night"
+ # The fallback is this renderer's own daylight, not the reference's.
+ assert out["bareSun"][0] > 4.0, (
+ f"the no-rig default sun is {out['bareSun']}, which is not the "
+ "irradiance this renderer's day rig delivers")
+ assert 0.7 < out["bareAmb"] / out["day"]["amb"] < 1.4, (
+ "the no-rig default and the day rig disagree about the indirect, so "
+ "forgetting `rig` in daylight silently regrades the far field")
+ assert out["override"] == [0, 0, 0], "an explicit ambient is ignored"
+
+
+def test_a_backlit_card_is_a_mass_and_not_a_lit_flat():
+ """New here. The bowed normal sweeps radially across the card, so half of
+ every card faces the sun whichever way the stand is turned — including when
+ the sun is BEHIND the mass and the visible half of a real crown is in its
+ own shadow. Measured against a real crown of the same albedo at the same
+ distance: 1.41x, which is what a treeline pasted on with scissors looks
+ like. The card now knows which side of itself the sun is on (world space,
+ so both quads of a cross agree), turns the direct term down when it is
+ behind, and spends it on transmission through the thin edge instead."""
+ out = measure("""
+import { makeImposters } from './lib/woodland.js';
+const g = makeImposters({ count: 8, extent: 10, seed: 1 });
+let m = null;
+g.traverse((o) => { if (o.isMesh) m = o.material; });
+const vs = m.vertexShader.replace(/\\s+/g, ' ');
+const fs = m.fragmentShader.replace(/\\s+/g, ' ');
+console.log(JSON.stringify({
+ // computed against the eye in WORLD space, not against the card's quad
+ sunSide: /sunSide = dot\\(uImpSun, normalize\\(cameraPosition - wPos\\)\\)/
+ .test(vs),
+ carried: /vImpVar = vec4\\(/.test(vs),
+ damps: /iNdL \\*= mix\\(0\\.\\d+, 1\\.0, smoothstep\\([^)]*vImpVar\\.w\\)\\)/
+ .test(fs),
+ transmits: /iTrans = uImpSunColor/.test(fs)
+ && /iBack = smoothstep\\([^)]*vImpVar\\.w\\)/.test(fs),
+ occludes: /iAO = max\\(/.test(fs) && /uImpAmbient \\* iAO/.test(fs),
+ // and the mass is broken up rather than painted flat
+ clumps: /iMass = astraFbm2/.test(fs),
+ hueVaries: /iAlb = astraHueBreak\\(/.test(fs),
+}));
+""", _LIBS)
+ for k, why in (
+ ("sunSide", "the card cannot tell a backlit stand from a lit one"),
+ ("carried", "the sun side never reaches the fragment stage"),
+ ("damps", "a backlit card keeps its full direct sun term"),
+ ("transmits", "a backlit crown is a black cut-out"),
+ ("occludes", "the crown's interior sees the whole sky"),
+ ("clumps", "the crown is one flat mass"),
+ ("hueVaries", "one hue over a whole crown"),
+ ):
+ assert out[k], why
+
+
+def test_one_seed_grows_the_same_wood_twice():
+ out = measure("""
+import { makeImposters } from './lib/woodland.js';
+const shape = (seed) => {
+ const g = makeImposters({ count: 40, extent: 20, seed });
+ const v = [];
+ g.traverse((o) => {
+ if (!o.isMesh) return;
+ for (const [k, a] of Object.entries(o.geometry.attributes)) {
+ let s = 0;
+ for (let i = 0; i < a.count; i += 3) s += a.getX(i);
+ v.push(k + ':' + s.toFixed(4));
+ }
+ });
+ return v.join('|');
+};
+console.log(JSON.stringify({
+ same: shape(5) === shape(5),
+ differs: shape(5) !== shape(9),
+}));
+""", _LIBS)
+ assert out["same"] and out["differs"]
+
+# A FOGGED, shadow-casting scene: `USE_FOG` and the shadow branches only exist
+# in a program built from one, and a patch that drops a chunk compiles fine in
+# an unfogged fixture and renders as a sticker in a real scene.
+_COMPILE_SCENE = """
+import * as THREE from 'three';
+import { tickShaders } from './lib/shader.js';
+import { patchBark, makeImposters } from './lib/woodland.js';
+
+export const BOUNDS = { min: [-30, 0, -30], max: [30, 20, 30] };
+export function heightAt(x, z) { return Math.sin(x * 0.1) * 0.3; }
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ scene.fog = new THREE.FogExp2(0xcfd8e6, 0.004);
+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 1.0));
+ const sun = new THREE.DirectionalLight(0xffffff, 3);
+ sun.position.set(10, 20, 10); sun.castShadow = true; scene.add(sun);
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(80, 80),
+ new THREE.MeshStandardMaterial({ color: 0x6d6a52 }));
+ ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground);
+ const bark = new THREE.MeshStandardMaterial({ color: 0x6b5540 });
+ patchBark(bark, { kind: 'oak' });
+ const stem = new THREE.CylinderGeometry(0.3, 0.45, 6, 12);
+ stem.translate(0, 3, 0);
+ const trunk = new THREE.Mesh(stem, bark);
+ trunk.castShadow = true; scene.add(trunk);
+ scene.add(makeImposters({ count: 60, extent: 40, heightAt }));
+ return {
+ scene,
+ cameras: [{ name: 'a', position: [12, 5, 14], lookAt: [0, 2, 0], fov: 45 }],
+ update(t) { tickShaders(scene, t); },
+ };
+}
+"""
+
+
+def test_every_program_compiles_on_the_gpu():
+ """A patched built-in (bark) and a billboard sheet that must face the camera
+ from its vertex stage, in one scene: the two halves of this module build
+ different programs and both have to survive the fog and shadow chunks.
+
+ The reference had this case and the port dropped it: `_probe.shader_check`
+ staged only `src/fixture.js` while `check_shaders.mjs` boots the workspace's
+ `src/scene.js`, so it could never run. `_probe.compile_scene` stages the
+ scene, so the case is back (consolidation, 2026-09-01)."""
+ code, out = compile_scene(_COMPILE_SCENE, _LIBS)
+ assert code == 0, out
+ assert "ERROR" not in out, out