Official Codebase of 3DCodeVerse
Python
tests: the ten patch libraries share one name check and one GPU compile
gaoypeng14c3aa10a6a4
diff --git a/harness/tests/scene_runtime/lib/_probe.py b/harness/tests/scene_runtime/lib/_probe.pyindex c6fd234e..3bd91a69 100644--- a/harness/tests/scene_runtime/lib/_probe.py+++ b/harness/tests/scene_runtime/lib/_probe.py@@ -6,11 +6,17 @@ maps ``three`` / ``three/addons/*`` to the harness's own install), in a privatedir holding a copy of the library — never a live workspace. ``measure`` returns theLAST stdout line of the probe as JSON; ``compile_scene`` compiles every program afixture scene builds through ``runtime_js/check_shaders.mjs`` (headless GPU).++The readers every patch test shares live here too, once: ``SHADER_JS`` (the+two hooks patchStandard injects into, and ``compile`` / ``count`` / ``mains`` /+``locals`` over what comes back) and, on the Python side, ``_find`` and+``_main_body`` under the names the patch tests always called them by."""from __future__ import annotationsimport jsonimport os+import reimport shutilimport subprocessimport tempfile@@ -25,6 +31,43 @@ NODE_MODULES = HARNESS / "runtime_js" / "node_modules"pytestmark = pytest.mark.node+# 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:+# `compile(mat)` runs a material's onBeforeCompile over it, `count` counts a+# needle (a string or a RegExp), and `locals(mains(sh))` lists what the+# injected bodies declare inside main() in both stages.+SHADER_JS = """+const fake = () => ({+ vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',+ fragmentShader: 'void main() {\\n#include <color_fragment>\\n}',+ uniforms: {},+});+function compile(mat) {+ const shader = fake();+ mat.onBeforeCompile(shader);+ return shader;+}+const count = (src, needle) => src.split(needle).length - 1;+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 _find(pattern: str, src: str) -> re.Match:+ """``re.search`` that fails naming the pattern and the source it missed."""+ m = re.search(pattern, src)+ assert m, f"{pattern} not in\n{src}"+ return m+++def _main_body(src: str) -> str:+ """The shader from ``void main`` on: where the patch bodies land."""+ return src[src.index("void main"):]+def _three_ready() -> None:if not (NODE_MODULES / "three" / "package.json").is_file():@@ -60,6 +103,7 @@ def measure(script: str, libs: tuple[str, ...] = (), *, timeout_s: float = 120.0def compile_scene(scene_src: str, libs: tuple[str, ...] = (), *,extra: dict[str, str] | None = None,audit_module: str | None = None,+ report: Path | None = None,timeout_s: float = 180.0) -> tuple[int, str]:"""Compile every program a fixture SCENE builds, on the headless GPU.@@ -78,6 +122,10 @@ def compile_scene(scene_src: str, libs: tuple[str, ...] = (), *,undeclared/unbound pair on GLSL that is correct. ``src/lib/`` is alreadyexempt for that reason (``shader_report.mjs``); a fixture is not.+ ``report`` also writes the WHOLE JSON report to that path: the output+ returned is cut to its last 4000 characters, and a scene with many+ programs can overrun that before its report line even starts.+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@@ -95,7 +143,8 @@ def compile_scene(scene_src: str, libs: tuple[str, ...] = (), *,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 []),+ + (["--module", audit_module] if audit_module else [])+ + (["--out", str(report)] if report else []),capture_output=True, text=True, timeout=timeout_s + 30, cwd=str(HARNESS / "runtime_js"),env={**os.environ, "NODE_PATH": str(NODE_MODULES)},)diff --git a/harness/tests/scene_runtime/lib/test_accumulation.py b/harness/tests/scene_runtime/lib/test_accumulation.pyindex 66b1c99c..e8b01cb8 100644--- a/harness/tests/scene_runtime/lib/test_accumulation.py+++ b/harness/tests/scene_runtime/lib/test_accumulation.py@@ -18,9 +18,10 @@ 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.+convex edge sheds, sand ripples square to the wind. The names, and the whole+five-patch stack on a GPU (the only witness that the USE_INSTANCING branch+compiles at all), are asserted with every sibling library's in+test_patch_union.py.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@@ -33,170 +34,28 @@ by up to 21%, with the melt hole printed through the wall behind it)."""from __future__ import annotations-import jsonimport mathimport re-from collections import Counterimport pytest-from _probe import LIB_DIR, compile_scene, measure+from _probe import LIB_DIR, SHADER_JS, _find, _main_body, measurepytestmark = pytest.mark.node-_LIBS = ("shader.js", "terrain_shade.js", "waterside.js", "surface_wear.js",- "aging.js", "accumulation.js")+_LIBS = ("shader.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 = """+_PRELUDE = SHADER_JS + """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';+import { patchMicroBreakup } from './lib/surface_wear.js';+import { 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() {} };-}"""@@ -204,46 +63,6 @@ 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 bankof the other meet on the same ground in any half-thawed scene.@@ -502,83 +321,6 @@ console.log(JSON.stringify({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 keydecides the GLSL every material sharing it gets. Two materials that differdiff --git a/harness/tests/scene_runtime/lib/test_aging.py b/harness/tests/scene_runtime/lib/test_aging.pyindex 94ab29e4..963ad10d 100644--- a/harness/tests/scene_runtime/lib/test_aging.py+++ b/harness/tests/scene_runtime/lib/test_aging.py@@ -13,144 +13,29 @@ and a waterline. `patchStandard` absorbs a duplicate uniform SILENTLY (thesecond declaration is dropped and that patch then reads whatever its neighbourset) while a duplicate local inside main is a compile error, so the sharedcontract is asserted first: one world base, no name any neighbour owns, every-option a uniform rather than baked GLSL.+option a uniform rather than baked GLSL. (The names, and the whole stack on+a GPU, are asserted with every sibling library's in test_patch_union.py.)"""from __future__ import annotations-import json-import re-from collections import Counter-import pytest-from _probe import LIB_DIR, compile_scene, measure+from _probe import LIB_DIR, SHADER_JS, _find, _main_body, measurepytestmark = pytest.mark.node-_LIBS = ("shader.js", "terrain_shade.js", "waterside.js", "surface_wear.js",- "aging.js")+_LIBS = ("shader.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 = """+_PRELUDE = SHADER_JS + """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';+import { patchMicroBreakup } from './lib/surface_wear.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() {},- };-}"""@@ -158,47 +43,6 @@ 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 butnever dusts is half a wall. patchStandard chains them, but it repeats@@ -245,76 +89,6 @@ console.log(JSON.stringify({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 andsmear a pipe; an object-space axis would tilt with the mesh. So the fielddiff --git a/harness/tests/scene_runtime/lib/test_caustics.py b/harness/tests/scene_runtime/lib/test_caustics.pyindex 2b0247f8..d17df99f 100644--- a/harness/tests/scene_runtime/lib/test_caustics.py+++ b/harness/tests/scene_runtime/lib/test_caustics.py@@ -10,8 +10,9 @@ emissive term caps the net at the light the surface already gets, so itvanishes exactly where a pool is interesting; and a net whose peaks runpast what the tone map holds comes out of ACES as flat white — thebrightest 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.+These pin the source that avoids that; that its names collide with no+sibling library's, and that the real chain compiles on the real renderer,+are asserted with every sibling's in test_patch_union.py.Ported 2026-09-01 from the scene_multifile_graphics reference test. Theassertions about THEIR renderer contract are gone; the colour half (a@@ -22,31 +23,14 @@ from __future__ import annotationsimport re-from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure # noqa: F401+from tests.scene_runtime.lib._probe import LIB_DIR, SHADER_JS, measure-_LIBS = ("shader.js", "caustics.js", "waterside.js", "terrain_shade.js",- "surface_wear.js")+_LIBS = ("shader.js", "caustics.js", "waterside.js", "terrain_shade.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)+ return measure(SHADER_JS + script, _LIBS)def test_the_net_is_ridged_interference_not_one_noise_call():@@ -441,49 +425,6 @@ console.log(JSON.stringify({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 rockprojection, the waterline and this at once. patchStandard chains by@@ -506,7 +447,6 @@ patchCaustics(m, { level: 1.2, seed: 4 });patchCaustics(m, { level: 1.4, seed: 4 }); // retune, not a 4th patchm.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({@@ -586,121 +526,3 @@ console.log(JSON.stringify({# One export: the library is the net, nothing else.assert src.count("\nexport ") == 1assert 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 outdiff --git a/harness/tests/scene_runtime/lib/test_damp.py b/harness/tests/scene_runtime/lib/test_damp.pyindex 2c033e7a..e5f30b7a 100644--- a/harness/tests/scene_runtime/lib/test_damp.py+++ b/harness/tests/scene_runtime/lib/test_damp.py@@ -23,21 +23,21 @@ These three patches land on materials that already carry a triplanar, a microbreakup and a waterline, so the shared contract is asserted first: one worldbase, 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).+key fixes the GLSL for every material sharing it). The names, and the+whole six-patch stack on a GPU, are asserted with every sibling library's in+test_patch_union.py."""from __future__ import annotations-import jsonimport re-from collections import Counterimport pytest-from _probe import LIB_DIR, compile_scene, measure+from _probe import LIB_DIR, SHADER_JS, _find, _main_body, measurepytestmark = pytest.mark.node_LIBS = ("shader.js", "terrain_shade.js", "waterside.js", "surface_wear.js",- "aging.js", "accumulation.js", "strata.js", "damp.js")+ "aging.js", "accumulation.js", "damp.js")_LIB_SRC = (LIB_DIR / "damp.js").read_text(encoding="utf-8")@@ -48,32 +48,18 @@ _LIB_SRC = (LIB_DIR / "damp.js").read_text(encoding="utf-8")# 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 = """+_PRELUDE = SHADER_JS + """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';+import { patchMicroBreakup } from './lib/surface_wear.js';+import { patchTriplanar } from './lib/terrain_shade.js';+import { patchShoreWet } from './lib/waterside.js';+import { patchDust } from './lib/aging.js';+import { patchSnow } from './lib/accumulation.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`. */@@ -110,196 +96,11 @@ function run(code, 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: ashore bed is mossy at its edge, damp across its apron and cracked in its@@ -802,101 +603,6 @@ console.log(JSON.stringify({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 keydecides the GLSL every material sharing it gets. Two materials that differdiff --git a/harness/tests/scene_runtime/lib/test_foliage_shade.py b/harness/tests/scene_runtime/lib/test_foliage_shade.pyindex cbecf082..1f1f4dfc 100644--- a/harness/tests/scene_runtime/lib/test_foliage_shade.py+++ b/harness/tests/scene_runtime/lib/test_foliage_shade.py@@ -22,7 +22,7 @@ from __future__ import annotationsimport jsonimport re-from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure+from tests.scene_runtime.lib._probe import LIB_DIR, SHADER_JS, _find, compile_scene, measure_LIBS = ("shader.js", "foliage_shade.js")@@ -30,22 +30,12 @@ _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 = """+_PRELUDE = SHADER_JS + """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@@ -125,12 +115,6 @@ 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 termis a dot against the NEGATED sun so it peaks when the eye looks into the@@ -445,7 +429,6 @@ 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(),diff --git a/harness/tests/scene_runtime/lib/test_patch_union.py b/harness/tests/scene_runtime/lib/test_patch_union.pynew file mode 100644index 00000000..9af5a7c0--- /dev/null+++ b/harness/tests/scene_runtime/lib/test_patch_union.py@@ -0,0 +1,342 @@+"""The ten surface-patch libraries on ONE material: the names each owns, and+every chain of them on the real renderer.++terrain_shade, waterside, surface_wear, aging, accumulation, strata, damp,+roadway, caustics and submerged are written to land on the same materials —+a submerged, weathered, splatted bank wears half of them at once — and+`patchStandard` chains whatever it is handed. Every way that goes wrong is+silent or far from its cause. patchStandard DROPS a repeated uniform or+varying and keeps the first, so a name two libraries share leaves one patch+reading the other's value with nothing reported; a helper two libraries both+define is deduped while the bodies match and THROWS the day either is edited;+a main() local two bodies both declare is a redefinition that takes the whole+material down; and a chain that compiles in one order, one variant or next+to one neighbour only is a scene that renders black the day an author picks+another.++Each library's own suite pins its physics. This file holds the two claims+about all ten at once. Consolidated 2026-09-22 from eight per-file+"no patch declares a name its neighbours own" tests, which between them+checked the uniforms of 31 of the 45 library pairs, and from eleven per-file+GPU scenes that each compiled one library's own chain.+"""+from __future__ import annotations++import itertools+import json+import re+from collections import Counter++import pytest++from tests.scene_runtime.lib._probe import (+ LIB_DIR,+ SHADER_JS,+ _find,+ _main_body,+ compile_scene,+ measure,+)++pytestmark = pytest.mark.node++# The ten, and the patches each ships.+LIBRARIES: dict[str, tuple[str, ...]] = {+ "terrain_shade.js": ("patchTriplanar", "patchSlopeSplat"),+ "waterside.js": ("patchShoreWet", "patchShoreFoam", "patchShallowWater"),+ "surface_wear.js": ("patchMicroBreakup", "patchEdgeWear"),+ "aging.js": ("patchDripStains", "patchRust", "patchDust"),+ "accumulation.js": ("patchSnow", "patchSand"),+ "strata.js": ("patchRockStrata", "patchErosionStreaks"),+ "damp.js": ("patchMoss", "patchMoisture", "patchCrackedMud"),+ "roadway.js": ("patchRoadSurface", "patchSeamBand", "patchTracks"),+ "caustics.js": ("patchCaustics",),+ "submerged.js": ("patchUnderwater", "patchThinIce"),+}+ALL = [p for patches in LIBRARIES.values() for p in patches]++# Shared ON PURPOSE: the clock tickShaders drives, and the one world+# position / normal pair every library's base writes (shader.js+# WORLD_VARYINGS), so a material wearing several declares ONE.+SHARED = {"uniform": {"uTime"}, "varying": {"vAstraWorld", "vAstraWorldN"}}++# The spelling each library's own suite pinned, so a name added later stays+# inside its library rather than merely missing today's neighbours.+SPELLING = {+ "caustics.js": {"uniform": ("uCau",), "local": ("cau",)},+ "submerged.js": {"uniform": ("uSub", "uIce"), "local": ("sub", "ice"),+ "helper": ("astraIce",)},+ "strata.js": {"helper": ("astraStrata",)},+ "roadway.js": {"helper": ("astraRoad",)},+}++# Every patch at its defaults, but the splat's snow line pulled into frame+# so its snow branch is live code. Shared by the probe and the scene.+_APPLY_JS = "\n".join(+ f"import {{ {', '.join(patches)} }} from './lib/{lib}';"+ for lib, patches in LIBRARIES.items()) + """+const LIBS = """ + json.dumps({lib: list(p) for lib, p in LIBRARIES.items()}) + """;+const PATCH = { """ + ", ".join(ALL) + """ };+const OPTS = { patchSlopeSplat: { snowLine: 30 } };+const apply = (m, names) => {+ for (const n of names) PATCH[n](m, OPTS[n] || {});+ return m;+};+const ALL = Object.values(LIBS).flat();+"""++# What a head or a body declares, by kind (the return types are the set+# patchStandard's own duplicate-helper check reads).+_TYPE = r"(?:void|float|u?int|bool|[biu]?vec[234]|mat[234](?:x[234])?)"+_HELPER = re.compile(r"^\s*(?:(?:lowp|mediump|highp)\s+)?" + _TYPE + r"\s+(\w+)\s*\(", re.M)+_LOCAL = re.compile(r"^\s*(?:const\s+)?(?:(?:lowp|mediump|highp)\s+)?"+ r"(?:float|u?int|bool|[biu]?vec[234]|mat[234])\s+(\w+)\s*[=;,\[]", re.M)+_VARYING = re.compile(r"^\s*varying\s+(?:(?:lowp|mediump|highp)\s+)?\w+\s+(\w+)\s*;", re.M)+_DECL = re.compile(r"^\s*(?:uniform|varying)\s+(?:(?:lowp|mediump|highp)\s+)?\w+\s+(\w+)", re.M)+++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_no_library_declares_a_name_another_owns():+ """All 45 pairs, both stages, four kinds of name — each library compiled+ ALONE, so a clash is caught however the two ever meet. Uniforms by the+ keys patchStandard merges (the map it dedupes silently), varyings and+ helpers by the heads, locals by what the bodies declare inside main().++ Then every chain at once, forward and reversed: no declaration, helper+ or main() local may appear twice in either stage. And each library's+ vertex stage is its world base and no more: the point and normal it+ writes fold in `instanceMatrix` (the vertex hook runs before+ <project_vertex>, so without it every copy of a scattered rock shades+ from the mesh ORIGIN), three declares that attribute itself, nothing+ fragment-only is called there (the util block ships in both stages, so+ fwidth and astraStroke may be DEFINED in it, never called), and nothing+ displaces `transformed`, or a hard-edged bed would tear open at its rim."""+ out = measure(SHADER_JS + """+import * as THREE from 'three';+import { GLSL_UTIL } from './lib/shader.js';+""" + _APPLY_JS + """+const std = () => new THREE.MeshStandardMaterial({ color: 0x8b8478, roughness: 0.7 });+const per = {};+for (const [lib, names] of Object.entries(LIBS)) {+ const m = apply(std(), names);+ const s = compile(m);+ per[lib] = { uniforms: Object.keys(m.userData.uniforms),+ vs: s.vertexShader, fs: s.fragmentShader };+}+const union = (names) => {+ const s = compile(apply(std(), names));+ return { vs: s.vertexShader, fs: s.fragmentShader };+};+console.log(JSON.stringify({ per, util: GLSL_UTIL, forward: union(ALL),+ reversed: union(ALL.slice().reverse()) }));+""", tuple(LIBRARIES))+ util = set(_HELPER.findall(out["util"]))+ owns = {}+ for lib, got in out["per"].items():+ vs, fs = got["vs"], got["fs"]+ heads = vs[:vs.index("void main")] + fs[:fs.index("void main")]+ owns[lib] = {+ "uniform": set(got["uniforms"]) - SHARED["uniform"],+ "varying": set(_VARYING.findall(vs + fs)) - SHARED["varying"],+ "helper": set(_HELPER.findall(heads)) - util,+ "local": set(_LOCAL.findall(_main_body(vs) + _main_body(fs))),+ }+ # An empty set would make every pair below pass for nothing.+ assert owns[lib]["uniform"] and owns[lib]["local"], (lib, owns[lib])+ clashes = [f"{a} and {b} both declare the {kind}(s) {sorted(both)}"+ for (a, mine), (b, theirs) in itertools.combinations(owns.items(), 2)+ for kind in mine if (both := mine[kind] & theirs[kind])]+ assert not clashes, "\n".join(clashes)+ for lib, rules in SPELLING.items():+ for kind, stems in rules.items():+ names = owns[lib][kind]+ assert names, (lib, kind)+ stray = sorted(n for n in names if not n.startswith(stems))+ assert not stray, f"{lib}: {kind}(s) outside {stems}: {stray}"++ for order in ("forward", "reversed"):+ for stage in ("vs", "fs"):+ src = out[order][stage]+ for kind, found in (("declaration", _DECL.findall(src)),+ ("helper", _HELPER.findall(_unguarded(src))),+ ("main() local", _LOCAL.findall(_main_body(src)))):+ twice = sorted(n for n, c in Counter(found).items() if c > 1)+ assert not twice, f"{order} chain, {stage}: {kind}(s) {twice} twice"++ for lib, got in out["per"].items():+ vs, fs = got["vs"], got["fs"]+ body = _main_body(vs)+ p = _find(r"vAstraWorld = \(modelMatrix \* (\w+)\)\.xyz;", body).group(1)+ n = _find(r"vAstraWorldN = normalize\(\(modelMatrix \* vec4\((\w+), 0\.0\)\)\.xyz\);",+ body).group(1)+ assert "#ifdef USE_INSTANCING" in body, lib+ assert f"{p} = instanceMatrix * {p};" in body, (lib, p)+ assert f"{n} = mat3(instanceMatrix) * {n};" in body, (lib, n)+ assert "attribute mat4 instanceMatrix" not in vs, lib+ # A varying declared in one stage only is a link failure, and the+ # symptom is the patch simply not drawing.+ assert set(_VARYING.findall(vs)) == set(_VARYING.findall(fs)), lib+ assert SHARED["varying"] <= set(_VARYING.findall(vs)), lib+ called = [t for t in ("fwidth(", "dFdx(", "dFdy(", "astraStroke(") if t in body]+ assert not called and "gl_FragCoord" not in vs, (lib, called)+ assert not re.search(r"\btransformed\s*[-+*/]?=", body), lib+++# Every chain the scene compiles: (material name, patches, options, instances).+# Each patch ALONE: only that catches a body reading a uniform, helper or+# local that a sibling patch or another library declares, because every+# bigger chain supplies it. Then all of them on one material, forward and+# reversed (a body that reads what a LATER one declares fails one of the+# two) — the case terrain_shade's own two patches once failed together+# ('astraWp' redefinition, 'astraFbmUnit' already has a body: a dead+# material, found only when a sibling library landed on the same bank) —+# and across the variants that change the program: flat shading+# (three omits vNormal), instancing (the only compile of each base's+# USE_INSTANCING branch), transparency (three defines OPAQUE otherwise),+# maps with a bump map and vertex colours (three's own uv and colour+# varyings arrive), and `fog: false` — the fogless branch the waterline+# sheen falls back to, which in a fogged scene only a fogless material+# compiles. The variants share programs because each whole-chain program+# costs about a second and a half of ANGLE's time on this GPU.+MATERIALS: list[tuple[str, list[str], dict, int]] = [+ *((f"{name} alone", [name], {}, 0) for name in ALL),+ ("every patch", ALL, {}, 0),+ ("every patch, reversed, flat-shaded, instanced", ALL[::-1],+ {"flatShading": True}, 4),+ ("every patch, transparent, textured, unfogged", ALL,+ {"transparent": True, "opacity": 0.6, "textured": True, "fog": False}, 0),+]++# A workspace SCENE for check_shaders.mjs, which boots it through the host:+# fogged, 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); a sun that CASTS, or no program carries the+# shadow-map chunks; a camera, or the host reports the scene as not booted+# and never reaches the compile stage. Around the chains: terrain.js's+# ground and cliff wearing the splat and the triplanar as the terrain suite+# shipped them, and the rain rings, which assemble their OWN shader and so+# take their fog and depth chunks from makeShaderMaterial alone.+_SCENE = """+import * as THREE from 'three';+import { tickShaders } from './lib/shader.js';+import { ground, cliff } from './lib/terrain.js';+import { makeRainRings } from './lib/submerged.js';+""" + _APPLY_JS + """+const MATERIALS = """ + json.dumps(MATERIALS) + """;++export const BOUNDS = { min: [-40, 0, -40], max: [40, 30, 40] };++export function createScene({ renderer }) {+ // The report pins an error on the materials whose source holds the line+ // it quotes, and every chain here shares most of its lines. So each+ // material's cache key carries its own index, and the host's error hook+ // is wrapped to name the chain whose program did not link.+ const labels = [];+ const tag = (mat, label) => {+ const key = mat.customProgramCacheKey;+ const i = labels.push(label) - 1;+ mat.name = label;+ mat.customProgramCacheKey = () => key() + '#' + i;+ };+ const hook = renderer.debug.onShaderError;+ renderer.debug.onShaderError = (gl, program, ...rest) => {+ const p = renderer.info.programs.find((x) => x.program === program);+ const i = p && /#(\\d+)$/.exec(p.cacheKey);+ console.error('this chain did not link: ' + (i ? labels[i[1]] : p ? p.name : '?'));+ if (hook) hook(gl, program, ...rest);+ };++ 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 tex = new THREE.DataTexture(new Uint8Array([200, 190, 170, 255]), 1, 1);+ tex.colorSpace = THREE.SRGBColorSpace;+ tex.needsUpdate = true;+ MATERIALS.forEach(([label, names, o, count], i) => {+ const { textured, ...params } = o;+ const mat = new THREE.MeshStandardMaterial(Object.assign(+ { color: 0x8b8478, roughness: 0.7 }, params,+ textured ? { map: tex, bumpMap: tex, roughnessMap: tex, vertexColors: true } : {}));+ tag(apply(mat, names), label);+ const geo = new THREE.IcosahedronGeometry(0.6, 2);+ if (textured) {+ geo.setAttribute('color', new THREE.Float32BufferAttribute(+ new Array(geo.attributes.position.count * 3).fill(0.9), 3));+ }+ const mesh = count ? new THREE.InstancedMesh(geo, mat, count) : new THREE.Mesh(geo, mat);+ for (let k = 0; k < count; k++) {+ mesh.setMatrixAt(k, new THREE.Matrix4().makeTranslation(0, k * 1.3, 0));+ }+ mesh.position.set((i % 10) * 2 - 9, 0.6, Math.floor(i / 10) * 2 - 6);+ mesh.castShadow = mesh.receiveShadow = true;+ mesh.frustumCulled = false;+ scene.add(mesh);+ });++ let s = 7;+ const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);+ const land = ground({ size: 80, segments: 24, rand, relief: 10 });+ tag(patchSlopeSplat(land.mesh.material, { snowLine: 9, snowBand: 2.5 }),+ 'ground() with patchSlopeSplat');+ const wall = cliff({ length: 30, height: 12, rand });+ tag(patchTriplanar(wall.mesh.material, { scale: 3.5 }), 'cliff() with patchTriplanar');+ wall.mesh.position.set(0, 0, -20);+ scene.add(land.mesh, wall.mesh, makeRainRings({ count: 16 }));+ return {+ scene,+ cameras: [{ name: 'hero', position: [0, 16, 26], lookAt: [0, 1, 0], fov: 60 }],+ update(t) { tickShaders(scene, t); },+ };+}+"""+++def _library_line(glsl: str | None) -> str:+ """Where a quoted GLSL line lives in the library. The report maps a line+ back through template strings, and these libraries write their GLSL as+ arrays of quoted lines, which it cannot see."""+ needle = (glsl or "").strip()+ hits = [f"{lib}:{n}" for lib in (*LIBRARIES, "shader.js")+ for n, text in enumerate((LIB_DIR / lib).read_text(encoding="utf-8").splitlines(), 1)+ if len(needle) > 2 and needle in text]+ return " ".join(hits[:3]) or "(not a library line)"+++def test_every_chain_compiles_on_the_real_renderer(tmp_path):+ """The only witness that counts. Everything above reads strings; whether+ the GPU takes every chain of the ten — two dozen bodies in one main, each+ library's instancing branch, the fog and no-fog branches, flat and+ textured variants, a Voronoi with nested loops, a refract into a parallax+ — cannot be asserted from source, and a patch that does not compile is+ worth nothing. Runs the preflight the authoring agent runs, on our own+ renderer; a failure names the library line, the GLSL error and the chain+ whose program did not link."""+ report_path = tmp_path / "report.json"+ code, out = compile_scene(+ _SCENE, (*LIBRARIES, "terrain.js"), report=report_path)+ assert report_path.is_file(), out # the preflight itself died: `out` says why+ report = json.loads(report_path.read_text(encoding="utf-8"))+ problems = [f"{_library_line(e.get('source_line'))}: {e.get('message')}"+ for e in report["errors"]]+ problems += [f"{w.get('file')}: {w.get('message')}" for w in report["warnings"]]+ assert code == 0 and report["ok"] and not problems, "\n".join(problems) or out+ compiled = report["compile"]+ assert compiled["gpu"], "this claim is only worth a real GPU"+ # Every chain above is its own program (plus ground, cliff and rings):+ # a green exit on a compile that skipped them would prove nothing.+ assert compiled["custom_materials"] >= len(MATERIALS) + 3, compiled+ assert compiled["programs"] >= len(MATERIALS) + 3, compileddiff --git a/harness/tests/scene_runtime/lib/test_roadway.py b/harness/tests/scene_runtime/lib/test_roadway.pyindex 076be477..fe454f26 100644--- a/harness/tests/scene_runtime/lib/test_roadway.py+++ b/harness/tests/scene_runtime/lib/test_roadway.py@@ -6,7 +6,9 @@ frame shared by three patches, ruts along the ROAD's own axis and not a worldone, whole lanes so the wheel strips land on the road, a seam band bounded bythe width it was given, a track count and kind that are uniforms, nobodyassigning over the albedo they landed on, one seed one road, and every field-finer than its pixel faded out before it can alias.+finer than its pixel faded out before it can alias. No name a neighbour owns,+and the whole road stack on a GPU, are asserted with every sibling library's+in test_patch_union.py.THE PORT'S OWN LAW, and the regression this file exists to stop:@@ -29,154 +31,32 @@ drip line all back. Half this file's new assertions are that bound.from __future__ import annotations-import jsonimport re-from collections import Counterimport pytest-from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure+from tests.scene_runtime.lib._probe import LIB_DIR, SHADER_JS, _find, _main_body, measurepytestmark = pytest.mark.node_LIBS = ("shader.js", "noise.js", "materials.js", "terrain_shade.js",- "surface_wear.js", "aging.js", "accumulation.js", "strata.js",- "roadway.js")+ "surface_wear.js", "aging.js", "accumulation.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 = """+_PRELUDE = SHADER_JS + """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';+import { patchMicroBreakup } from './lib/surface_wear.js';+import { patchTriplanar } from './lib/terrain_shade.js';+import { patchDust } from './lib/aging.js';+import { patchSnow } from './lib/accumulation.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() {} };-}"""@@ -184,47 +64,6 @@ 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 itstops, and what drove over it — and patchStandard repeats whatever it is@@ -555,81 +394,6 @@ console.log(JSON.stringify({ fs: compile(m).vertexShader }));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 keydecides the GLSL every material sharing it gets. Two materials thatdiff --git a/harness/tests/scene_runtime/lib/test_strata.py b/harness/tests/scene_runtime/lib/test_strata.pyindex ed4c4187..a12ebff7 100644--- a/harness/tests/scene_runtime/lib/test_strata.py+++ b/harness/tests/scene_runtime/lib/test_strata.py@@ -16,8 +16,9 @@ cannot quietly undo them: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+shared contract is asserted first — one world base, no name a neighbour owns+(test_patch_union.py, with every sibling library and the whole stack on a+GPU), every option a uniform rather than baked GLSL — and then the geology. Twoclaims are checked by NUMBERS rather than by reading the source: the bedstack is walked with the shipped uniforms and the constants pulled out of thecompiled GLSL, because "thickness varies" and "two cliffs share one bedding@@ -25,44 +26,27 @@ plane" are statements about a sequence of metres and a regex sees neither."""from __future__ import annotations-import jsonimport re-from collections import Counterimport pytest-from _probe import LIB_DIR, compile_scene, measure+from _probe import LIB_DIR, SHADER_JS, _find, _main_body, measurepytestmark = pytest.mark.node-_LIBS = ("shader.js", "terrain_shade.js", "waterside.js", "surface_wear.js",- "aging.js", "strata.js")+_LIBS = ("shader.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 = """+_PRELUDE = SHADER_JS + """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';+import { patchMicroBreakup } from './lib/surface_wear.js';+import { patchDripStains } 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@@ -148,135 +132,11 @@ 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 isbedded but never streaked is half a cliff. patchStandard chains them,@@ -654,76 +514,6 @@ console.log(JSON.stringify({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 onlydiff --git a/harness/tests/scene_runtime/lib/test_submerged.py b/harness/tests/scene_runtime/lib/test_submerged.pyindex 51bc43df..3168ad27 100644--- a/harness/tests/scene_runtime/lib/test_submerged.py+++ b/harness/tests/scene_runtime/lib/test_submerged.py@@ -14,7 +14,8 @@ shared local takes the whole material down.Ported 2026-09-01 from the scene_multifile_graphics reference test. Theassertions 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+so the GPU pass is a scene of its own, test_patch_union.py's, which also+holds its names against every library it lands on). What is new is the colourhalf this host measured and this session added: the turbidity spectrum,the veil's dither and its ``light``, and the FRESNEL the ice interiornow sits behind.@@ -25,31 +26,15 @@ from __future__ import annotationsimport mathimport re-from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure # noqa: F401+from tests.scene_runtime.lib._probe import LIB_DIR, SHADER_JS, measure_LIBS = ("shader.js", "submerged.js", "caustics.js", "waterside.js",- "terrain_shade.js", "aging.js")+ "terrain_shade.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)+ return measure(SHADER_JS + script, _LIBS)def _approx(x):@@ -693,69 +678,6 @@ console.log(JSON.stringify({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.@@ -782,7 +704,6 @@ patchCaustics(m, { level: 1.2, depthFade: 2.8 });patchUnderwater(m, { level: 1.4, seed: 4 }); // retune, not a 5th patchm.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({@@ -892,128 +813,3 @@ console.log(JSON.stringify({for name in ("patchUnderwater", "makeRainRings", "patchThinIce"):assert "export function " + name in srcassert 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 outdiff --git a/harness/tests/scene_runtime/lib/test_surface_wear.py b/harness/tests/scene_runtime/lib/test_surface_wear.pyindex 4be71c05..3b7115c7 100644--- a/harness/tests/scene_runtime/lib/test_surface_wear.py+++ b/harness/tests/scene_runtime/lib/test_surface_wear.py@@ -6,7 +6,8 @@ shared world base, no name a neighbour already owns, every option a uniformrather than baked GLSL, one seed one surface, a hard bound on the albedoswing, a SIGNED curvature in 1/m for the edge route, and a gloss thatcomposes on the material because per-pixel roughness is unreachable from-<color_fragment>.+<color_fragment>. The names, and the stack with a triplanar on a GPU, are+asserted with every sibling library's in test_patch_union.py.THE PORT'S OWN LAWS, and the two regressions this file exists to stop.@@ -47,119 +48,24 @@ THE PORT'S OWN LAWS, and the two regressions this file exists to stop.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+from tests.scene_runtime.lib._probe import LIB_DIR, SHADER_JS, _find, _main_body, measurepytestmark = pytest.mark.node-_LIBS = ("shader.js", "terrain_shade.js", "waterside.js", "surface_wear.js")+_LIBS = ("shader.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 = """+_PRELUDE = SHADER_JS + """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() {},- };-}"""@@ -167,45 +73,6 @@ 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 thatvaries but has no worn edges is half the idea. patchStandard chains@@ -246,59 +113,6 @@ console.log(JSON.stringify({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 keydecides the GLSL every material sharing it gets. Two materials thatdiff --git a/harness/tests/scene_runtime/lib/test_terrain_shade.py b/harness/tests/scene_runtime/lib/test_terrain_shade.pyindex 43c2a5b5..84c48945 100644--- a/harness/tests/scene_runtime/lib/test_terrain_shade.py+++ b/harness/tests/scene_runtime/lib/test_terrain_shade.py@@ -24,27 +24,16 @@ argued in code:"""from __future__ import annotations-import jsonimport re-from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure # noqa: F401+from tests.scene_runtime.lib._probe import LIB_DIR, SHADER_JS, measure_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)+ return measure(SHADER_JS + script, _LIBS)def test_triplanar_projects_on_three_world_planes_and_reads_no_uv():@@ -393,116 +382,6 @@ def test_the_shipped_module_is_deterministic():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 onthe terrain the prompts recommend — triplanar for the rock, splatdiff --git a/harness/tests/scene_runtime/lib/test_waterside.py b/harness/tests/scene_runtime/lib/test_waterside.pyindex aaaa4000..989a0b03 100644--- a/harness/tests/scene_runtime/lib/test_waterside.py+++ b/harness/tests/scene_runtime/lib/test_waterside.py@@ -36,28 +36,17 @@ exposure 1.0, no post chain, baked environment) in the fx showcase:from __future__ import annotations-import json-import pytest-from _probe import LIB_DIR, compile_scene, measure+from _probe import LIB_DIR, SHADER_JS, measurepytestmark = 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)+ return measure(SHADER_JS + script, _LIBS)def test_the_wet_band_fades_above_the_line_instead_of_cutting_it():@@ -534,17 +523,10 @@ patchShallowWater(m, { bedLevel: -1 });patchShoreWet(m, { level: 0.5 }); // retune, not a fourth patchm.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;-}+const seen = {};+for (const name of locals(mains(sh))) seen[name] = (seen[name] || 0) + 1;console.log(JSON.stringify({key: m.customProgramCacheKey(),wet: fs.includes('uWetDark'),@@ -560,7 +542,7 @@ console.log(JSON.stringify({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),+ dupLocals: Object.keys(seen).filter((k) => seen[k] > 1),}));""")assert out["wet"] and out["foam"] and out["shallow"], out@@ -611,101 +593,3 @@ def test_the_shipped_module_is_deterministic_and_stage_safe():# Three exports, no more: the library is the contact transitions.assert src.count("\nexport ") == 3assert 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"], outdiff --git a/harness/tests/scene_runtime/lib/test_windows.py b/harness/tests/scene_runtime/lib/test_windows.pyindex 3ea76ea4..6f259074 100644--- a/harness/tests/scene_runtime/lib/test_windows.py+++ b/harness/tests/scene_runtime/lib/test_windows.py@@ -57,18 +57,13 @@ fx/out/windows/, looked at, and measured:from __future__ import annotations-from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure # noqa: F401+from tests.scene_runtime.lib._probe import LIB_DIR, SHADER_JS, compile_scene, measure_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: {},-});+# A fresh window-interior patch, run through the two hooks of SHADER_JS.+_PATCHED = """const patched = (opts) => {const sh = fake();patchWindowInteriors(new THREE.MeshStandardMaterial(), opts || {})@@ -80,7 +75,7 @@ const patched = (opts) => {_PRELUDE = """import * as THREE from 'three';import { patchWindowInteriors, makeNightWindows } from './lib/windows.js';-""" + _FAKE_SHADER+""" + SHADER_JS + _PATCHEDdef _measure(script: str, libs: tuple[str, ...] = _LIBS) -> dict: