Official Codebase of 3DCodeVerse
Python
spatial: the shader-presence / ablation instrument
gaoypeng68ede76f0aa8
diff --git a/harness/codeverse/spatial/ablation.py b/harness/codeverse/spatial/ablation.pynew file mode 100644index 00000000..af9e7094--- /dev/null+++ b/harness/codeverse/spatial/ablation.py@@ -0,0 +1,246 @@+"""Effect-presence measurement for ``scene_threejs``: what fraction of the+delivered frame the scene's custom shaders actually paint.++The scene track can already tell whether a shader COMPILES (``check_shaders``)+and how many custom materials exist (``census.custom_materials``). Neither+answers the question the graphics work is actually about: is the effect in the+picture? A shader that is behind the camera, occluded, alpha-zero or quietly+replaced by a flat material after one compiler error passes both checks and+delivers nothing.++The answer is a counterfactual, measured in code (law 3): render each camera as+authored, and again with every ShaderMaterial / ``onBeforeCompile`` patch+replaced by a neutral material of the same base colour, and diff the pixels.+Zero change means the effect is not there. Per material — leave one out at a+time — the same diff says WHICH shader carries the picture.++Reproducibility, measured on the starter scene: bit-identical within one process+(three runs, same fractions, same PNG hashes) and stable to ~1e-4 across separate+browser contexts (one camera moved 0.3820 -> 0.3819, 14 pixels of 147 456) — two+orders of magnitude under ``PRESENT_FLOOR``, so no verdict turns on it.++``ablate_scene(ws)`` drives ``runtime_js/ablate_scene.mjs`` (page-side logic in+``runtime_js/lib/host_ablation.mjs``) and returns a typed+:class:`AblationReport`; ``merge_into_census`` folds the compact form into+``artifacts/census.json`` under ``effect_ablation``, where the gates, the judge+context and the agent's own ``check_placement``-style reads already look.+"""++from __future__ import annotations++import json+import time+from collections.abc import Sequence+from pathlib import Path+from typing import Any++from pydantic import BaseModel, Field++from codeverse.contracts.plan import CameraPlan+from codeverse.proc import read_json_or_none+from codeverse.spatial.render_scene import SceneRenderError, run_scene_script+from codeverse.workspace import Workspace++#: census.json key the compact report lands under+CENSUS_FIELD = "effect_ablation"+#: mid-phase of the animated second the scene track judges (never a synchronised extreme)+DEFAULT_TIME_S = 1.5+#: changed-pixel fraction below which an effect is not in the frame. 0.5 % of a+#: 512x288 readback is ~740 pixels — comfortably above the renderer's own noise+#: floor (measured 0.0000: the leave-one-out pass for a shader placed BEHIND the+#: camera is a full second render and differs from the authored frame in zero+#: pixels) and below any effect worth authoring.+PRESENT_FLOOR = 0.005+#: leave-one-out is linear in materials; past this the answer is already "yes"+MAX_MATERIALS = 8+++class CameraAblation(BaseModel):+ """One camera's authored-vs-ablated frame difference."""++ camera: str+ changed_frac: float = Field(description="fraction of pixels the custom shaders change")+ mean_abs: float = 0.0+ pixels: int = 0+++class MaterialAblation(BaseModel):+ """One custom material's leave-one-out contribution (``changed_frac`` None = not measured)."""++ material: str+ type: str = ""+ kind: str = Field(default="", description="ShaderMaterial | onBeforeCompile")+ on: str = ""+ meshes: int = 0+ backdrop: str = Field(default="content", description="sky | ground | content (shared backdrop rules)")+ changed_frac: float | None = None+ camera: str = Field(default="", description="the camera the contribution was measured on")+++class AblationReport(BaseModel):+ """Typed result of one ablation run over a workspace."""++ ok: bool = False+ custom_materials: int = 0+ cameras: list[CameraAblation] = Field(default_factory=list)+ materials: list[MaterialAblation] = Field(default_factory=list)+ max_changed_frac: float = 0.0+ content_changed_frac: float = 0.0+ per_material_measured: bool = False+ per_material_cameras: list[str] = Field(default_factory=list)+ time_s: float = DEFAULT_TIME_S+ sim_time: float | None = None+ threshold: int = 8+ grid: list[int] = Field(default_factory=list, description="[w, h] of the diff readback")+ images: list[str] = Field(default_factory=list, description="authored/ablated PNG pairs (absolute paths)")+ console_errors: list[str] = Field(default_factory=list)+ error: str = ""+ duration_ms: int = 0++ @property+ def present(self) -> bool:+ """The custom shaders visibly change the frame in at least one camera."""+ return self.max_changed_frac >= PRESENT_FLOOR++ def top_materials(self, n: int = 5) -> list[MaterialAblation]:+ """Measured materials, largest contribution first."""+ rows = [m for m in self.materials if m.changed_frac is not None]+ return sorted(rows, key=lambda m: (-(m.changed_frac or 0.0), m.material))[:n]++ def census_field(self) -> dict[str, Any]:+ """The compact form written into ``census.json`` (``effect_ablation``)."""+ return {+ "custom_materials": self.custom_materials,+ "max_changed_frac": round(self.max_changed_frac, 4),+ "content_changed_frac": round(self.content_changed_frac, 4),+ "present": self.present,+ "present_floor": PRESENT_FLOOR,+ "time_s": self.time_s,+ "per_camera": {c.camera: c.changed_frac for c in self.cameras},+ "top_materials": [+ {"material": m.material, "kind": m.kind, "backdrop": m.backdrop,+ "changed_frac": m.changed_frac, "camera": m.camera}+ for m in self.top_materials()+ ],+ }++ def summary_lines(self) -> list[str]:+ """What the agent reads: the headline, then per camera, then per material."""+ if self.error:+ return [f"ablation could not measure the scene: {self.error}"]+ if self.custom_materials == 0:+ return ["no custom shader materials in the scene (no ShaderMaterial, no onBeforeCompile patch) — "+ "every surface is a stock material, so the effect contributes 0% by construction"]+ head = (f"custom shaders paint {self.max_changed_frac:.1%} of the frame "+ f"({self.custom_materials} custom material(s), t={self.time_s:g} s)")+ if not self.present:+ head += " — NOT VISIBLE: removing every custom shader changes (almost) nothing"+ lines = [head]+ lines.append("per camera: " + ", ".join(f"{c.camera}={c.changed_frac:.1%}" for c in self.cameras))+ if self.per_material_measured:+ lines.append("per material (leave-one-out over "+ + ", ".join(self.per_material_cameras) + ", best frame each):")+ for m in self.top_materials():+ where = f", best in {m.camera}" if m.camera else ""+ flag = "" if (m.changed_frac or 0.0) >= PRESENT_FLOOR else " <- in no camera's frame"+ lines.append(f" {m.changed_frac:.1%} {m.material} "+ f"[{m.kind}, {m.backdrop}, {m.meshes} mesh(es){where}]{flag}")+ elif self.custom_materials > MAX_MATERIALS:+ lines.append(f"per-material contribution skipped ({self.custom_materials} materials > {MAX_MATERIALS})")+ return lines+++def _cameras_arg(cameras: Sequence[CameraPlan] | None) -> str:+ if not cameras:+ return "authored"+ return json.dumps([{"name": c.name, "position": list(c.position), "lookAt": list(c.look_at), "fov": c.fov}+ for c in cameras])+++def ablate_scene(+ ws: Workspace,+ *,+ out_dir: Path | None = None,+ cameras: Sequence[CameraPlan] | None = None,+ time_s: float = DEFAULT_TIME_S,+ width: int = 512,+ height: int = 288,+ frames: bool = True,+ max_materials: int = MAX_MATERIALS,+ timeout_s: float = 120.0,+) -> AblationReport:+ """Measure how much of the frame the workspace's custom shaders paint.++ ``out_dir`` (default ``artifacts/ablation``) receives ``ablation.json`` and,+ with ``frames``, one authored/ablated PNG pair per camera. A scene that does+ not boot yields ``ok=False`` with ``error`` set — the build gate is where a+ broken scene is reported, this instrument only declines to measure it. A+ driver failure raises :class:`SceneRenderError`.+ """+ t0 = time.time()+ out = Path(out_dir) if out_dir else ws.artifacts / "ablation"+ out.mkdir(parents=True, exist_ok=True)+ args = [+ "--ws", str(ws.root), "--out", str(out), "--t", f"{time_s:g}",+ "--width", str(width), "--height", str(height),+ "--max-materials", str(max_materials),+ "--cameras", _cameras_arg(cameras),+ "--timeout-ms", str(int(timeout_s * 1000)),+ ]+ if frames:+ args.append("--frames")+ res = run_scene_script("ablate_scene.mjs", args, timeout_s=timeout_s + 20)+ return _report(res.summary, out, duration_ms=int((time.time() - t0) * 1000))+++def _report(summary: dict[str, Any], out_dir: Path, *, duration_ms: int = 0) -> AblationReport:+ """Interpret an ``ablate_scene.mjs`` summary. Pure over the driver JSON."""+ images: list[str] = []+ for f in summary.get("frame_files") or []:+ for key in ("authored", "ablated"):+ p = out_dir / str(f.get(key) or "")+ if f.get(key) and p.is_file():+ images.append(str(p))+ grid = list(summary.get("grid") or [])+ return AblationReport(+ ok=bool(summary.get("ok")),+ custom_materials=int(summary.get("custom_materials") or 0),+ cameras=[CameraAblation.model_validate(c) for c in summary.get("cameras") or []],+ materials=[MaterialAblation.model_validate(m) for m in summary.get("materials") or []],+ max_changed_frac=float(summary.get("max_changed_frac") or 0.0),+ content_changed_frac=float(summary.get("content_changed_frac") or 0.0),+ per_material_measured=bool(summary.get("per_material_measured")),+ per_material_cameras=[str(c) for c in summary.get("per_material_cameras") or []],+ time_s=float(summary.get("time_s") or DEFAULT_TIME_S),+ sim_time=summary.get("sim_time"),+ threshold=int(summary.get("threshold") or 8),+ grid=[int(v) for v in grid[:2]],+ images=images,+ console_errors=[str(e)[:400] for e in (summary.get("console_errors") or [])][:10],+ error=str(summary.get("error") or ""),+ duration_ms=duration_ms or int(summary.get("duration_ms") or 0),+ )+++def merge_into_census(ws: Workspace, report: AblationReport) -> bool:+ """Write ``report.census_field()`` into ``artifacts/census.json`` under+ ``effect_ablation``. Returns False when there is no census to merge into (a+ workspace that has not been built) or it could not be rewritten — the+ measurement is still returned to the caller either way."""+ path = ws.artifacts / "census.json"+ census = read_json_or_none(path)+ if not isinstance(census, dict):+ return False+ census[CENSUS_FIELD] = report.census_field()+ try:+ path.write_text(json.dumps(census, indent=1))+ except OSError:+ return False+ return True+++__all__ = [+ "CENSUS_FIELD", "DEFAULT_TIME_S", "MAX_MATERIALS", "PRESENT_FLOOR",+ "AblationReport", "CameraAblation", "MaterialAblation",+ "SceneRenderError", "ablate_scene", "merge_into_census",+]diff --git a/harness/codeverse/spatial/tools.py b/harness/codeverse/spatial/tools.pyindex 86089f39..6a6eba09 100644--- a/harness/codeverse/spatial/tools.py+++ b/harness/codeverse/spatial/tools.py@@ -21,6 +21,8 @@ from codeverse.contracts.common import Language, Trackfrom codeverse.contracts.plan import StaticPlanfrom codeverse.contracts.spec import Specfrom codeverse.conventions import OBJECT_VIEWS, OBJECT_VIEWS_QUICK+from codeverse.spatial.ablation import ablate_scene as _ablate_scene+from codeverse.spatial.ablation import merge_into_census as _merge_ablation_censusfrom codeverse.spatial.connectivity import check_connectivity as _check_connectivityfrom codeverse.spatial.contract import check_contract as _check_contractfrom codeverse.spatial.contract import planned_joins@@ -504,6 +506,31 @@ def scene_probe(ctx: ToolContext, args: NoArgs) -> Observation:return obs+class EffectAblationArgs(BaseModel):+ time_s: float = Field(default=1.5, description="animation time (s) to freeze the scene at (mid-phase, not an extreme)")+ frames: bool = Field(default=True, description="also write the authored/ablated PNG pair per camera")+++@tool("effect_ablation", EffectAblationArgs,+ "Does your custom GLSL actually reach the picture? Renders every camera twice — as authored, and with every "+ "ShaderMaterial / onBeforeCompile patch replaced by a neutral material of the same base colour — and reports "+ "the fraction of the frame your shaders paint, per camera and per material. 0% means the effect is not in the "+ "frame (behind the camera, occluded, alpha 0) or you retreated to a flat material. LOOK at the returned pair.",+ languages=(Language.SCENE_THREEJS.value,), cost_hint="slow")+def effect_ablation(ctx: ToolContext, args: EffectAblationArgs) -> Observation:+ if not 0.0 <= args.time_s <= 60.0:+ raise ToolUsageError("time_s must be between 0 and 60 seconds", "effect_ablation(time_s=1.5)")+ report = _ablate_scene(ctx.workspace, out_dir=tool_out_dir(ctx, "ablation"),+ time_s=args.time_s, frames=args.frames)+ # the census is what the gates and the judge read: keep them on this number+ _merge_ablation_census(ctx.workspace, report)+ text = "\n".join(report.summary_lines())+ if report.console_errors:+ text += "\nconsole:\n" + "\n".join(f" ! {sanitize_text(e, ctx.workspace.root)}" for e in report.console_errors[:5])+ return Observation(ok=report.ok, text=truncate(text), numbers=report.census_field(),+ images=image_budget(report.images))++class SceneViewsArgs(BaseModel):cameras: str = Field(default="authored", description="authored = the plan/scene cameras · orbit = overview rig · all = both")times: list[float] = Field(default=[0.0, 1.5], description="animation times (s) to capture")diff --git a/harness/runtime_js/ablate_scene.mjs b/harness/runtime_js/ablate_scene.mjsnew file mode 100644index 00000000..73dd4059--- /dev/null+++ b/harness/runtime_js/ablate_scene.mjs@@ -0,0 +1,101 @@+#!/usr/bin/env node+/**+ * Ablation probe for a scene_threejs workspace: does the scene's custom GLSL+ * actually reach the frame?+ *+ * node ablate_scene.mjs --ws <ws> [--out <dir>] [--cameras authored|<json>]+ * [--t 1.5] [--width 512] [--height 288] [--frames] [--max-materials 8]+ * [--gpu auto] [--timeout-ms 120000]+ *+ * Boots the host once and calls `window.__c3v.ablation()` (lib/host_ablation.mjs):+ * every camera is rendered as authored and again with every ShaderMaterial /+ * onBeforeCompile patch replaced by a neutral material of the same base colour,+ * and the changed-pixel fraction is reported per camera, plus per material+ * (leave-one-out) on the camera where the shaders show most.+ *+ * `--frames` also writes `<camera>_authored.png` / `<camera>_ablated.png` into+ * --out: the pair a human (or a VLM) looks at to see WHAT the shader paints.+ * Writes `ablation.json` into --out when given; last stdout line = the same JSON.+ * Exit 0 measured, 1 the scene did not boot, 2 driver failure.+ */++import path from 'node:path';+import { armWatchdog, dataUrlToPng, ensureDir, fail, finish, parseCli, readJsonArg, safeName, writeJson } from './lib/cli.mjs';+import { createTimeoutMs, errorSummary, openHost } from './lib/host_page.mjs';++const args = parseCli({+ ws: {}, out: { default: '' }, cameras: { default: 'authored' }, t: { default: '1.5' },+ width: { default: '512' }, height: { default: '288' }, 'max-materials': { default: '8' },+ frames: { type: 'boolean', default: false }, gpu: { default: process.env.CV3D_RENDER_GPU || 'auto' },+ 'timeout-ms': { default: '120000' }, 'create-timeout-ms': { default: '' },+});++async function main() {+ if (!args.ws) throw new Error('--ws is required');+ const width = parseInt(args.width, 10), height = parseInt(args.height, 10);+ const t = parseFloat(args.t);+ if (!Number.isFinite(t) || t < 0) throw new Error('--t must be a non-negative number');+ const timeoutMs = parseInt(args['timeout-ms'], 10);+ const watchdog = armWatchdog(timeoutMs);+ const t0 = Date.now();+ const outDir = args.out ? ensureDir(path.resolve(args.out)) : null;++ let host;+ try {+ host = await openHost(args.ws, {+ width, height, gpu: args.gpu,+ createSceneTimeoutMs: createTimeoutMs(args['create-timeout-ms'], timeoutMs),+ });+ } catch (e) {+ return fail(`host failed: ${e.message}`);+ }+ const { page, boot } = host;+ const summary = { ok: false, renderer: boot.renderer || host.renderer, gpu: host.gpu, time_s: t, ...emptyReport() };+ try {+ if (!boot.ok) {+ Object.assign(summary, errorSummary(host.errors, boot), { error: boot.error || 'scene did not boot' });+ await host.close();+ if (outDir) writeJson(path.join(outDir, 'ablation.json'), summary);+ return finish(summary, 1);+ }+ let cams = null;+ if (args.cameras !== 'authored' && args.cameras !== 'none') {+ cams = (readJsonArg(args.cameras, 'cameras') || []).map((c) => ({ ...c, name: safeName(c.name, 'camera name') }));+ }+ const report = await page.evaluate(+ (o) => window.__c3v.ablation(o),+ { t, cameras: cams, maxMaterials: parseInt(args['max-materials'], 10), frames: !!(args.frames && outDir) },+ );+ // PNG pairs live on disk, never in the summary (a data URL per camera is megabytes)+ const frames = report.frames || [];+ delete report.frames;+ Object.assign(summary, report);+ if (outDir && frames.length) {+ summary.frame_files = frames.map((f) => {+ const name = safeName(f.camera, 'camera name');+ const a = `${name}_authored.png`, b = `${name}_ablated.png`;+ dataUrlToPng(f.authored, path.join(outDir, a));+ dataUrlToPng(f.ablated, path.join(outDir, b));+ return { camera: name, authored: a, ablated: b };+ });+ }+ Object.assign(summary, errorSummary(host.errors, boot));+ summary.ok = !report.error;+ summary.duration_ms = Date.now() - t0;+ clearTimeout(watchdog);+ await host.close();+ if (outDir) writeJson(path.join(outDir, 'ablation.json'), summary);+ return finish(summary, summary.ok ? 0 : 1);+ } catch (e) {+ await host.close();+ return fail(`ablation failed: ${e.message}`);+ }+}++/** The report shape a caller can rely on even when the scene never booted. */+function emptyReport() {+ return { custom_materials: 0, cameras: [], materials: [], max_changed_frac: 0,+ content_changed_frac: 0, per_material_measured: false, per_material_camera: '' };+}++main().catch((e) => fail(e.stack || String(e)));diff --git a/harness/runtime_js/lib/host_ablation.mjs b/harness/runtime_js/lib/host_ablation.mjsnew file mode 100644index 00000000..8c5db1e4--- /dev/null+++ b/harness/runtime_js/lib/host_ablation.mjs@@ -0,0 +1,374 @@+/**+ * Ablation instrument (page-side): how much of the delivered frame the scene's+ * CUSTOM shaders actually paint.+ *+ * A shader can compile, pass every gate and still be absent from the picture —+ * behind the camera, occluded, alpha-zero, scaled to nothing, or quietly+ * retreated to a flat material after the first compiler error. Nothing the+ * harness measures today can tell "the effect is there" from "the effect+ * compiled": `census.custom_materials` counts materials, `check_shaders`+ * compiles them, and both are happy about a shader nobody can see.+ *+ * The answer is a counterfactual, and it is deterministic (law 3): render the+ * frame twice — as authored, and with every custom-shader CONTRIBUTION removed+ * — and diff the pixels. Two removals, because a shader is absent in two+ * different ways:+ *+ * ShaderMaterial / RawShaderMaterial owns everything its mesh draws, so it+ * is replaced by a neutral MeshStandardMaterial of the same base colour+ * (sniffed from `uniforms`), keeping only the compositing state — side,+ * transparent, opacity, blending, depth — because "neutral" means neutral+ * SHADING, not a different silhouette or a different blend.+ * onBeforeCompile-patched builtin draws either way, so the question is what+ * the patch changed: it is replaced by an unpatched clone of ITSELF, which+ * is literally the same MeshStandardMaterial with the same base colour and+ * maps, minus the patch. Anything coarser (a grey stand-in) would measure+ * the material's textures rather than the agent's GLSL.+ *+ * Everything here is pure over a THREE.Scene plus a `renderFrame(spec)`+ * callback the host supplies (see `scene_host.mjs: ablation()`), so the module+ * knows nothing about renderers, canvases or cameras and is testable on its own.+ * `isCustomShader` is imported from the census — "is this a custom shader" is+ * stated once, there (law 2 in spirit: import, never restate).+ */++import { classifyBackdrop } from './backdrop.mjs';+import { isCustomShader } from './host_census.mjs';++/** Per-channel difference (0..255) that counts a pixel as changed. */+export const DIFF_THRESHOLD = 8;+/** Diff readback cap: frames are compared at native size up to this grid. */+export const DIFF_MAX_W = 512;+export const DIFF_MAX_H = 288;+/** Leave-one-out contribution is measured only when at most this many custom materials exist. */+export const MAX_MATERIALS = 8;+/** Render budget for the whole leave-one-out stage (materials x cameras). */+export const MAX_LOO_RENDERS = 24;+/** Neutral stand-in colour when a ShaderMaterial declares no colour-ish uniform. */+export const NEUTRAL_HEX = 0x808080;++const COLOR_UNIFORM_RE = /(^|_)(u_?)?(colou?r|tint|albedo|diffuse|base)\b|colou?r$/i;++/**+ * Base colour of a material as a THREE.Color: `.color` when it has one (every+ * builtin), else the first colour-ish uniform in NAME ORDER (sorted, so the+ * pick is deterministic when a shader carries several), else neutral grey.+ * HDR values are clamped into [0,1]: an emissive uniform at 4.0 would make the+ * stand-in blow out the frame and inflate the diff for the wrong reason.+ */+export function baseColor(mat, THREE) {+ if (mat.color && mat.color.isColor) return mat.color.clone();+ const u = mat.uniforms || {};+ for (const key of Object.keys(u).sort()) {+ if (!COLOR_UNIFORM_RE.test(key)) continue;+ const v = u[key] && u[key].value;+ if (!v) continue;+ const c = v.isColor ? v.clone()+ : (typeof v.x === 'number' && typeof v.y === 'number' && typeof v.z === 'number')+ ? new THREE.Color(v.x, v.y, v.z) : null;+ if (!c) continue;+ c.r = Math.min(1, Math.max(0, c.r));+ c.g = Math.min(1, Math.max(0, c.g));+ c.b = Math.min(1, Math.max(0, c.b));+ return c;+ }+ return new THREE.Color(NEUTRAL_HEX);+}++/**+ * Neutral stand-in for a from-scratch ShaderMaterial: lit MeshStandardMaterial+ * of the same base colour, same compositing state, no vertex colours (the+ * geometry may not carry the attribute the custom program declared).+ */+export function neutralMaterial(mat, THREE) {+ const m = new THREE.MeshStandardMaterial({+ color: baseColor(mat, THREE),+ roughness: 0.85,+ metalness: 0.0,+ side: mat.side,+ transparent: !!mat.transparent,+ opacity: Number.isFinite(mat.opacity) ? mat.opacity : 1,+ depthTest: mat.depthTest !== false,+ depthWrite: mat.depthWrite !== false,+ blending: mat.blending,+ alphaTest: Number.isFinite(mat.alphaTest) ? mat.alphaTest : 0,+ fog: true,+ });+ m.name = `${mat.name || mat.type}__ablated`;+ return m;+}++/**+ * The same builtin material without its `onBeforeCompile` patch. `userData` is+ * emptied across the clone because `Material.copy` JSON-clones it and a patched+ * material routinely parks live uniforms (or a texture) there — verified on+ * three 0.182: `clone()` copies neither `onBeforeCompile` nor+ * `customProgramCacheKey`, but both are reset explicitly so a future three+ * cannot silently carry the patch across.+ */+export function unpatchedClone(mat, THREE) {+ const keep = mat.userData;+ let c;+ try {+ mat.userData = {};+ c = mat.clone();+ } finally {+ mat.userData = keep;+ }+ c.userData = {};+ c.onBeforeCompile = THREE.Material.prototype.onBeforeCompile;+ c.customProgramCacheKey = THREE.Material.prototype.customProgramCacheKey;+ c.name = `${mat.name || mat.type}__unpatched`;+ c.needsUpdate = true;+ return c;+}++/** World-space AABB of a drawable, or null when it has none. */+function worldBox(o, THREE) {+ if (!o.geometry) return null;+ if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();+ const gb = o.geometry.boundingBox;+ if (!gb || gb.isEmpty()) return null;+ const box = new THREE.Box3().copy(gb).applyMatrix4(o.matrixWorld);+ return box.isEmpty() ? null : box;+}++/**+ * Every custom-shader material in the scene, once each, in traversal order.+ * @returns {Array<{uuid, name, type, kind, on, meshes, backdrop, visible}>}+ * `kind` is 'ShaderMaterial' | 'onBeforeCompile' (same words the census uses),+ * `backdrop` the shared sky/ground/content class of the meshes carrying it.+ */+export function ablationTargets(scene, THREE) {+ scene.updateMatrixWorld(true);+ const byUuid = new Map();+ scene.traverse((o) => {+ if (!o.material) return;+ for (const m of Array.isArray(o.material) ? o.material : [o.material]) {+ if (!m || !isCustomShader(m, THREE)) continue;+ let row = byUuid.get(m.uuid);+ if (!row) {+ row = {+ uuid: m.uuid,+ name: m.name || `${m.type} on ${o.name || o.parent?.name || o.type}`,+ type: m.type,+ kind: m.isShaderMaterial || m.isRawShaderMaterial ? 'ShaderMaterial' : 'onBeforeCompile',+ on: o.name || o.parent?.name || o.type,+ meshes: 0,+ backdrop: 'content',+ visible: false,+ };+ byUuid.set(m.uuid, row);+ }+ row.meshes += 1;+ if (o.visible) row.visible = true;+ const box = worldBox(o, THREE);+ if (box && row.backdrop === 'content') row.backdrop = classifyBackdrop(o, box);+ }+ });+ return [...byUuid.values()];+}++/**+ * Replace custom-shader materials with their neutral stand-ins; returns the+ * undo function (call it before the next render, always in a `finally`).+ * `only` (a material uuid) ablates that ONE material — the leave-one-out pass+ * that gives per-material contribution.+ */+export function ablate(scene, THREE, { only = null } = {}) {+ const undo = [];+ const cache = new Map();+ const standIn = (m) => {+ if (!cache.has(m.uuid)) {+ cache.set(m.uuid, (m.isShaderMaterial || m.isRawShaderMaterial)+ ? neutralMaterial(m, THREE) : unpatchedClone(m, THREE));+ }+ return cache.get(m.uuid);+ };+ scene.traverse((o) => {+ if (!o.material) return;+ const mats = Array.isArray(o.material) ? o.material : [o.material];+ const swapped = mats.map((m) => (+ m && isCustomShader(m, THREE) && (!only || m.uuid === only) ? standIn(m) : m));+ if (!swapped.some((m, i) => m !== mats[i])) return;+ const orig = o.material;+ o.material = Array.isArray(orig) ? swapped : swapped[0];+ undo.push(() => { o.material = orig; });+ });+ return () => {+ for (const u of undo) u();+ for (const m of cache.values()) m.dispose();+ };+}++/**+ * Pixel difference between two RGBA readbacks of the same size.+ * `changed_frac` — pixels whose largest channel difference exceeds `threshold`;+ * `mean_abs` — mean of that per-pixel maximum, 0..1 (a whole-frame tint that+ * moves every pixel by 3/255 shows up here and not in `changed_frac`).+ */+export function frameDiff(a, b, threshold = DIFF_THRESHOLD) {+ if (!a || !b || a.length !== b.length) throw new Error('frameDiff: frames differ in size');+ const n = a.length / 4;+ let changed = 0;+ let sum = 0;+ for (let i = 0; i < n; i++) {+ const j = i * 4;+ const d = Math.max(Math.abs(a[j] - b[j]), Math.abs(a[j + 1] - b[j + 1]), Math.abs(a[j + 2] - b[j + 2]));+ if (d > threshold) changed += 1;+ sum += d;+ }+ return {+ changed_frac: +(changed / Math.max(n, 1)).toFixed(4),+ mean_abs: +(sum / Math.max(n, 1) / 255).toFixed(4),+ pixels: n,+ };+}++/**+ * A reusable RGBA sampler for one render canvas. Frames are read at NATIVE+ * size up to DIFF_MAX_W × DIFF_MAX_H: unlike `host_metrics.sampleFrame` (a+ * fixed 96×54 statistics grid shared with the coverage masks so the numbers+ * stay comparable), this instrument measures WHERE pixels changed, and a 2 px+ * light shaft averaged into a 96×54 cell falls under the 8/255 threshold and+ * reads as "no effect". One scratch canvas is kept for the whole report.+ */+export function frameSampler(canvas) {+ const w = Math.min(canvas.width, DIFF_MAX_W);+ const h = Math.min(canvas.height, DIFF_MAX_H);+ const small = document.createElement('canvas');+ small.width = w;+ small.height = h;+ const ctx = small.getContext('2d', { willReadFrequently: true });+ const sample = () => {+ ctx.clearRect(0, 0, w, h);+ ctx.drawImage(canvas, 0, 0, w, h);+ return ctx.getImageData(0, 0, w, h).data;+ };+ sample.grid = [w, h];+ return sample;+}++/**+ * The whole measurement. Renders per camera: authored, then everything+ * ablated; then one leave-one-out pass per custom material per camera, whose+ * MAXIMUM over cameras is that material's contribution.+ *+ * Per camera and not "on the busiest camera": measured on the starter scene,+ * the busiest camera was the windmill (53.8 %, all of it the sky dome) where+ * the pond water is not in shot at all, so a single-camera pass reported the+ * water at 0.0 % while it paints 17.7 % of the pond camera. A material's+ * contribution is the most it paints in ANY delivered frame. The stage is+ * skipped above MAX_MATERIALS (past eight the answer is already "yes"), never+ * runs on a camera the shaders do not touch at all, and stops at+ * MAX_LOO_RENDERS renders — cameras are visited busiest-first, so the budget+ * always buys the frames that carry the effects.+ *+ * @param {THREE.Scene} scene+ * @param {object} THREE+ * @param {{renderFrame: (spec:object)=>Uint8ClampedArray, cameras: object[],+ * maxMaterials?: number, threshold?: number, maxRenders?: number,+ * grid?: number[], snapshot?: ()=>string}} opts+ * `renderFrame(spec)` renders that camera at the already-fixed sim time and+ * returns the RGBA readback. `snapshot()`, when given, returns the canvas+ * as it stands — called right after each of the two renders the report+ * already makes, so the PNG pair the agent looks at costs no extra frames.+ * @returns {object} plain JSON (see `codeverse.spatial.ablation.AblationReport`)+ */+export function ablationReport(scene, THREE, opts) {+ const { renderFrame, cameras: rawCameras, maxMaterials = MAX_MATERIALS, threshold = DIFF_THRESHOLD,+ maxRenders = MAX_LOO_RENDERS, grid = null, snapshot = null } = opts;+ // camera names key every row and every PNG filename: a duplicate would pair one+ // camera's authored frame with another's ablated one+ const seen = new Set();+ const cameras = (rawCameras || []).filter((c) => !seen.has(c.name) && seen.add(c.name));+ const targets = ablationTargets(scene, THREE);+ const out = {+ custom_materials: targets.length,+ threshold,+ grid: grid || [0, 0],+ cameras: [],+ materials: targets.map((t) => ({+ material: t.name, type: t.type, kind: t.kind, on: t.on, meshes: t.meshes,+ backdrop: t.backdrop, changed_frac: null, camera: '',+ })),+ per_material_cameras: [],+ per_material_measured: false,+ max_changed_frac: 0,+ content_changed_frac: 0,+ frames: [],+ };+ if (!cameras.length) {+ out.error = 'no cameras to ablate';+ return out;+ }+ const authored = new Map();+ for (const spec of cameras) {+ const a = renderFrame(spec);+ authored.set(spec.name, a);+ const authoredUrl = snapshot ? snapshot() : '';+ let row;+ let ablatedUrl = authoredUrl;+ if (!targets.length) {+ // Nothing to ablate: the counterfactual IS the authored frame. Report the+ // exact zero rather than rendering it again — "no custom shader at all" is+ // the retreat this instrument exists to name, not a measurement failure.+ row = { camera: spec.name, changed_frac: 0, mean_abs: 0, pixels: a.length / 4 };+ } else {+ const undo = ablate(scene, THREE, {});+ let b;+ try {+ b = renderFrame(spec);+ if (snapshot) ablatedUrl = snapshot();+ } finally {+ undo();+ }+ row = { camera: spec.name, ...frameDiff(a, b, threshold) };+ }+ out.cameras.push(row);+ out.max_changed_frac = Math.max(out.max_changed_frac, row.changed_frac);+ if (snapshot) out.frames.push({ camera: spec.name, authored: authoredUrl, ablated: ablatedUrl });+ }+ if (!targets.length) return out;++ // leave-one-out: busiest camera first, so a render budget always buys the+ // frames the effects are actually in (index keeps the order deterministic on ties)+ if (targets.length <= maxMaterials) {+ const order = out.cameras+ .map((c, i) => ({ c, i }))+ .sort((x, y) => (y.c.changed_frac - x.c.changed_frac) || (x.i - y.i))+ .map((x) => x.c);+ let spent = 0;+ for (const cam of order) {+ // the busiest camera is always measured (even at 0: "which of these shaders+ // is missing" is exactly the question a 0 raises); after that, skip frames no+ // shader touches and stop when the budget is spent+ if (spent && cam.changed_frac <= 0) continue;+ if (spent && spent + targets.length > maxRenders) break;+ const spec = cameras.find((c) => c.name === cam.camera);+ const a = authored.get(cam.camera);+ targets.forEach((t, i) => {+ const undo = ablate(scene, THREE, { only: t.uuid });+ let b;+ try {+ b = renderFrame(spec);+ } finally {+ undo();+ }+ const frac = frameDiff(a, b, threshold).changed_frac;+ const row = out.materials[i];+ if (row.changed_frac === null || frac > row.changed_frac) {+ row.changed_frac = frac;+ row.camera = cam.camera;+ }+ });+ spent += targets.length;+ out.per_material_cameras.push(cam.camera);+ }+ out.per_material_measured = out.per_material_cameras.length > 0;+ out.content_changed_frac = out.materials+ .filter((m) => m.backdrop === 'content')+ .reduce((mx, m) => Math.max(mx, m.changed_frac || 0), 0);+ }+ return out;+}diff --git a/harness/runtime_js/lib/shader_report.mjs b/harness/runtime_js/lib/shader_report.mjsindex a223e4ba..6eb0d5d5 100644--- a/harness/runtime_js/lib/shader_report.mjs+++ b/harness/runtime_js/lib/shader_report.mjs@@ -30,6 +30,17 @@ export function listSources(root, sub = 'src') {}));}+/** `src/lib/*.js` — the harness's own effect library, shipped into every+ * scene workspace (D51). The STATIC audits skip it: its GLSL is written for+ * `shader.js patchStandard`, which declares and binds `uTime` itself (see+ * `withTime`), and no string-level audit can see that — it fired the+ * undeclared/unbound uTime PAIR on six shipped modules, and once a workspace+ * carried the library that pair outranked the agent's own real shader error+ * in the build report. These files are verified on the GPU by+ * `tests/scene_runtime/lib/`, not by the workspace gate. They stay in+ * `files`, so a COMPILE error inside one still maps back to its file:line. */+const LIB_RE = /^src\/lib\//;+/*** Static-audit stage: build the report skeleton with the node-side GLSL* findings. `module` (optional) restricts the audit to one source file.@@ -38,7 +49,9 @@ export function listSources(root, sub = 'src') {export function staticShaderReport(ws, module = null) {const files = listSources(ws);const sceneUsesFog = files.some((f) => /new\s+THREE\.(Fog|FogExp2)\b|\.fog\s*=/.test(f.text));- const auditTargets = module ? files.filter((f) => f.file === module.replace(/^\.?\//, '')) : files;+ const auditTargets = module+ ? files.filter((f) => f.file === module.replace(/^\.?\//, ''))+ : files.filter((f) => !LIB_RE.test(f.file));if (module && !auditTargets.length) throw new Error(`--module ${module} not found under ${ws}`);const errors = [], warnings = [];for (const f of auditTargets) {diff --git a/harness/tests/scene_runtime/test_ablation.py b/harness/tests/scene_runtime/test_ablation.pynew file mode 100644index 00000000..80be23ca--- /dev/null+++ b/harness/tests/scene_runtime/test_ablation.py@@ -0,0 +1,331 @@+"""The ablation instrument: does the scene's custom GLSL reach the frame?++Three fixture scenes, one instrument, one claim each:+ * a scene with ONE ShaderMaterial in shot → contribution > 0+ * the same scene with the shader replaced by a stock material (the measured+ failure this exists to name — the retreat to a flat material) → exactly 0+ * two shaders, one in shot and one behind the camera → leave-one-out separates+ "the shader exists" from "the shader is in the picture"++Plus the pure pieces (frameDiff, the two stand-in materials) in node without a+browser, and the python reader / census merge with no node at all.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from codeverse.config import get_settings+from codeverse.spatial.ablation import (+ CENSUS_FIELD,+ PRESENT_FLOOR,+ AblationReport,+ _report,+ ablate_scene,+ merge_into_census,+)+from codeverse.spatial.registry import get_tool+from codeverse.workspace import Workspace+from tests.scene_runtime.conftest import needs_browser, needs_node, run_node_json++pytestmark = pytest.mark.node++_HOST_ABLATION = f"{get_settings().runtime_js_dir()}/lib/host_ablation.mjs"+++def _node(script: str) -> dict:+ """Run an inline probe against the real module (absolute import: `-e` has no file dir)."""+ return run_node_json(script.replace("./lib/host_ablation.mjs", _HOST_ABLATION))+++# --------------------------------------------------------------------------- fixture scenes+# One unlit orange quad filling the shot. No colour-ish uniform on purpose: the+# stand-in then falls back to neutral grey and the two frames differ by a lot,+# which is what makes the assertion about presence and not about tone mapping.+_SHADER_QUAD = """+function shaderQuad(THREE, z) {+ const m = new THREE.ShaderMaterial({+ vertexShader: 'void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',+ fragmentShader: 'void main() { gl_FragColor = vec4(0.95, 0.25, 0.05, 1.0); }',+ });+ m.name = 'quad_shader_z' + z;+ const q = new THREE.Mesh(new THREE.PlaneGeometry(6, 4), m);+ q.position.set(0, 1.5, z);+ q.name = 'Quad' + z;+ return q;+}+"""++_SCENE_HEAD = """+import * as THREE from 'three';+""" + _SHADER_QUAD + """+function base(THREE) {+ const scene = new THREE.Scene();+ scene.background = new THREE.Color(0x20242a);+ scene.add(new THREE.HemisphereLight(0xbcd6ef, 0x4a4130, 1.2));+ const dir = new THREE.DirectionalLight(0xffffff, 1.4);+ dir.position.set(4, 6, 5);+ scene.add(dir);+ const box = new THREE.Mesh(new THREE.BoxGeometry(1.2, 1.2, 1.2),+ new THREE.MeshStandardMaterial({ color: 0x6a7f5a, roughness: 0.8 }));+ box.position.set(3.4, 0.6, 1.0);+ box.name = 'PlainBox';+ scene.add(box);+ return scene;+}+const CAMERAS = [{ name: 'front', position: [0, 1.6, 6], lookAt: [0, 1.5, 0], fov: 55 }];+"""++SCENE_ONE_SHADER = _SCENE_HEAD + """+export function createScene() {+ const scene = base(THREE);+ scene.add(shaderQuad(THREE, 0));+ return { scene, cameras: CAMERAS, update() {} };+}+"""++SCENE_NO_SHADER = _SCENE_HEAD + """+export function createScene() {+ const scene = base(THREE);+ const q = new THREE.Mesh(new THREE.PlaneGeometry(6, 4),+ new THREE.MeshStandardMaterial({ color: 0xf2401a, roughness: 0.6 }));+ q.position.set(0, 1.5, 0);+ q.name = 'Quad0';+ scene.add(q);+ return { scene, cameras: CAMERAS, update() {} };+}+"""++# Two custom shaders: one in the shot, one 40 m BEHIND the camera. Both compile,+# both are counted by the census, and only one of them is in the picture.+SCENE_TWO_SHADERS = _SCENE_HEAD + """+export function createScene() {+ const scene = base(THREE);+ scene.add(shaderQuad(THREE, 0));+ scene.add(shaderQuad(THREE, 40));+ return { scene, cameras: CAMERAS, update() {} };+}+"""+++def _scene_ws(ws, source: str):+ ws.src.mkdir(parents=True, exist_ok=True)+ (ws.src / "scene.js").write_text(source)+ return ws+++# --------------------------------------------------------------------------- browser+@needs_browser+def test_a_shader_in_shot_contributes(ws) -> None:+ r = ablate_scene(_scene_ws(ws, SCENE_ONE_SHADER), time_s=1.5)+ assert r.ok and not r.error, r.model_dump()+ assert r.custom_materials == 1+ assert r.cameras and r.cameras[0].camera == "front"+ assert r.max_changed_frac > 0.05, r.model_dump()+ assert r.present+ # the leave-one-out row IS the whole effect here+ assert r.per_material_measured and r.per_material_cameras == ["front"]+ row = r.materials[0]+ assert row.kind == "ShaderMaterial" and row.material == "quad_shader_z0"+ assert row.changed_frac == pytest.approx(r.max_changed_frac, abs=0.02)+ # the pair the agent looks at+ assert len(r.images) == 2 and all(Path(p).is_file() for p in r.images)+ a, b = (Path(p).read_bytes() for p in sorted(r.images))+ assert a != b, "authored and ablated PNGs are identical — nothing was ablated"+++@needs_browser+def test_a_scene_with_no_custom_shader_contributes_exactly_nothing(ws) -> None:+ """The retreat to a flat material: same picture, no GLSL. The instrument must+ say 0 without pretending it failed to measure."""+ r = ablate_scene(_scene_ws(ws, SCENE_NO_SHADER), time_s=1.5)+ assert r.ok and r.custom_materials == 0+ assert r.max_changed_frac == 0.0 and not r.present+ assert r.cameras[0].changed_frac == 0.0+ assert "no custom shader materials" in r.summary_lines()[0]+++@needs_browser+def test_leave_one_out_separates_the_shader_in_shot_from_the_one_behind_the_camera(ws) -> None:+ r = ablate_scene(_scene_ws(ws, SCENE_TWO_SHADERS), time_s=1.5, frames=False)+ assert r.ok and r.custom_materials == 2 and r.per_material_measured+ rows = {m.material: m for m in r.materials}+ assert set(rows) == {"quad_shader_z0", "quad_shader_z40"}+ assert rows["quad_shader_z0"].changed_frac > PRESENT_FLOOR+ assert rows["quad_shader_z40"].changed_frac == 0.0, "a mesh behind the camera cannot change the frame"+ assert not r.images # frames=False writes no PNGs+++@needs_browser+def test_the_measurement_lands_in_the_census_where_the_gates_read_it(ws) -> None:+ _scene_ws(ws, SCENE_ONE_SHADER)+ census_path = ws.artifacts / "census.json"+ census_path.parent.mkdir(parents=True, exist_ok=True)+ census_path.write_text(json.dumps({"totals": {"meshes": 2}}))+ r = ablate_scene(ws, time_s=1.5, frames=False)+ assert merge_into_census(ws, r) is True+ field = json.loads(census_path.read_text())[CENSUS_FIELD]+ assert field["custom_materials"] == 1 and field["present"] is True+ assert field["max_changed_frac"] > 0.05 and field["per_camera"]["front"] > 0.05+ assert json.loads(census_path.read_text())["totals"]["meshes"] == 2 # nothing else disturbed+++@needs_browser+def test_the_build_switch_puts_the_number_where_the_scene_gates_read_it(ws, monkeypatch) -> None:+ """CV3D_ABLATION folds the measurement into the build census (a second browser+ boot, hence opt-in). Off — the default — the build is untouched."""+ from codeverse.languages.scene_threejs import SceneThreeJsRuntime++ _scene_ws(ws, SCENE_ONE_SHADER)+ runtime = SceneThreeJsRuntime()+ monkeypatch.delenv("CV3D_ABLATION", raising=False)+ assert CENSUS_FIELD not in (runtime.build(ws).census or {})+ monkeypatch.setenv("CV3D_ABLATION", "1")+ field = (runtime.build(ws).census or {}).get(CENSUS_FIELD)+ assert field and field["present"] is True and field["custom_materials"] == 1+ assert json.loads((ws.artifacts / "census.json").read_text())[CENSUS_FIELD]["present"] is True+++# --------------------------------------------------------------------------- node, no browser+@needs_node+def test_frame_diff_counts_only_pixels_past_the_threshold() -> None:+ out = _node("""+import { frameDiff, DIFF_THRESHOLD } from './lib/host_ablation.mjs';+const n = 100;+const mk = (fn) => { const a = new Uint8ClampedArray(n * 4); for (let i = 0; i < n; i++) { const v = fn(i); a[i*4] = v; a[i*4+1] = v; a[i*4+2] = v; a[i*4+3] = 255; } return a; };+const flat = mk(() => 100);+const same = frameDiff(flat, mk(() => 100));+const under = frameDiff(flat, mk(() => 108)); // exactly at the threshold: not changed+const quarter = frameDiff(flat, mk((i) => (i < 25 ? 200 : 100)));+let threw = '';+try { frameDiff(flat, new Uint8ClampedArray(8)); } catch (e) { threw = e.message; }+console.log(JSON.stringify({ same, under, quarter, threw, DIFF_THRESHOLD }));+""")+ assert out["DIFF_THRESHOLD"] == 8+ assert out["same"]["changed_frac"] == 0.0 and out["same"]["mean_abs"] == 0.0+ assert out["under"]["changed_frac"] == 0.0 and out["under"]["mean_abs"] > 0+ assert out["quarter"]["changed_frac"] == 0.25 and out["quarter"]["pixels"] == 100+ assert "differ in size" in out["threw"]+++@needs_node+def test_the_stand_ins_keep_the_base_colour_and_drop_only_the_shader() -> None:+ """A ShaderMaterial becomes a neutral lit material of its own colour uniform;+ a patched builtin becomes ITSELF unpatched — same colour, same maps, no GLSL."""+ out = _node("""+import * as THREE from 'three';+import { ablationTargets, baseColor, neutralMaterial, unpatchedClone } from './lib/host_ablation.mjs';++const sm = new THREE.ShaderMaterial({+ uniforms: { uTime: { value: 0 }, uColor: { value: new THREE.Color(0.2, 0.4, 0.8) } },+ vertexShader: 'void main() { gl_Position = vec4(position, 1.0); }',+ fragmentShader: 'void main() { gl_FragColor = vec4(1.0); }',+ transparent: true, opacity: 0.5, side: THREE.DoubleSide, depthWrite: false,+});+sm.name = 'glow';+const neutral = neutralMaterial(sm, THREE);++const std = new THREE.MeshStandardMaterial({ color: 0x336699, roughness: 0.42 });+std.name = 'terrain';+std.userData.uniforms = { uTime: { value: 3 } };+std.onBeforeCompile = (s) => { s.fragmentShader = '#define PATCHED\\n' + s.fragmentShader; };+const plain = unpatchedClone(std, THREE);++const scene = new THREE.Scene();+const a = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), sm); a.name = 'Glow';+const b = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), std); b.name = 'Terrain';+const c = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), new THREE.MeshStandardMaterial()); c.name = 'Plain';+scene.add(a, b, c);++console.log(JSON.stringify({+ neutral_type: neutral.type,+ neutral_color: [neutral.color.r, neutral.color.g, neutral.color.b].map((v) => +v.toFixed(3)),+ neutral_keeps: [neutral.transparent, neutral.opacity, neutral.side === THREE.DoubleSide, neutral.depthWrite],+ hdr_clamped: [baseColor(new THREE.ShaderMaterial({ uniforms: { uColor: { value: new THREE.Vector3(4, 0, 0) } } }), THREE).r],+ plain_color: plain.color.getHex(),+ plain_roughness: plain.roughness,+ plain_patched: plain.onBeforeCompile !== THREE.Material.prototype.onBeforeCompile,+ plain_userdata: Object.keys(plain.userData).length,+ source_still_patched: std.onBeforeCompile !== THREE.Material.prototype.onBeforeCompile,+ source_userdata: Object.keys(std.userData).length,+ targets: ablationTargets(scene, THREE).map((t) => [t.name, t.kind, t.on, t.meshes, t.backdrop]),+}));+""")+ assert out["neutral_type"] == "MeshStandardMaterial"+ assert out["neutral_color"] == [0.2, 0.4, 0.8]+ assert out["neutral_keeps"] == [True, 0.5, True, False]+ assert out["hdr_clamped"] == [1.0] # an HDR uniform cannot blow out the stand-in+ assert out["plain_color"] == 0x336699 and out["plain_roughness"] == 0.42+ assert out["plain_patched"] is False and out["plain_userdata"] == 0+ assert out["source_still_patched"] is True and out["source_userdata"] == 1 # the original is untouched+ assert out["targets"] == [["glow", "ShaderMaterial", "Glow", 1, "content"],+ ["terrain", "onBeforeCompile", "Terrain", 1, "content"]]+++@needs_node+def test_ablate_swaps_only_custom_materials_and_undoes_itself() -> None:+ out = _node("""+import * as THREE from 'three';+import { ablate } from './lib/host_ablation.mjs';+const mk = (mat, name) => { const m = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), mat); m.name = name; return m; };+const sm = new THREE.ShaderMaterial({ vertexShader: 'void main(){}', fragmentShader: 'void main(){}' });+sm.name = 'glow';+const std = new THREE.MeshStandardMaterial({ color: 0x112233 });+std.onBeforeCompile = (s) => s;+std.name = 'terrain';+const plain = new THREE.MeshStandardMaterial({ color: 0x445566 });+plain.name = 'plain';+const scene = new THREE.Scene();+scene.add(mk(sm, 'A'), mk(std, 'B'), mk(plain, 'C'));+const names = () => { const o = {}; scene.traverse((x) => { if (x.material) o[x.name] = x.material.name; }); return o; };+const before = names();+let undo = ablate(scene, THREE, {});+const all = names();+undo();+const restored = names();+undo = ablate(scene, THREE, { only: sm.uuid });+const one = names();+undo();+console.log(JSON.stringify({ before, all, restored, one, back: names() }));+""")+ assert out["before"] == {"A": "glow", "B": "terrain", "C": "plain"}+ assert out["all"] == {"A": "glow__ablated", "B": "terrain__unpatched", "C": "plain"}+ assert out["restored"] == out["before"] and out["back"] == out["before"]+ # leave-one-out touches exactly one material+ assert out["one"] == {"A": "glow__ablated", "B": "terrain", "C": "plain"}+++# --------------------------------------------------------------------------- pure python+def test_the_reader_survives_a_scene_that_never_booted(tmp_path: Path) -> None:+ r = _report({"ok": False, "error": "scene did not boot", "custom_materials": 0}, tmp_path)+ assert not r.ok and not r.present and r.max_changed_frac == 0.0+ assert r.summary_lines() == ["ablation could not measure the scene: scene did not boot"]+ assert r.census_field()["present"] is False+++def test_summary_names_the_shader_that_is_not_in_the_frame() -> None:+ r = AblationReport(+ ok=True, custom_materials=2, per_material_measured=True,+ max_changed_frac=0.21, content_changed_frac=0.21, per_material_cameras=["front"],+ cameras=[{"camera": "front", "changed_frac": 0.21, "mean_abs": 0.03, "pixels": 100}],+ materials=[{"material": "rain", "kind": "ShaderMaterial", "changed_frac": 0.21, "meshes": 1, "camera": "front"},+ {"material": "glow", "kind": "onBeforeCompile", "changed_frac": 0.0, "meshes": 2}],+ )+ text = "\n".join(r.summary_lines())+ assert "21.0% of the frame" in text and "front=21.0%" in text+ assert "in no camera's frame" in text.split("glow")[-1] and "best in front" in text+ assert [m.material for m in r.top_materials()] == ["rain", "glow"]+ assert r.census_field()["top_materials"][0]["material"] == "rain"+++def test_merge_into_census_declines_without_a_census(tmp_path: Path) -> None:+ ws = Workspace(tmp_path / "run").create()+ assert merge_into_census(ws, AblationReport(ok=True)) is False+++def test_the_tool_is_registered_and_says_what_zero_means() -> None:+ card = get_tool("effect_ablation").card()+ assert "0%" in card and "time_s" in card and "neutral material" in carddiff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.pyindex 1105e804..108b9e91 100644--- a/harness/tests/spatial_tools/test_tools.py+++ b/harness/tests/spatial_tools/test_tools.py@@ -27,7 +27,7 @@ CORE_TOOLS = {"build", "measure", "render_views", "render_sheet", "isolate", "cr#: track- / language-scoped tools (documented; keep in sync when registering a new one)SCOPED_TOOLS = {"joint_sweep", # articulated_object- "shader_probe", "scene_probe", "scene_views", "check_placement", # scene_threejs+ "shader_probe", "scene_probe", "scene_views", "check_placement", "effect_ablation", # scene_threejs"gl_probe", "gl_frames", # graphics (glsl_shader / opengl_python)"texture_pass", "texture_preview", # object tracks (texturing)}