Official Codebase of 3DCodeVerse
Python
runtime_js: delete what nothing calls or reads, and the re-centring --normalise
gaoypengdefb877a11cb
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.mdindex 6cac42f7..9aeea0ad 100644--- a/harness/docs/INSTALL.md+++ b/harness/docs/INSTALL.md@@ -175,8 +175,8 @@ three.js in headless Chrome), whichever language produced the GLB.```harness/runtime_js/- package.json committed — 3 direct deps- package-lock.json committed — exact tree (100 packages), the reproducibility unit+ package.json committed — 2 direct deps+ package-lock.json committed — exact tree (99 packages), the reproducibility unitnode_modules/ NOT committed — .gitignore'd, ~97 MB, created by `npm ci`*.mjs *.cjs lib/ the harness's own node code (see runtime_js/README.md)```@@ -187,13 +187,12 @@ Direct dependencies and what they are for:|---|---|---|| `three` | 0.182.0 | GLB export (`export_glb.mjs`), the render rig, the scene host, GLSL preflight || `puppeteer` | 24.43.1 | headless Chrome for WebGL rendering (`gpu_launch.cjs`, `browser_daemon.cjs`) |-| `three-mesh-bvh` | 0.9.14 | accelerated raycasts in scene probes |### Install / refresh```bashcd harness/runtime_js-npm ci # exact lockfile install; ~2 s, 100 packages, 95–97 MB+npm ci # exact lockfile install; ~2 s, 99 packages, 95–97 MBnpx puppeteer browsers install chrome # only if the Chrome cache is missing (see below)```@@ -237,8 +236,8 @@ and nothing else; it never imports a harness module and never gets abare specifier for it in two places:* **node**: `node --import runtime_js/lib/resolve_three.mjs …` installs a- `registerHooks` resolver that redirects `three`, `three/addons/*` and- `three-mesh-bvh` into `runtime_js/node_modules`, for a module living anywhere+ `registerHooks` resolver that redirects `three` and `three/addons/*` into+ `runtime_js/node_modules`, for a module living anywhereon disk (`NODE_PATH` cannot do this — it is CommonJS-only). Python side:`spatial.node.run_node(..., three_hook=True)`.* **browser**: `serve.cjs` mounts `runtime_js/` at `/__runtime/` on the loopback@@ -594,7 +593,7 @@ those by hand (`npm rm -g @google/gemini-cli @anthropic-ai/claude-code @openai/c| python | 3.13.9 (the one supported version — §2.1) | `/home/yipeng/miniconda3/bin/python` || pip packages | pydantic 2.13.2 · trimesh 4.12.2 · python-fcl 0.7.0.11 · moderngl 5.12.0 · shapely 2.1.2 · networkx 3.6.1 · manifold3d 3.5.2 · pyarrow 24.0.0 · mcp 2.0.0 · scipy 1.18.0 · yourdfpy 0.0.60 · cadquery 2.8.0 · google-genai 2.10.0 · pytest 9.1.1 · ruff 0.15.20 | editable install of `harness/` || node / npm | v24.14.0 / 11.9.0 (floor 20.6.0 — §2.1, verified against node 20.19.5) | `/home/yipeng/miniconda3/bin/node` |-| runtime_js deps | three 0.182.0 · puppeteer 24.43.1 · three-mesh-bvh 0.9.14 (100 packages, 97 MB) | `harness/runtime_js/node_modules` |+| runtime_js deps | three 0.182.0 · puppeteer 24.43.1 (99 packages, 97 MB) | `harness/runtime_js/node_modules` || Chrome (puppeteer) | 148.0.7778.97 (+ headless-shell) | `~/.cache/puppeteer` || Blender | 5.0.1 (2025-12-16) | `~/.local/bin/blender-5.0` → `~/3dcodeverse_data/tools/blender-5.0.1-linux-x64` || git | 2.53.0 | `/usr/bin/git` |diff --git a/harness/runtime_js/README.md b/harness/runtime_js/README.mdindex 53babaaf..ba7ed5b1 100644--- a/harness/runtime_js/README.md+++ b/harness/runtime_js/README.md@@ -11,7 +11,7 @@ never imports from this directory**; it only imports `three` (andThis directory is an ordinary npm package owned by the harness: `package.json`and `package-lock.json` are committed, `node_modules/` is **not** (gitignored,-~97 MB, 100 packages). Node itself is a system prerequisite — installing it is+~97 MB, 99 packages). Node itself is a system prerequisite — installing it isseparate from what `npm ci` does here.**Node floor: 20.6.0** (`package.json` `engines.node`; developed on v24.14.0).@@ -38,8 +38,8 @@ npx puppeteer browsers install chrome # only if ~/.cache/puppeteer is emptyRe-run `npm ci` after a fresh clone or after pulling a `package.json` /`package-lock.json` change — it deletes `node_modules/` first, so never while arender or bench is running. Deps: `three` 0.182 (export + render + scene host),-`puppeteer` 24 (headless Chrome, downloads its own build into `~/.cache/puppeteer`),-`three-mesh-bvh` 0.9.14 (accelerated raycasts). Full guide: `../docs/INSTALL.md`.+`puppeteer` 24 (headless Chrome, downloads its own build into `~/.cache/puppeteer`).+Full guide: `../docs/INSTALL.md`.```gpu_launch.cjs launchBrowser({gpu:'auto'|'on'|'off'}) → {browser, gpu, renderer, shared, release()};@@ -55,12 +55,11 @@ serve.cjs serveDirs({root, mounts, routes}) loopback static server ('three/addons/' onto it — nothing is ever fetched from the internetexport_glb.mjs node --import lib/resolve_three.mjs export_glb.mjs --ws <ws> [--entry src/object.js][--out artifacts/object.glb] [--census artifacts/census.json]- [--normalise 0|1] imports the agent module, build(THREE) (awaits promises), validates+ imports the agent module, build(THREE) (awaits promises), validates(NaN/empty-bbox errors name the mesh + part), runs an exported selfcheck(THREE, root)if any (throw → SelfCheckError), bakes InstancedMesh copies into named meshes(lib/instances.mjs — trimesh ignores EXT_mesh_gpu_instancing), keeps the source- placement (off-ground/off-centre → warning + census.placement_offset; --normalise 1- translates instead, for dataset canonicalisation only), strips textures (warning),+ placement (off-ground/off-centre → warning + census.placement_offset), strips textures (warning),writes GLB + census.json; on failure export_error.json +{ok:false,error:{type,message,file,line,frames,part?}}render_glb.mjs --glb --out --views '[{name,azimuth,elevation}]' [--mode shaded|wire|normals|silhouette|clay]@@ -69,11 +68,11 @@ render_glb.mjs --glb --out --views '[{name,azimuth,elevation}]' [--mode swrites view_<name>.png + views.json; last stdout line = JSON record. Thin entry:args/JSON protocol from lib/cli.mjs, browser + server from lib/host_env.mjs,browser release from lib/host_page.mjs, everything visual from lib/browser/-lib/resolve_three.mjs node --import hook: bare 'three' / 'three/addons/*' (and three-mesh-bvh) resolve+lib/resolve_three.mjs node --import hook: bare 'three' / 'three/addons/*' resolvefrom runtime_js/node_modules for modules anywhere on disk (NODE_PATH is CJS-only);module.registerHooks on node >= 22.15, module.register + lib/resolve_three_async.mjson the 20.6 floor. Redirect rule stated once in lib/three_redirect.mjs-lib/node_polyfills.mjs FileReader/Blob/self shims so GLTFExporter writes binary GLB without a DOM+lib/node_polyfills.mjs FileReader/self shims so GLTFExporter writes binary GLB without a DOMlib/census.mjs per-part tri counts, world bboxes, materials, NaN check naming mesh + part (node + browser)lib/instances.mjs bakeInstancedMeshes(THREE, root): InstancedMesh → Group of named plain mesheslib/stack.mjs Error → {type,message,file,line,frames} with workspace-relative src/ pathsdiff --git a/harness/runtime_js/ablate_scene.mjs b/harness/runtime_js/ablate_scene.mjsindex 338a230a..bde31cd1 100644--- a/harness/runtime_js/ablate_scene.mjs+++ b/harness/runtime_js/ablate_scene.mjs@@ -3,12 +3,11 @@* 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]+ * node ablate_scene.mjs --ws <ws> [--out <dir>] [--t 1.5] [--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 /+ * 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.@@ -20,19 +19,17 @@*/import path from 'node:path';-import { armWatchdog, dataUrlToPng, ensureDir, fail, finish, parseCli, readJsonArg, safeName, writeJson } from './lib/cli.mjs';+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({- ws: {}, out: { default: '' }, cameras: { default: 'authored' }, t: { default: '1.5' },- width: { default: '512' }, height: { default: '288' }, 'max-materials': { default: '8' },+ 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 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);@@ -43,7 +40,7 @@ async function main() {let host;try {host = await openHost(args.ws, {- width, height, gpu: args.gpu,+ width: 512, height: 288, gpu: args.gpu,createSceneTimeoutMs: createTimeoutMs(timeoutMs),});} catch (e) {@@ -58,13 +55,9 @@ async function main() {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) },+ { 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 || [];diff --git a/harness/runtime_js/browser_daemon.cjs b/harness/runtime_js/browser_daemon.cjsindex 587643cb..a8dba3b6 100644--- a/harness/runtime_js/browser_daemon.cjs+++ b/harness/runtime_js/browser_daemon.cjs@@ -81,7 +81,7 @@ async function main() {return;}} catch (_e) { /* browser gone or wedged: fall through and exit */ }- const cur = (() => { try { return JSON.parse(fs.readFileSync(epPath, 'utf8')); } catch (_e) { return null; } })();+ const cur = _internal.readJson(epPath);if (cur && cur.ws === record.ws) fs.rmSync(epPath, { force: true });try { await Promise.race([browser.close(), new Promise((res) => setTimeout(res, 5000))]); } catch (_e) { /* already dead */ }process.exit(code);@@ -89,7 +89,7 @@ async function main() {browser.on('disconnected', () => {// our own connection died with the browser process- try { const cur = JSON.parse(fs.readFileSync(epPath, 'utf8')); if (cur.ws === record.ws) fs.rmSync(epPath, { force: true }); } catch (_e) { /* ignore */ }+ try { const cur = _internal.readJson(epPath); if (cur && cur.ws === record.ws) fs.rmSync(epPath, { force: true }); } catch (_e) { /* ignore */ }process.exit(0);});@@ -101,7 +101,7 @@ async function main() {} catch (_e) {return bail(0); // endpoint deleted (poisoned verdict or manual cleanup)}- const cur = (() => { try { return JSON.parse(fs.readFileSync(epPath, 'utf8')); } catch (_e) { return null; } })();+ const cur = _internal.readJson(epPath);if (!cur || cur.ws !== record.ws) return bail(0, { advertise: false }); // superseded: never clobber the newer daemonconst idle = Date.now() - st.mtimeMs;// Reap leaked pages only when NOBODY is working: clients tick the heartbeat everydiff --git a/harness/runtime_js/export_glb.mjs b/harness/runtime_js/export_glb.mjsindex 5790ebbc..06c59dcf 100644--- a/harness/runtime_js/export_glb.mjs+++ b/harness/runtime_js/export_glb.mjs@@ -10,8 +10,7 @@// throws. InstancedMesh objects are baked into named plain meshes (lib/instances.mjs)// so trimesh-based gates see every copy. The object is exported exactly where the// source put it: an off-ground / off-centre build only WARNS (census.placement_offset),-// like the Blender/CadQuery wrappers, so plan-frame gates stay valid; `--normalise 1`-// (dataset canonicalisation only — never passed by ThreeJsRuntime) translates instead.+// like the Blender/CadQuery wrappers, so plan-frame gates stay valid.// Last stdout line is a JSON record:// ok:true -> {ok, glb, census, duration_ms}// ok:false -> {ok:false, error:{type,message,file,line,frames,stack,part?}, warnings}@@ -38,7 +37,7 @@ const PLACEMENT_THRESHOLD_M = 0.01;function cli() {const values = parseCli({ws: {}, entry: { default: 'src/object.js' }, out: { default: 'artifacts/object.glb' },- census: { default: 'artifacts/census.json' }, normalise: { default: '0' },+ census: { default: 'artifacts/census.json' },});if (!values.ws) throw new Error('--ws <workspace dir> is required');const ws = path.resolve(values.ws);@@ -48,7 +47,6 @@ function cli() {entry: abs(values.entry),out: abs(values.out),census: abs(values.census),- normalise: values.normalise === '1',};}@@ -138,19 +136,14 @@ async function runSelfcheck(mod, THREE, group) {/*** Offset that WOULD stand the object on y=0 centred on the Y axis (null when within- * PLACEMENT_THRESHOLD_M). Only applied when `--normalise 1` was given: by default the- * GLB keeps the source placement so check_contract compares in the plan's frame.+ * PLACEMENT_THRESHOLD_M). Never applied: the GLB keeps the source placement so+ * check_contract compares in the plan's frame (law 7).*/-function placement(THREE, group, apply) {+function placement(THREE, group) {const box = new THREE.Box3().setFromObject(group, true);const c = box.getCenter(new THREE.Vector3());const offset = new THREE.Vector3(-c.x, -box.min.y, -c.z);- if (offset.length() <= PLACEMENT_THRESHOLD_M) return { offset: null, applied: null };- const rounded = offset.toArray().map((v) => +v.toFixed(5));- if (!apply) return { offset: rounded, applied: null };- group.position.add(offset);- group.updateWorldMatrix(true, true);- return { offset: rounded, applied: rounded };+ return offset.length() <= PLACEMENT_THRESHOLD_M ? null : offset.toArray().map((v) => +v.toFixed(5));}function stripTextures(group, warnings) {@@ -197,14 +190,12 @@ async function main() {const tickPresent = typeof (group.userData && group.userData.tick) === 'function';if (tickPresent) delete group.userData.tick; // functions cannot be serialised into glTF extras- const place = placement(THREE, group, args.normalise);- if (place.applied) warnings.push(`object was off ground/centre by ${JSON.stringify(place.applied)} m; translated so min.y=0 and xz-centre=0 (--normalise 1)`);- else if (place.offset) warnings.push(`object is off ground/centre: it needs a translation of ${JSON.stringify(place.offset)} m to stand on y=0 centred on the Y axis; exported as authored — fix the source (the contract gate reports this too)`);+ const offset = placement(THREE, group);+ if (offset) warnings.push(`object is off ground/centre: it needs a translation of ${JSON.stringify(offset)} m to stand on y=0 centred on the Y axis; exported as authored — fix the source (the contract gate reports this too)`);stripTextures(group, warnings);const census = objectCensus(THREE, group);- census.placement_offset = place.offset;- census.normalised_offset = place.applied;+ census.placement_offset = offset;census.instanced_meshes_baked = bakedInstances;census.selfcheck_ran = selfchecked;census.tick_present = tickPresent;diff --git a/harness/runtime_js/gpu_launch.cjs b/harness/runtime_js/gpu_launch.cjsindex 76b40dcd..0118e7af 100644--- a/harness/runtime_js/gpu_launch.cjs+++ b/harness/runtime_js/gpu_launch.cjs@@ -48,14 +48,6 @@ const GPU_ENV = {};const SOFTWARE_RE = /swiftshader|llvmpipe|softpipe|software|basic render/i;-function readCache() {- try {- return JSON.parse(fs.readFileSync(CACHE_PATH, 'utf8'));- } catch (_e) {- return null;- }-}-function writeCache(decision) {try {fs.mkdirSync(CACHE_DIR, { recursive: true });@@ -328,7 +320,7 @@ async function launchBrowser(opts = {}) {// auto: a fresh negative verdict skips the slow GPU attempt; a positive one is// re-verified by the GPU attempt itself (shared endpoint or launch), since the// GPU can go away.- const cached = readCache();+ const cached = readJson(CACHE_PATH);const fresh = cached && typeof cached.at === 'number' && Date.now() - cached.at < NEGATIVE_TTL_MS;if (cached && cached.use_gpu === false && fresh) return cpuBrowser(puppeteer);@@ -345,7 +337,7 @@ module.exports = {launchBrowser, rendererInfo, GPU_ARGS, CPU_ARGS, GPU_ENV, CACHE_PATH,// internals shared with browser_daemon.cjs (not a public surface)_internal: {- launchCpu, tryGpu, loadPuppeteer, endpointPath, daemonFailPath, spawnLockPath,+ launchCpu, tryGpu, loadPuppeteer, readJson, endpointPath, daemonFailPath, spawnLockPath,CACHE_DIR, RUNTIME_KEY, SOFTWARE_RE,},};diff --git a/harness/runtime_js/lib/backdrop.mjs b/harness/runtime_js/lib/backdrop.mjsindex a72fa126..86d15314 100644--- a/harness/runtime_js/lib/backdrop.mjs+++ b/harness/runtime_js/lib/backdrop.mjs@@ -39,6 +39,16 @@ export function nonSolid(mesh) {return real.length > 0 && real.every((m) => m.depthWrite === false);}+/** World-space AABB of a drawable (a fresh THREE.Box3), or null when it has none. */+export 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;+}+export const SKY_NAME_RE = /\b(sky|skydome|skybox|stars|clouds?|sun|moon|atmosphere)\b/i;export const GROUND_NAME_RE = /\b(ground|terrain|floor|water|ocean|sea|lake|river|plane|sand|grass|land)\b/i;diff --git a/harness/runtime_js/lib/browser/camera_fit.js b/harness/runtime_js/lib/browser/camera_fit.jsindex 9b141bd9..9e4c9cdc 100644--- a/harness/runtime_js/lib/browser/camera_fit.js+++ b/harness/runtime_js/lib/browser/camera_fit.js@@ -17,15 +17,6 @@ export function viewDirection(azimuthDeg, elevationDeg) {return new THREE.Vector3(...orbitDirection(azimuthDeg, elevationDeg));}-/** The 8 corners of a Box3. */-export function boxCorners(box) {- const out = [];- for (const x of [box.min.x, box.max.x])- for (const y of [box.min.y, box.max.y])- for (const z of [box.min.z, box.max.z]) out.push(new THREE.Vector3(x, y, z));- return out;-}-/*** Screen-up for a view: near-vertical views make (0,1,0) ~collinear with the* view direction, which makes lookAt's roll unstable — pin up to -Z (front atdiff --git a/harness/runtime_js/lib/browser/post.js b/harness/runtime_js/lib/browser/post.jsindex 27a409d6..82ad7dc9 100644--- a/harness/runtime_js/lib/browser/post.js+++ b/harness/runtime_js/lib/browser/post.js@@ -420,25 +420,6 @@ function makeGlowLayer(renderer, scene, { width, height, levels, threshold }) {renderer.setRenderTarget(savedTarget);return true;},-- setSize(width2, height2) {- let w2 = Math.max(2, width2 >> 1), h2 = Math.max(2, height2 >> 1);- for (const t of targets) {- t.setSize(w2, h2);- w2 = Math.max(2, w2 >> 1);- h2 = Math.max(2, h2 >> 1);- }- },-- dispose() {- for (const t of targets) t.dispose();- for (const p of proxies.values()) if (p) p.dispose();- proxies.clear();- black.dispose();- down.dispose();- up.dispose();- quad.dispose();- },};}@@ -495,8 +476,7 @@ export function isNeutralGrade(applied) {* @param {THREE.WebGLRenderer} renderer* @param {THREE.Scene} scene* @param {{width:number, height:number, options?:object}} spec- * @returns {{render(camera):void, setSize(w,h):void, dispose():void, info:object,- * refreshGrade():void, composer:EffectComposer}}+ * @returns {{render(camera):void, info:object, refreshGrade():void}}*/export function makePostChain(renderer, scene, { width, height, options = {} } = {}) {const opt = { ...POST_DEFAULTS, ...(options || {}) };@@ -566,7 +546,6 @@ export function makePostChain(renderer, scene, { width, height, options = {} } =};return {- composer,info,/** Re-read scene.userData.grade (a scene may set it during createScene or update). */refreshGrade() {@@ -590,16 +569,5 @@ export function makePostChain(renderer, scene, { width, height, options = {} } =if (gtao) gtao.camera = camera;composer.render();},- setSize(w, h) {- composer.setSize(w, h);- if (gtao) gtao.setSize(w, h);- if (glow) glow.setSize(w, h);- },- dispose() {- for (const p of composer.passes) { if (typeof p.dispose === 'function') p.dispose(); }- if (glow) glow.dispose();- composer.renderTarget1.dispose();- composer.renderTarget2.dispose();- },};}diff --git a/harness/runtime_js/lib/browser/studio.js b/harness/runtime_js/lib/browser/studio.jsindex 9bd5e413..9f3d2deb 100644--- a/harness/runtime_js/lib/browser/studio.js+++ b/harness/runtime_js/lib/browser/studio.js@@ -102,7 +102,6 @@ function addContactShadow(scene, center, box, radius) {blob.position.set(center.x, box.min.y + radius * 2e-3, center.z);blob.renderOrder = -1;scene.add(blob);- return blob;}const DEG = Math.PI / 180;@@ -140,8 +139,7 @@ export function aimStudio(rig, azimuthDeg, elevationDeg = 0) {/*** Add environment + backdrop + lights (+ shadow catcher) to `scene`, scaled to `box`.- * Returns the rig handle `{catcher, key, fill, rim, blob, center, radius, scene}` — `catcher`- * is the shadow plane callers exclude from framing, the rest is what `aimStudio` moves.+ * Returns the rig handle `{key, fill, rim, center, radius, scene}` that `aimStudio` moves.*/export function buildStudio(renderer, scene, box, { background = 'studio', shadow = true, lights = true } = {}) {const bg = BACKGROUNDS[background];@@ -158,7 +156,7 @@ export function buildStudio(renderer, scene, box, { background = 'studio', shadoconst center = box.getCenter(new THREE.Vector3());const radius = Math.max(box.getSize(new THREE.Vector3()).length() / 2, 1e-3);- const rig = { catcher: null, key: null, fill: null, rim: null, blob: null, center, radius, scene };+ const rig = { key: null, fill: null, rim: null, center, radius, scene };if (lights) {scene.environment = environmentTexture(renderer);@@ -205,8 +203,7 @@ export function buildStudio(renderer, scene, box, { background = 'studio', shadocatcher.position.set(center.x, box.min.y - radius * 1e-3, center.z);catcher.receiveShadow = true;scene.add(catcher);- rig.catcher = catcher;- rig.blob = addContactShadow(scene, center, box, radius);+ addContactShadow(scene, center, box, radius);}return rig;}diff --git a/harness/runtime_js/lib/host_ablation.mjs b/harness/runtime_js/lib/host_ablation.mjsindex e5adbc6c..7fb6636a 100644--- a/harness/runtime_js/lib/host_ablation.mjs+++ b/harness/runtime_js/lib/host_ablation.mjs@@ -32,7 +32,7 @@* stated once, there (law 2 in spirit: import, never restate).*/-import { classifyBackdrop } from './backdrop.mjs';+import { classifyBackdrop, worldBox } from './backdrop.mjs';import { isCustomShader } from './host_census.mjs';/** Per-channel difference (0..255) that counts a pixel as changed. */@@ -123,16 +123,6 @@ export function unpatchedClone(mat, THREE) {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}>}@@ -203,26 +193,18 @@ export function ablate(scene, THREE, { only = null } = {}) {/*** 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`).+ * `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;- 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,- };+ return { changed_frac: +(changed / Math.max(n, 1)).toFixed(4) };}/**@@ -245,7 +227,6 @@ export function frameSampler(canvas) {ctx.drawImage(canvas, 0, 0, w, h);return ctx.getImageData(0, 0, w, h).data;};- sample.grid = [w, h];return sample;}@@ -268,7 +249,7 @@ export function frameSampler(canvas) {* @param {object} THREE* @param {{renderFrame: (spec:object)=>Uint8ClampedArray, cameras: object[],* maxMaterials?: number, threshold?: number, maxRenders?: number,- * grid?: number[], snapshot?: ()=>string}} opts+ * 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@@ -277,7 +258,7 @@ export function frameSampler(canvas) {*/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;+ 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 oneconst seen = new Set();@@ -285,8 +266,6 @@ export function ablationReport(scene, THREE, opts) {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,@@ -313,7 +292,7 @@ export function ablationReport(scene, THREE, opts) {// 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 };+ row = { camera: spec.name, changed_frac: 0 };} else {const undo = ablate(scene, THREE, {});let b;diff --git a/harness/runtime_js/lib/host_census.mjs b/harness/runtime_js/lib/host_census.mjsindex cc4b8e0f..41cfca70 100644--- a/harness/runtime_js/lib/host_census.mjs+++ b/harness/runtime_js/lib/host_census.mjs@@ -6,7 +6,7 @@* overlap statistics. Returns plain JSON.*/-import { classifyBackdrop } from './backdrop.mjs';+import { classifyBackdrop, worldBox } from './backdrop.mjs';import { geometryTriangles as triCount } from './census.mjs';import { placementTable } from './host_placement.mjs';@@ -79,12 +79,11 @@ function walkGroup(root, THREE) {tris += triCount(o.geometry) * count;const mats = Array.isArray(o.material) ? o.material : [o.material];if (mats.some((m) => isCustomShader(m, THREE))) custom += 1;- if (!o.geometry) return;- if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();- const gb = o.geometry.boundingBox;- if (!gb || gb.isEmpty()) return;- const mb = new THREE.Box3();+ let mb = worldBox(o, THREE);+ if (!mb) return;if (o.isInstancedMesh) {+ const gb = o.geometry.boundingBox;+ mb = new THREE.Box3();const m = new THREE.Matrix4();const n = Math.min(o.count, 4096);for (let i = 0; i < n; i++) {@@ -94,7 +93,6 @@ function walkGroup(root, THREE) {copy(o.name || 'instances', tmp);}} else {- mb.copy(gb).applyMatrix4(o.matrixWorld);copy((o.name || '').replace(/[_.]\d+$/, '') || 'meshes', mb);}if (mb.isEmpty()) return;diff --git a/harness/runtime_js/lib/host_coverage.mjs b/harness/runtime_js/lib/host_coverage.mjsindex 796150aa..289abcdb 100644--- a/harness/runtime_js/lib/host_coverage.mjs+++ b/harness/runtime_js/lib/host_coverage.mjs@@ -11,22 +11,17 @@* the content bbox (scatter across the whole ground) as backdrop.*/-import { classifyBackdrop, nonSolid } from './backdrop.mjs';+import { classifyBackdrop, nonSolid, worldBox } from './backdrop.mjs';import { sampleFrame } from './host_metrics.mjs';function collectDrawables(scene, THREE, contentSpan) {const out = [];- const box = new THREE.Box3();scene.traverse((o) => {if (!o.visible) return;if (!(o.isMesh || o.isPoints || o.isLine || o.isSprite)) return;- if (!o.geometry) return;- if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();- const gb = o.geometry.boundingBox;- if (!gb || gb.isEmpty()) return;- box.copy(gb).applyMatrix4(o.matrixWorld);- out.push({ obj: o, kind: classifyBackdrop(o, box, contentSpan) });+ const box = worldBox(o, THREE);+ if (box) out.push({ obj: o, kind: classifyBackdrop(o, box, contentSpan) });});return out;}diff --git a/harness/runtime_js/lib/host_env.mjs b/harness/runtime_js/lib/host_env.mjsindex e570436c..74ac5d28 100644--- a/harness/runtime_js/lib/host_env.mjs+++ b/harness/runtime_js/lib/host_env.mjs@@ -16,40 +16,18 @@ export const RUNTIME_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.const gpuLaunch = require_(path.join(RUNTIME_ROOT, 'gpu_launch.cjs'));const serve = require_(path.join(RUNTIME_ROOT, 'serve.cjs'));-/**- * Launch (or connect to) a headless browser; see gpu_launch.cjs.- * @param {{gpu?: 'auto'|'on'|'off'}} opts- * @returns {Promise<{browser: object, gpu: boolean, renderer: string, release: () => Promise<void>}>}- */-export async function launchBrowser(opts = {}) {- return gpuLaunch.launchBrowser(opts);-}--/**- * Serve arbitrary directories / in-memory routes (see serve.cjs); runtime_js is- * always mounted at `runtimeMount()`. The object renderer serves the GLB's- * directory this way; scenes go through `serveWorkspace` below.- * @returns {Promise<{server, base: string, url: (p: string) => string, close: () => Promise<void>}>}- */-export async function serveDirs(opts = {}) {- return serve.serveDirs(opts);-}--/** URL prefix under which runtime_js is served ('/__runtime/'). */-export function runtimeMount() {- return serve.RUNTIME_MOUNT;-}--/** Import map that resolves 'three' and 'three/addons/*' to the local runtime copy. */-export function importMapHtml() {- return serve.importMapHtml();-}+// launchBrowser({gpu}) — see gpu_launch.cjs. serveDirs({root, mounts, routes}) — the object+// renderer serves the GLB's directory this way; scenes go through `serveWorkspace` below.+// importMapHtml() resolves 'three' and 'three/addons/*' to the local runtime copy, which is+// served under RUNTIME_MOUNT ('/__runtime/').+export const { launchBrowser } = gpuLaunch;+export const { serveDirs, importMapHtml, RUNTIME_MOUNT } = serve;/*** Serve a workspace on 127.0.0.1:0 with these mounts:* /src/** /public/** → <ws>/src, <ws>/public* /assets/** → <ws>/public/assets (contract: '/assets/x.glb')- * <runtimeMount()>/** → runtime_js (node_modules/three, lib/*.mjs)+ * <RUNTIME_MOUNT>/** → runtime_js (node_modules/three, lib/*.mjs)* /__host.html → generated host page (import map + scene_host.mjs)* @returns {Promise<{server, base: string, close: () => Promise<void>}>}*/diff --git a/harness/runtime_js/lib/host_metrics.mjs b/harness/runtime_js/lib/host_metrics.mjsindex 86e257cf..cfde63a2 100644--- a/harness/runtime_js/lib/host_metrics.mjs+++ b/harness/runtime_js/lib/host_metrics.mjs@@ -3,7 +3,7 @@* readback of the render canvas and near-geometry tests for a camera.*/-import { GROUND_NAME_RE, classifyBackdrop, nonSolid } from './backdrop.mjs';+import { GROUND_NAME_RE, classifyBackdrop, nonSolid, worldBox } from './backdrop.mjs';export const SAMPLE_W = 96;export const SAMPLE_H = 54;@@ -28,7 +28,6 @@ export function sampleFrame(canvas) {export function frameStats(canvas) {const { data, n } = sampleFrame(canvas);let sum = 0, sumSq = 0, dark = 0, blown = 0;- let top = 0, bottom = 0;const hist = new Uint32Array(8);for (let i = 0; i < n; i++) {const r = data[i * 4], g = data[i * 4 + 1], b = data[i * 4 + 2];@@ -37,7 +36,6 @@ export function frameStats(canvas) {if (lum < 10) dark += 1;if (r > 250 && g > 250 && b > 250) blown += 1;hist[Math.min(7, Math.floor(lum / 32))] += 1;- if (i < n / 2) top += lum; else bottom += lum;}const mean = sum / n;const std = Math.sqrt(Math.max(0, sumSq / n - mean * mean));@@ -50,7 +48,6 @@ export function frameStats(canvas) {dark_frac: +(dark / n).toFixed(4),blown_frac: +(blown / n).toFixed(4),modal_frac: +(modal / n).toFixed(4),- top_bottom_ratio: +((top + 1) / (bottom + 1)).toFixed(3),};}@@ -131,27 +128,23 @@ export function nearGeometry(scene, camera, THREE, limitM = 0.3, lookAt = null)scene.traverse((o) => { if ((o.isMesh || o.isInstancedMesh) && o.visible && !nonSolid(o)) targets.push(o); });const pts = [];for (let gy = -1; gy <= 1; gy++) for (let gx = -1; gx <= 1; gx++) pts.push([gx * 0.6, gy * 0.6]);- let hits = 0;let nearRays = 0;for (const [x, y] of pts) {rc.setFromCamera(new THREE.Vector2(x, y), camera);let hit = null;try { hit = rc.intersectObjects(targets, false)[0]; } catch (e) { hit = null; }if (hit) {- hits += 1;if (hit.distance < BLOCKED_M) nearRays += 1;if (hit.distance < nearest) { nearest = hit.distance; nearestName = hit.object.name || hit.object.parent?.name || hit.object.type; }}}const inside = [];const eye = camera.position;- const box = new THREE.Box3();const groundMeshes = [];for (const o of targets) {if (o.isInstancedMesh) continue;- if (!o.geometry) continue;- if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();- box.copy(o.geometry.boundingBox).applyMatrix4(o.matrixWorld);+ const box = worldBox(o, THREE);+ if (!box) continue;const s = box.getSize(new THREE.Vector3());// terrain overhead must also be NAMED as ground: a 40 m 'Ceiling' is ground-shaped to the// classifier, and loop 25's cathedral read "camera 17.8 m under Ceiling" on every interior@@ -199,12 +192,9 @@ export function nearGeometry(scene, camera, THREE, limitM = 0.3, lookAt = null)} catch (e) { targetHit = null; }}}- const center = new THREE.Vector3();- camera.getWorldDirection(center);return {nearest_hit_m: Number.isFinite(nearest) ? +nearest.toFixed(3) : null,nearest_hit_name: nearestName,- rays_hit: hits,rays_total: pts.length,inside_mesh_bbox: inside.slice(0, 5),camera_in_geometry: (Number.isFinite(nearest) && nearest < limitM) || inside.length > 0,@@ -218,7 +208,6 @@ export function nearGeometry(scene, camera, THREE, limitM = 0.3, lookAt = null)target_distance_m: targetDist,target_hit_m: targetHit,target_hit_name: targetHitName,- look_dir: [center.x, center.y, center.z].map((v) => +v.toFixed(3)),};}diff --git a/harness/runtime_js/lib/host_page.mjs b/harness/runtime_js/lib/host_page.mjsindex f0c85eab..34d7ed53 100644--- a/harness/runtime_js/lib/host_page.mjs+++ b/harness/runtime_js/lib/host_page.mjs@@ -6,7 +6,7 @@import fs from 'node:fs';import path from 'node:path';-import { importMapHtml, launchBrowser, runtimeMount, serveWorkspace } from './host_env.mjs';+import { importMapHtml, launchBrowser, RUNTIME_MOUNT, serveWorkspace } from './host_env.mjs';const SHADER_NOISE_RE = /shader|program not valid|glsl|WebGL|compile|THREE\.WebGLProgram/i;const MAX_CONSOLE = 60;@@ -17,7 +17,7 @@ function hostHtml() {'<!doctype html><html><head><meta charset="utf-8"><title>3dcode scene host</title>',importMapHtml(),'<style>html,body{margin:0;background:#000;overflow:hidden}</style></head><body>',- `<script type="module" src="${runtimeMount()}lib/scene_host.mjs"></script></body></html>`,+ `<script type="module" src="${RUNTIME_MOUNT}lib/scene_host.mjs"></script></body></html>`,].join('\n');}diff --git a/harness/runtime_js/lib/host_placement.mjs b/harness/runtime_js/lib/host_placement.mjsindex bd140020..ad5fa5c7 100644--- a/harness/runtime_js/lib/host_placement.mjs+++ b/harness/runtime_js/lib/host_placement.mjs@@ -413,6 +413,38 @@ function pairs(checked) {return out.sort((x, y) => y.aabb_overlap - x.aabb_overlap).slice(0, 40);}+/** Index `scene` once and collect its assets; `owner(mesh)` names the asset a mesh belongs to. */+function survey(scene, opts) {+ const notes = [];+ scene.updateMatrixWorld(true);+ const { map: indices, volumetric } = indexMeshes(scene, notes);+ const { assets, total } = collectAssets(scene, indices, volumetric, opts.contentBox || null);+ const meshOwner = new Map();+ for (const a of assets) { a.meshSet = new Set(a.meshes); for (const ci of a.meshes) meshOwner.set(ci.mesh, a.name); }+ const groundY = Number.isFinite(opts.groundY) ? opts.groundY : null;+ return { groundY, notes, indices, assets, total, owner: (mesh) => meshOwner.get(mesh) || nearestName(mesh) };+}++/** Probe every foot column of `a`: smallest gap (`best`), deepest and shallowest burial (`sunk`,+ * `minSunk` — 0 once a column is not sunk), whether an unsunk column rests, any foot in water. */+function probeFeet(a, indices, owner, groundY) {+ const cols = footColumns(a);+ const f = { columns: cols.length, best: null, sunk: null, water: false, minSunk: Infinity, anyRest: false };+ for (const col of cols) {+ const r = probeColumn(a, col, indices, owner, groundY);+ if (r.gap !== null && (!f.best || r.gap < f.best.gap)) f.best = r;+ if (r.sunk > 0) {+ if (!f.sunk || r.sunk > f.sunk.sunk) f.sunk = r;+ f.minSunk = Math.min(f.minSunk, r.sunk);+ } else {+ f.minSunk = 0;+ if (r.gap !== null && r.gap <= CONTACT_TOL_M) f.anyRest = true;+ }+ if (r.water) f.water = true; // one foot in the water is enough: a jetty is half on the shore+ }+ return f;+}+/*** The placement table for `scene`.* @param {THREE.Scene} scene@@ -421,14 +453,7 @@ function pairs(checked) {*/export function placementTable(scene, THREE, opts = {}) {const t0 = Date.now();- const groundY = Number.isFinite(opts.groundY) ? opts.groundY : null;- const notes = [];- scene.updateMatrixWorld(true);- const { map: indices, volumetric } = indexMeshes(scene, notes);- const { assets, total } = collectAssets(scene, indices, volumetric, opts.contentBox || null);- const meshOwner = new Map();- for (const a of assets) { a.meshSet = new Set(a.meshes); for (const ci of a.meshes) meshOwner.set(ci.mesh, a.name); }- const owner = (mesh) => meshOwner.get(mesh) || nearestName(mesh);+ const { groundY, notes, indices, assets, total, owner } = survey(scene, opts);const checked = [];let timeCut = false;const rows = [];@@ -437,18 +462,11 @@ export function placementTable(scene, THREE, opts = {}) {exempt: a.exempt, bbox: a.min ? boxJson(a.min, a.max) : null };if (a.exempt) { rows.push(row); continue; }if (Date.now() - t0 > TIME_BUDGET_MS) { row.exempt = 'time_budget'; timeCut = true; rows.push(row); continue; }- const cols = footColumns(a);- let best = null, sunk = null, water = false;- for (const col of cols) {- const r = probeColumn(a, col, indices, owner, groundY);- if (r.gap !== null && (!best || r.gap < best.gap)) best = r;- if (r.sunk > 0 && (!sunk || r.sunk > sunk.sunk)) sunk = r;- if (r.water) water = true; // one foot in the water is enough: a jetty is half on the shore- }+ const { columns, best, sunk, water } = probeFeet(a, indices, owner, groundY);a.attached = [];a.row = row;Object.assign(row, {- columns: cols.length,+ columns,ground_gap_m: best ? r3(best.gap) : null,support: best ? best.support : '',sunk_m: sunk ? r3(sunk.sunk) : 0,@@ -508,36 +526,14 @@ const PARTIAL_OK_RE = /\b(boulders?|bridges?|bush(es)?|cliffs?|docks?|dunes?|fen* their support. Returns `{count, moves}`; mutates object positions (world-space dy* applied through each parent's frame) and leaves matrices updated. */export function settleScene(scene, THREE, opts = {}) {- const groundY = Number.isFinite(opts.groundY) ? opts.groundY : null;- const notes = [];- scene.updateMatrixWorld(true);- const { map: indices, volumetric } = indexMeshes(scene, notes);- const { assets } = collectAssets(scene, indices, volumetric, opts.contentBox || null);+ const { groundY, indices, assets, owner } = survey(scene, opts);const checked = assets.filter((a) => !a.exempt);- for (const a of checked) { a.meshSet = new Set(a.meshes); }- const meshOwner = new Map();- for (const a of assets) for (const ci of a.meshes) meshOwner.set(ci.mesh, a.name);- const owner = (mesh) => meshOwner.get(mesh) || nearestName(mesh);const moves = [];const t0 = Date.now();for (const a of checked) {if (Date.now() - t0 > TIME_BUDGET_MS) break;- const cols = footColumns(a);- if (!cols.length) continue;- let best = null, sunk = null, water = false, minSunk = Infinity, anyRest = false;- for (const col of cols) {- const r = probeColumn(a, col, indices, owner, groundY);- if (r.gap !== null && (!best || r.gap < best.gap)) best = r;- if (r.sunk > 0) {- if (!sunk || r.sunk > sunk.sunk) sunk = r;- minSunk = Math.min(minSunk, r.sunk);- } else {- minSunk = 0;- if (r.gap !== null && r.gap <= CONTACT_TOL_M) anyRest = true;- }- if (r.water) water = true;- }- if (water) continue;+ const { columns, best, sunk, water, minSunk, anyRest } = probeFeet(a, indices, owner, groundY);+ if (!columns || water) continue;const name = spaced(a.name);const height = Math.max(a.max[1] - a.min[1], 1e-6);let dy = 0, why = '';diff --git a/harness/runtime_js/lib/node_polyfills.mjs b/harness/runtime_js/lib/node_polyfills.mjsindex 64c1f45f..6a899c73 100644--- a/harness/runtime_js/lib/node_polyfills.mjs+++ b/harness/runtime_js/lib/node_polyfills.mjs@@ -6,8 +6,6 @@//// import { installExporterPolyfills } from './node_polyfills.mjs';-import { Blob as NodeBlob } from 'node:buffer';-class FileReaderShim {constructor() {this.result = null;@@ -43,20 +41,8 @@ class FileReaderShim {}}-/** Install the shims once (idempotent); returns the list of names installed. */+/** Install the shims once (idempotent). */export function installExporterPolyfills() {- const installed = [];- if (typeof globalThis.self === 'undefined') {- globalThis.self = globalThis;- installed.push('self');- }- if (typeof globalThis.Blob === 'undefined') {- globalThis.Blob = NodeBlob;- installed.push('Blob');- }- if (typeof globalThis.FileReader === 'undefined') {- globalThis.FileReader = FileReaderShim;- installed.push('FileReader');- }- return installed;+ if (typeof globalThis.self === 'undefined') globalThis.self = globalThis;+ if (typeof globalThis.FileReader === 'undefined') globalThis.FileReader = FileReaderShim;}diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjsindex b081f98c..ba6d5303 100644--- a/harness/runtime_js/lib/scene_host.mjs+++ b/harness/runtime_js/lib/scene_host.mjs@@ -21,7 +21,7 @@ import { sceneCensus } from './host_census.mjs';import { placementTable, settleScene } from './host_placement.mjs';import { frameStats, nearGeometry, repairCameraSpec } from './host_metrics.mjs';import { frameCoverage, glbCoverage } from './host_coverage.mjs';-import { classifyBackdrop, nonSolid } from './backdrop.mjs';+import { classifyBackdrop, nonSolid, worldBox } from './backdrop.mjs';import { installShaderErrorHook } from './host_shader_errors.mjs';import { attributeErrors, captured, captureMaterialSources, materialAudit } from './host_compile.mjs';import { makeRenderer, rendererString } from './browser/renderer.js';@@ -148,15 +148,11 @@ function makeLoaders(manager) {/** geometry uuid -> world box of every mesh drawing it (the GLB bookkeeping's one traversal). */function geometryBoxes(scene) {const used = new Map();- const box = new THREE.Box3();scene.traverse((o) => {if (!o.geometry || !o.geometry.uuid || !(o.isMesh || o.isInstancedMesh)) return;- if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();if (!used.has(o.geometry.uuid)) used.set(o.geometry.uuid, new THREE.Box3());- if (o.geometry.boundingBox && !o.geometry.boundingBox.isEmpty()) {- box.copy(o.geometry.boundingBox).applyMatrix4(o.matrixWorld);- used.get(o.geometry.uuid).union(box);- }+ const box = worldBox(o, THREE);+ if (box) used.get(o.geometry.uuid).union(box);});return used;}@@ -513,19 +509,16 @@ function renderOnce(cam) {*/function skyLayersBelow(eye) {const out = [];- const box = new THREE.Box3();state.scene.traverse((o) => {if (!(o.isMesh || o.isInstancedMesh) || !o.visible || !o.geometry) return;if (o.parent && o.parent.name === 'RoomShell' && /^Ceiling/.test(o.name || '')) {- if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();- box.copy(o.geometry.boundingBox).applyMatrix4(o.matrixWorld);- if (!box.isEmpty() && box.max.y < eye.y) out.push(o);+ const box = worldBox(o, THREE);+ if (box && box.max.y < eye.y) out.push(o);return;}if (!nonSolid(o)) return;- if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();- if (o.geometry.boundingBox.isEmpty()) return;- box.copy(o.geometry.boundingBox).applyMatrix4(o.matrixWorld);+ const box = worldBox(o, THREE);+ if (!box) return;if (o.frustumCulled === false && o.geometry.isInstancedBufferGeometry) {// an instanced billboard deck keeps its quad at the origin and offsets it in the shader:// its instance offsets are the only honest extent@@ -666,12 +659,10 @@ function ablation(opts = {}) {const sample = frameSampler(state.canvas);const renderFrame = (spec) => { renderOnce(buildCamera(spec)); return sample(); };const snapshot = opts.frames ? () => state.canvas.toDataURL('image/png') : null;- const report = ablationReport(state.scene, THREE, {- renderFrame, snapshot, cameras, grid: sample.grid,+ return ablationReport(state.scene, THREE, {+ renderFrame, snapshot, cameras,maxMaterials: opts.maxMaterials, threshold: opts.threshold, maxRenders: opts.maxRenders,});- report.sim_time = state.simTime;- return report;}/** Per-asset placement table (host_placement.mjs) — never throws: a failure is `{error}`. */diff --git a/harness/runtime_js/lib/three_redirect.mjs b/harness/runtime_js/lib/three_redirect.mjsindex e222158c..3f711a1f 100644--- a/harness/runtime_js/lib/three_redirect.mjs+++ b/harness/runtime_js/lib/three_redirect.mjs@@ -11,7 +11,7 @@ const RUNTIME_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '/** Parent URL to resolve from; must end with '/' so it acts as a directory. */export const RUNTIME_PARENT = pathToFileURL(RUNTIME_DIR + path.sep).href;-const REDIRECTED = ['three', 'three-mesh-bvh'];+const REDIRECTED = ['three'];export function isRedirected(spec) {return REDIRECTED.some((p) => spec === p || spec.startsWith(p + '/'));diff --git a/harness/runtime_js/package-lock.json b/harness/runtime_js/package-lock.jsonindex d30c817e..68747162 100644--- a/harness/runtime_js/package-lock.json+++ b/harness/runtime_js/package-lock.json@@ -9,8 +9,7 @@"version": "0.1.0","dependencies": {"puppeteer": "^24.43.1",- "three": "^0.182.0",- "three-mesh-bvh": "^0.9.0"+ "three": "^0.182.0"},"engines": {"node": ">=20.6.0"@@ -1018,15 +1017,6 @@"integrity": "sha512-GbHabT+Irv+ihI1/f5kIIsZ+Ef9Sl5A1Y7imvS5RQjWgtTPfPnZ43JmlYI7NtCRDK9zir20lQpfg8/9Yd02OvQ==","license": "MIT"},- "node_modules/three-mesh-bvh": {- "version": "0.9.14",- "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.14.tgz",- "integrity": "sha512-xJzfUXnLYjgw5tRKGxjfJW3Pcx0IbwNskvpdwRryhK07SYrKrYB4W8zAaPxu784gK7G4lCBgG+vfG3YeYn95kg==",- "license": "MIT",- "peerDependencies": {- "three": ">= 0.159.0"- }- },"node_modules/tslib": {"version": "2.8.1","resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",diff --git a/harness/runtime_js/package.json b/harness/runtime_js/package.jsonindex bcf22efc..c9226dae 100644--- a/harness/runtime_js/package.json+++ b/harness/runtime_js/package.json@@ -9,7 +9,6 @@},"dependencies": {"three": "^0.182.0",- "puppeteer": "^24.43.1",- "three-mesh-bvh": "^0.9.0"+ "puppeteer": "^24.43.1"}}diff --git a/harness/runtime_js/probe_scene.mjs b/harness/runtime_js/probe_scene.mjsindex ce1cfbe5..19022f03 100644--- a/harness/runtime_js/probe_scene.mjs+++ b/harness/runtime_js/probe_scene.mjs@@ -86,16 +86,14 @@ async function main() {// exercise update() for a few fixed steps and one tiny render (lazy programs compile)const upd = await page.evaluate((n) => {try {- const cam = window.__c3v.cameras()[0];- const r = window.__c3v.renderAt(cam, n / 30);- return { ok: true, sim_time: r.sim_time, ms: r.ms };+ window.__c3v.renderAt(window.__c3v.cameras()[0], n / 30);+ return { ok: true };} catch (e) {return { ok: false, error: String((e && e.stack) || e).slice(0, 800) };}}, 10);result.update_ok = upd.ok;result.update_error = upd.error || '';- result.first_render_ms = upd.ms;// update() exceptions are caught page-side (rendering continues); still a probe failureconst updateErrors = await page.evaluate(() => window.__c3v.updateErrors());if (upd.ok && updateErrors.length) {diff --git a/harness/runtime_js/render_glb.mjs b/harness/runtime_js/render_glb.mjsindex 8d2aef4a..f82294d8 100644--- a/harness/runtime_js/render_glb.mjs+++ b/harness/runtime_js/render_glb.mjs@@ -18,7 +18,7 @@ import fs from 'node:fs';import path from 'node:path';import { ensureDir, finish, parseCli, writeJson } from './lib/cli.mjs';-import { launchBrowser, importMapHtml, runtimeMount, serveDirs } from './lib/host_env.mjs';+import { launchBrowser, importMapHtml, RUNTIME_MOUNT, serveDirs } from './lib/host_env.mjs';import { bounded, releaseBrowser } from './lib/host_page.mjs';const MODES = ['shaded', 'wire', 'normals', 'silhouette', 'clay'];@@ -64,7 +64,7 @@ function pageHtml(cfg) {<style>html,body{margin:0;background:#000}canvas{display:block}</style></head><body><canvas id="c" width="${cfg.width}" height="${cfg.height}"></canvas><script type="module">-import { renderGlbViews } from '${runtimeMount()}lib/browser/render_rig.js';+import { renderGlbViews } from '${RUNTIME_MOUNT}lib/browser/render_rig.js';window.__c3v_result = null;renderGlbViews(${JSON.stringify(config_)}).then((r) => { window.__c3v_result = r; },diff --git a/harness/runtime_js/serve.cjs b/harness/runtime_js/serve.cjsindex 7eb48fb5..ab611efc 100644--- a/harness/runtime_js/serve.cjs+++ b/harness/runtime_js/serve.cjs@@ -94,7 +94,7 @@ function resolveInside(rootAbs, relUrlPath) {/*** Serve one or more directories on 127.0.0.1:<random port>.- * @param {{root?: string, mounts?: Record<string,string>, routes?: Record<string,{body:string|Buffer,type?:string}>, log?: boolean}} opts+ * @param {{root?: string, mounts?: Record<string,string>, routes?: Record<string,{body:string|Buffer,type?:string}>}} opts* root - directory served at '/'* mounts - url prefix ('/name/') -> directory; checked before root. runtime_js is always mounted at RUNTIME_MOUNT.* routes - exact url path -> in-memory response (e.g. a generated HTML page).@@ -107,11 +107,9 @@ async function serveDirs(opts = {}) {mounts[prefix] = path.resolve(dir);}const routes = opts.routes || {};- const requests = [];const server = http.createServer((req, res) => {const urlPath = decodeURIComponent((req.url || '/').split('?')[0]);- if (opts.log) requests.push(urlPath);res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Cache-Control', 'no-store');@@ -150,7 +148,6 @@ async function serveDirs(opts = {}) {return {server,base,- requests,url: (p) => base + (p.startsWith('/') ? p : '/' + p),close: () => new Promise((resolve) => server.close(() => resolve())),};@@ -158,15 +155,13 @@ async function serveDirs(opts = {}) {/*** `<script type="importmap">` that maps 'three' and 'three/addons/' onto the- * locally served runtime (no CDN). `extra` adds more bare specifiers.+ * locally served runtime (no CDN).*/-function importMapHtml(extra = {}) {+function importMapHtml() {const imports = {three: `${RUNTIME_MOUNT}node_modules/three/build/three.module.js`,'three/addons/': `${RUNTIME_MOUNT}node_modules/three/examples/jsm/`,'three/examples/jsm/': `${RUNTIME_MOUNT}node_modules/three/examples/jsm/`,- 'three-mesh-bvh': `${RUNTIME_MOUNT}node_modules/three-mesh-bvh/build/index.module.js`,- ...extra,};return `<script type="importmap">${JSON.stringify({ imports })}</script>`;}diff --git a/harness/tests/scene_runtime/test_ablation.py b/harness/tests/scene_runtime/test_ablation.pyindex 5f69fcb2..f37fea22 100644--- a/harness/tests/scene_runtime/test_ablation.py+++ b/harness/tests/scene_runtime/test_ablation.py@@ -205,9 +205,9 @@ try { frameDiff(flat, new Uint8ClampedArray(8)); } catch (e) { threw = e.messageconsole.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 out["same"]["changed_frac"] == 0.0+ assert out["under"]["changed_frac"] == 0.0+ assert out["quarter"]["changed_frac"] == 0.25assert "differ in size" in out["threw"]diff --git a/harness/tests/threejs_render/test_build.py b/harness/tests/threejs_render/test_build.pyindex c6ae36f8..e77cfc93 100644--- a/harness/tests/threejs_render/test_build.py+++ b/harness/tests/threejs_render/test_build.py@@ -26,7 +26,7 @@ def test_build_stool_glb_and_census(stool_ws: Workspace):assert [p["name"] for p in c["parts"]] == ["Seat", "Legs", "Stretchers"]assert c["tri_count"] > 500 and c["n_meshes"] == 9assert c["tick_present"] is True- assert c["normalised_offset"] is None and c["placement_offset"] is None+ assert c["placement_offset"] is Noneassert c["instanced_meshes_baked"] == 0 and c["selfcheck_ran"] is Falseassert c["unnamed_meshes"] == 0assert "Leg_LB" in c["parts"][1]["children"]@@ -79,8 +79,7 @@ def test_build_keeps_source_placement_and_warns(stool_ws: Workspace):p = stool_ws.src / "object.js"p.write_text(p.read_text().replace("return root;", "root.position.set(0.5, 0.2, 0); return root;"))res = ThreeJsRuntime().build(stool_ws)- assert res.ok- assert res.census["normalised_offset"] is None+ assert res.ok and "normalised_offset" not in res.censusoff = res.census["placement_offset"]assert off is not None and abs(off[0] + 0.5) < 1e-4 and abs(off[1] + 0.2) < 1e-4assert any("off ground/centre" in w and "exported as authored" in w for w in res.census["warnings"])diff --git a/harness/tests/threejs_render/test_camera_fit.py b/harness/tests/threejs_render/test_camera_fit.pyindex a60ec72d..9b2345f1 100644--- a/harness/tests/threejs_render/test_camera_fit.py+++ b/harness/tests/threejs_render/test_camera_fit.py@@ -30,7 +30,7 @@ def _fit_report(tmp_path) -> list[dict]:script = tmp_path / "fit.mjs"script.write_text(f"""import * as THREE from 'three';-import {{ fitCameraToBox, boxCorners, viewDirection }} from {json.dumps(str(runtime_js_dir() / 'lib/browser/camera_fit.js'))};+import {{ fitCameraToBox, viewDirection }} from {json.dumps(str(runtime_js_dir() / 'lib/browser/camera_fit.js'))};const views = {json.dumps(VIEWS)}, boxes = {json.dumps(BOXES)};const rows = [];for (const [bi, [mn, mx]] of boxes.entries()) {{@@ -40,8 +40,8 @@ for (const [bi, [mn, mx]] of boxes.entries()) {{const cam = new THREE.PerspectiveCamera(35, aspect, 0.01, 100);const fit = fitCameraToBox(cam, box, v.azimuth, v.elevation, {{ fill: 0.85 }});let maxExt = 0;- for (const c of boxCorners(box)) {{- const n = c.clone().project(cam);+ for (const x of [mn[0], mx[0]]) for (const y of [mn[1], mx[1]]) for (const z of [mn[2], mx[2]]) {{+ const n = new THREE.Vector3(x, y, z).project(cam);maxExt = Math.max(maxExt, Math.abs(n.x), Math.abs(n.y));}}const centre = box.getCenter(new THREE.Vector3());diff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.pyindex 126c6e10..cd81583f 100644--- a/harness/tests/threejs_render/test_runtime_js.py+++ b/harness/tests/threejs_render/test_runtime_js.py@@ -20,14 +20,8 @@ def test_export_cli_writes_census_and_error_json(stool_ws: Workspace, tmp_path:rec = res.last_jsonassert rec["ok"] and rec["parts"] == 3 and (stool_ws.root / "artifacts/o.glb").is_file()census = json.loads((stool_ws.root / "artifacts/c.json").read_text())- assert set(census) >= {"object_name", "parts", "tri_count", "bbox", "materials", "normalised_offset", "warnings", "tick_present"}+ assert set(census) >= {"object_name", "parts", "tri_count", "bbox", "materials", "placement_offset", "warnings", "tick_present"}assert census["three_revision"] == "182"- # --normalise 1 (dataset canonicalisation only; never passed by ThreeJsRuntime) translates the group- (stool_ws.src / "object.js").write_text((stool_ws.src / "object.js").read_text().replace("return root;", "root.position.set(0.5, 0.2, 0); return root;"))- res = run_node(rt / "export_glb.mjs", ["--ws", str(stool_ws.root), "--out", "artifacts/n.glb", "--census", "artifacts/n.json", "--normalise", "1"], three_hook=True, timeout_s=60)- census = json.loads((stool_ws.root / "artifacts/n.json").read_text())- assert census["normalised_offset"] == census["placement_offset"] and abs(census["placement_offset"][0] + 0.5) < 1e-4- assert abs(census["bbox"]["min"][1]) < 1e-3 and any("--normalise 1" in w for w in census["warnings"])# error path: unknown entrywith pytest.raises(NodeError) as ei:run_node(rt / "export_glb.mjs", ["--ws", str(stool_ws.root), "--entry", "src/nope.js"], three_hook=True, timeout_s=60)