Skip to content

Official Codebase of 3DCodeVerse

Python

spatial: delete effect_ablation — its census field was read by no gate and no judge

gaoypengbc7e0689858e
diff --git a/harness/CLAUDE.md b/harness/CLAUDE.md
index f44f940d..eaf5df6b 100644
--- a/harness/CLAUDE.md
+++ b/harness/CLAUDE.md
@@ -6,7 +6,7 @@ Blender bpy · CadQuery · Three.js · URDF · GLSL / OpenGL, across four tracks
(`static_object`, `articulated_object`, `scene`, `graphics`), with pluggable
backends. **The coding agent is always a VENDOR's** — gemini-cli / claude-code /
codex / antigravity — and the harness supplies the workspace, the prompt and the
-3D tools its track can use (over MCP; 20 in the registry, filtered per track — D48
+3D tools its track can use (over MCP; 19 in the registry, filtered per track — D48
review), then reads the result. The harness's OWN api use is planning,
judging, single-shot file generation and the texture pass (Gemini/Anthropic/OpenAI).
It does not implement an agent loop: the in-process `api-agent` was deleted
diff --git a/harness/codeverse3d/languages/scene_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.py
index f0d13eea..add041e0 100644
--- a/harness/codeverse3d/languages/scene_threejs/__init__.py
+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py
@@ -777,8 +777,6 @@ class SceneThreeJsRuntime:
# census.json is only rewritten `if census:` below, so it MUST be wiped here
ws.stage_artifacts("census.json", "scene_probe.json", "shader_preflight.json", "build.json").invalidate()
probe, shaders, census = _probe_and_preflight(ws, timeout_s=tmo)
- if census and probe.passed:
- _ablation_into(ws, census)
if census:
(ws.artifacts / "census.json").write_text(json.dumps(census, indent=1))
gates_dir = ws.artifacts / "gates"
@@ -812,27 +810,6 @@ class SceneThreeJsRuntime:
return res
-def _ablation_into(ws: Workspace, census: dict[str, Any]) -> None:
- """Opt-in (``C3D_ABLATION``): measure how much of the frame the scene's custom
- shaders actually paint and put it in the census, so the scene gates and the
- judge context read "the effect contributes N%" instead of "N custom materials
- compiled". A second browser boot with its own renders, hence a switch and not
- a default; instrumentation never breaks a build, so every failure is swallowed
- into a census note. Details: ``spatial/ablation.py``."""
- from codeverse3d.config import env_flag
-
- if not env_flag("C3D_ABLATION", False):
- return
- from codeverse3d.spatial.ablation import CENSUS_FIELD, ablate_scene
-
- try:
- report = ablate_scene(ws, frames=False)
- except Exception as e: # noqa: BLE001 — an instrument must never fail a build
- census[CENSUS_FIELD] = {"error": f"{type(e).__name__}: {e}"[:300]}
- return
- census[CENSUS_FIELD] = report.census_field()
-
-
def _probe_and_preflight(ws: Workspace, *, timeout_s: float) -> tuple[GateReport, GateReport, dict]:
"""One ``probe_scene.mjs --compile`` run → (scene_probe, shader_preflight, census).
diff --git a/harness/codeverse3d/skills/c3d-threejs-shader-traps/SKILL.md b/harness/codeverse3d/skills/c3d-threejs-shader-traps/SKILL.md
index 68be7568..59d8afb7 100644
--- a/harness/codeverse3d/skills/c3d-threejs-shader-traps/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-threejs-shader-traps/SKILL.md
@@ -121,10 +121,9 @@ Verified against this runtime on 2026-08-25 — believing them costs a repair ro
The gate proves your shader **compiles and is bound**. It says nothing about whether it is
*visible* or *right*: colours crushed by the ACES plus sRGB output chain, transparent water
z-fighting the shore, a patched material whose clone lost its `onBeforeCompile`, a shared
-program cache key, an effect placed outside every camera's frustum. Only `effect_ablation`
-(scenes) renders the scene without your shader to compare against; otherwise look at the
-frames yourself: `scene_views` (or `render_views`) at two different times, and check that the
-thing you wrote changed something.
+program cache key, an effect placed outside every camera's frustum. Look at the frames
+yourself: `scene_views` (or `render_views`) at two different times, and check that the thing
+you wrote changed something.
Full audit source lines, the fix-hint texts, and a minimal citizen shader:
`references/shader-gate.md`.
diff --git a/harness/codeverse3d/spatial/ablation.py b/harness/codeverse3d/spatial/ablation.py
deleted file mode 100644
index eee8f757..00000000
--- a/harness/codeverse3d/spatial/ablation.py
+++ /dev/null
@@ -1,228 +0,0 @@
-"""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 pathlib import Path
-from typing import Any
-
-from pydantic import BaseModel, Field
-
-from codeverse3d.proc import read_json_or_none
-from codeverse3d.spatial.render_scene import (
- SceneRenderError,
- post_chain_args,
- probe_env_args,
- run_scene_script,
-)
-from codeverse3d.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")
-
-
-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
- 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 ablate_scene(
- ws: Workspace,
- *,
- out_dir: Path | None = None,
- time_s: float = DEFAULT_TIME_S,
- frames: bool = True,
- 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}",
- "--max-materials", str(MAX_MATERIALS),
- "--timeout-ms", str(int(timeout_s * 1000)),
- ]
- if frames:
- args.append("--frames")
- args += probe_env_args() + post_chain_args() # the judge's frames: same repair / settle / post policy
- 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))
- 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),
- 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/codeverse3d/spatial/tools.py b/harness/codeverse3d/spatial/tools.py
index e08786c4..3517ed3d 100644
--- a/harness/codeverse3d/spatial/tools.py
+++ b/harness/codeverse3d/spatial/tools.py
@@ -21,8 +21,6 @@ from codeverse3d.contracts.common import Language, Track
from codeverse3d.contracts.plan import StaticPlan
from codeverse3d.contracts.spec import Spec
from codeverse3d.conventions import OBJECT_VIEWS, OBJECT_VIEWS_QUICK
-from codeverse3d.spatial.ablation import ablate_scene as _ablate_scene
-from codeverse3d.spatial.ablation import merge_into_census as _merge_ablation_census
from codeverse3d.spatial.connectivity import check_connectivity as _check_connectivity
from codeverse3d.spatial.contract import check_contract as _check_contract
from codeverse3d.spatial.contract import planned_joins
@@ -544,31 +542,6 @@ 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/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index a94dfa3c..3d0a6c0b 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -126,13 +126,6 @@ codeverse3d/
scene_placement.py (scene_placement gate + check_placement tool: floating / sunken /
unsupported / interpenetration per placed asset from the probe census's placement
table, runtime_js/lib/host_placement.mjs; added 2026-08-26),
- ablation.py (effect_ablation tool + census.effect_ablation: the scene rendered as
- authored vs with every custom shader replaced by a neutral material of the same
- base colour — changed-pixel fraction per camera and per material,
- runtime_js/lib/host_ablation.mjs + ablate_scene.mjs; rebuilt 2026-09-01 as an
- instrument after the 08-28 cleanup deleted the unused counterfactual path.
- The scene build folds the field into its census only under C3D_ABLATION=1 —
- a second browser boot, so opt-in; the tool always writes it to census.json),
gl_render.py (GlHost), frame_stats.py (gl_frames),
sheet.py (montage_2x2, crop_region), measure.py, connectivity.py,
contract.py (authoring-frame hints), sections.py (the cross_section tool and the
@@ -379,10 +372,10 @@ summary:
`@tool(name, ArgsModel, description, *, tracks=(), languages=(), cost_hint)` registers
`fn(ctx, args) -> Observation` → (a) direct call from tracks, (b) the stdio MCP
server (name `3dcode`) for the vendor CLIs, (c) a native tool schema for any embedder
-(`ToolDef.schema()`), (d) a prompt card. The 20 tools: `build`, `measure`,
+(`ToolDef.schema()`), (d) a prompt card. The 19 tools: `build`, `measure`,
`render_views`, `render_sheet`, `isolate`, `cross_section`, `check_connectivity`,
`check_contract`, `check_placement`, `compare_silhouette`, `compare_reference`,
-`joint_sweep` (articulated), `shader_probe`, `scene_probe`, `scene_views`, `effect_ablation` (scene),
+`joint_sweep` (articulated), `shader_probe`, `scene_probe`, `scene_views` (scene),
`gl_probe`, `gl_frames` (graphics), `texture_pass`, `texture_preview` (object tracks).
An `Observation` carries two different answers: `ok` is the **verdict** and `failed`
diff --git a/harness/runtime_js/ablate_scene.mjs b/harness/runtime_js/ablate_scene.mjs
deleted file mode 100644
index 5d24ebbc..00000000
--- a/harness/runtime_js/ablate_scene.mjs
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/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>] [--t 1.5] [--frames] [--max-materials 8]
- * [--gpu auto] [--timeout-ms 120000]
- * [--no-settle] [--camera-repair] [--auto-exposure] [--no-post] (render_scene's switches)
- *
- * Boots the host once (512x288) and calls `window.__c3v.ablation()` (lib/host_ablation.mjs):
- * every authored 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, safeName, writeJson } from './lib/cli.mjs';
-import { createTimeoutMs, errorSummary, openHost } from './lib/host_page.mjs';
-
-const args = parseCli({
- 'no-settle': { type: 'boolean', default: false }, 'camera-repair': { type: 'boolean', default: false },
- 'auto-exposure': { type: 'boolean', default: false }, 'no-post': { type: 'boolean', default: false },
- ws: {}, out: { default: '' }, t: { default: '1.5' }, 'max-materials': { default: '8' },
- frames: { type: 'boolean', default: false }, gpu: { default: process.env.C3D_RENDER_GPU || 'auto' },
- 'timeout-ms': { default: '120000' },
-});
-
-async function main() {
- if (!args.ws) throw new Error('--ws is required');
- 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: 512, height: 288, gpu: args.gpu,
- createSceneTimeoutMs: createTimeoutMs(timeoutMs),
- settle: !args['no-settle'], cameraRepair: !!args['camera-repair'],
- autoExposure: !!args['auto-exposure'], post: !args['no-post'],
- });
- } 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);
- }
- const report = await page.evaluate(
- (o) => window.__c3v.ablation(o),
- { t, 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_cameras: [] };
-}
-
-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.mjs
deleted file mode 100644
index 7fb6636a..00000000
--- a/harness/runtime_js/lib/host_ablation.mjs
+++ /dev/null
@@ -1,353 +0,0 @@
-/**
- * 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, worldBox } 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;
-}
-
-/**
- * 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`.
- */
-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;
- 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;
- }
- return { changed_frac: +(changed / Math.max(n, 1)).toFixed(4) };
-}
-
-/**
- * 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;
- };
- 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,
- * 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 `codeverse3d.spatial.ablation.AblationReport`)
- */
-export function ablationReport(scene, THREE, opts) {
- const { renderFrame, cameras: rawCameras, maxMaterials = MAX_MATERIALS, threshold = DIFF_THRESHOLD,
- maxRenders = MAX_LOO_RENDERS, 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,
- 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 };
- } 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/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjs
index d47c52d1..6a0cf20d 100644
--- a/harness/runtime_js/lib/scene_host.mjs
+++ b/harness/runtime_js/lib/scene_host.mjs
@@ -9,14 +9,13 @@
* grade, `post: false` to disable); the coverage mask passes stay raw.
* boot(opts) · renderAt(cameraSpec, t) · census() · fps(seconds)
* cameraChecks(cameraSpec) (near geometry + luminance + content coverage)
- * compileAll(cameraSpec) · shaderErrors() · ablation(opts) (shader presence)
+ * compileAll(cameraSpec) · shaderErrors()
* Node drivers (render_scene / probe_scene / check_shaders) call these via
* page.evaluate. Agent code never imports this file.
*/
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-import { ablationReport, frameSampler } from './host_ablation.mjs';
import { sceneCensus } from './host_census.mjs';
import { placementTable, settleScene } from './host_placement.mjs';
import { frameStats, nearGeometry, repairCameraSpec } from './host_metrics.mjs';
@@ -636,35 +635,6 @@ function fps(seconds, spec) {
return { fps: frames / Math.max(elapsed, 1e-3), frames, seconds: elapsed, draw_calls: r.calls, triangles: r.triangles };
}
-/**
- * Ablation instrument (host_ablation.mjs): render each camera as authored and
- * again with every custom shader replaced by a neutral material, and report the
- * fraction of the frame the shaders actually paint.
- *
- * Time is advanced ONCE, before any render, and never again: every frame in the
- * report — authored, fully ablated, leave-one-out — is the same instant of the
- * same scene, so the only thing that differs between two frames is the shader
- * under test. Frames go through `renderOnce`, so the post chain (when armed)
- * is included: the measurement is of the DELIVERED picture, not of a raw pass
- * nobody sees.
- *
- * @param {{t?:number, cameras?:object[], maxMaterials?:number, threshold?:number, frames?:boolean}} opts
- */
-function ablation(opts = {}) {
- if (!state.booted) throw new Error('host not booted');
- const t = Number.isFinite(opts.t) ? opts.t : 1.5;
- advanceTo(t);
- state.scene.updateMatrixWorld(true);
- const cameras = (Array.isArray(opts.cameras) && opts.cameras.length) ? opts.cameras : state.cameras;
- const sample = frameSampler(state.canvas);
- const renderFrame = (spec) => { renderOnce(buildCamera(spec)); return sample(); };
- const snapshot = opts.frames ? () => state.canvas.toDataURL('image/png') : null;
- return ablationReport(state.scene, THREE, {
- renderFrame, snapshot, cameras,
- maxMaterials: opts.maxMaterials, threshold: opts.threshold, maxRenders: opts.maxRenders,
- });
-}
-
/** Per-asset placement table (host_placement.mjs) — never throws: a failure is `{error}`. */
function placement() {
try {
@@ -697,7 +667,6 @@ window.__c3v = {
compileAll,
census,
placement,
- ablation,
fps,
post: () => (state.postInfo ? { ...state.postInfo } : null),
hostWarnings: () => state.hostWarnings.slice(),
diff --git a/harness/tests/scene_runtime/test_ablation.py b/harness/tests/scene_runtime/test_ablation.py
deleted file mode 100644
index f37fea22..00000000
--- a/harness/tests/scene_runtime/test_ablation.py
+++ /dev/null
@@ -1,331 +0,0 @@
-"""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 codeverse3d.config import get_settings
-from codeverse3d.spatial.ablation import (
- CENSUS_FIELD,
- PRESENT_FLOOR,
- AblationReport,
- _report,
- ablate_scene,
- merge_into_census,
-)
-from codeverse3d.spatial.registry import get_tool
-from codeverse3d.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:
- """C3D_ABLATION folds the measurement into the build census (a second browser
- boot, hence opt-in). Off — the default — the build is untouched."""
- from codeverse3d.languages.scene_threejs import SceneThreeJsRuntime
-
- _scene_ws(ws, SCENE_ONE_SHADER)
- runtime = SceneThreeJsRuntime()
- monkeypatch.delenv("C3D_ABLATION", raising=False)
- assert CENSUS_FIELD not in (runtime.build(ws).census or {})
- monkeypatch.setenv("C3D_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
- assert out["under"]["changed_frac"] == 0.0
- assert out["quarter"]["changed_frac"] == 0.25
- 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}],
- 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 card
diff --git a/harness/tests/scene_runtime/test_driver_flags.py b/harness/tests/scene_runtime/test_driver_flags.py
index bf71c5ea..f95795c7 100644
--- a/harness/tests/scene_runtime/test_driver_flags.py
+++ b/harness/tests/scene_runtime/test_driver_flags.py
@@ -22,7 +22,7 @@ pytestmark = [pytest.mark.node, needs_node]
FLAGS = ["--no-settle", "--camera-repair", "--auto-exposure", "--no-post"]
[email protected]("driver", ["render_scene.mjs", "probe_scene.mjs", "ablate_scene.mjs"])
[email protected]("driver", ["render_scene.mjs", "probe_scene.mjs"])
def test_every_documented_flag_parses(driver):
s = get_settings()
node = s.binaries.node or "node"
diff --git a/harness/tests/scene_runtime/test_render_scene.py b/harness/tests/scene_runtime/test_render_scene.py
index 348d2410..f7bb260e 100644
--- a/harness/tests/scene_runtime/test_render_scene.py
+++ b/harness/tests/scene_runtime/test_render_scene.py
@@ -295,7 +295,6 @@ def test_every_driver_invocation_carries_the_env_flags(monkeypatch, ws, tmp_path
settle / camera-repair / auto-exposure flags as the standalone probe and
render paths — it used to pass none of them."""
import codeverse3d.languages.scene_threejs as st
- import codeverse3d.spatial.ablation as ablation_mod
import codeverse3d.spatial.probes as probes_mod
captured: dict[str, list[str]] = {}
@@ -306,7 +305,6 @@ def test_every_driver_invocation_carries_the_env_flags(monkeypatch, ws, tmp_path
monkeypatch.setattr(probes_mod, "run_scene_script", fake_run)
monkeypatch.setattr(rs_mod, "run_scene_script", fake_run)
- monkeypatch.setattr(ablation_mod, "run_scene_script", fake_run)
for k in ("C3D_SETTLE", "C3D_CAMERA_REPAIR", "C3D_AUTO_EXPOSURE", "C3D_POST"):
monkeypatch.delenv(k, raising=False)
@@ -319,20 +317,11 @@ def test_every_driver_invocation_carries_the_env_flags(monkeypatch, ws, tmp_path
render_scene(ws, tmp_path / "out_flags", cameras=[CameraPlan(name="c", position=(1, 2, 3), look_at=(0, 0, 0), fov=45)],
orbit=False, times=(0.0,), sheet=False)
assert _flags(captured["render_scene.mjs"]) == ["--camera-repair"]
- # effect_ablation measures the frames the judge sees: it used to run with repair OFF
- # and the post chain ON whatever C3D_POST said
- with pytest.raises(SceneRenderError):
- ablation_mod.ablate_scene(ws)
- assert _flags(captured["ablate_scene.mjs"]) == ["--camera-repair"] and "--no-post" not in captured["ablate_scene.mjs"]
# the A/B words reach every path, including the combined build
monkeypatch.setenv("C3D_SETTLE", "0")
monkeypatch.setenv("C3D_CAMERA_REPAIR", "false")
- monkeypatch.setenv("C3D_POST", "0")
st._probe_and_preflight(ws, timeout_s=5.0)
assert _flags(captured["probe_scene.mjs"]) == ["--no-settle"]
probes_mod.probe_scene(ws)
assert _flags(captured["probe_scene.mjs"]) == ["--no-settle"]
- with pytest.raises(SceneRenderError):
- ablation_mod.ablate_scene(ws)
- assert _flags(captured["ablate_scene.mjs"]) == ["--no-settle"] and "--no-post" in captured["ablate_scene.mjs"]
diff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.py
index 7ecf917f..1a9cf9d5 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", "effect_ablation", # scene_threejs
+ "shader_probe", "scene_probe", "scene_views", "check_placement", # scene_threejs
"gl_probe", "gl_frames", # graphics (glsl_shader / opengl_python)
"texture_pass", "texture_preview", # object tracks (texturing)
}