Official Codebase of 3DCodeVerse
Python
scene_placement: a mesh that writes no depth is fog, not matter
ziyao1b9769a6f82e
diff --git a/harness/runtime_js/lib/host_placement.mjs b/harness/runtime_js/lib/host_placement.mjsindex 8178649d..aeeb9fb8 100644--- a/harness/runtime_js/lib/host_placement.mjs+++ b/harness/runtime_js/lib/host_placement.mjs@@ -40,9 +40,11 @@* Exempt (listed with a reason, never scored): lights, cameras, ground / sky* meshes (`backdrop.mjs` rules), enclosures whose AABB swallows the content box,* instanced-only assets (scatter cannot be sampled per instance at this budget;- * instanced meshes are also never used as support), and anything the author tags- * `userData.placement = 'free'` on the asset or its zone (a bird, a hanging- * lantern, a drone). First 400 assets, 4 s budget; the table says when it cut.+ * instanced meshes are also never used as support), VOLUMETRIC assets — every mesh+ * of which writes no depth, i.e. haze, god rays, glow (`nonSolid`) — and anything+ * the author tags `userData.placement = 'free'` on the asset or its zone (a bird, a+ * hanging lantern, a drone). A volumetric mesh is not indexed at all, so it is+ * never a support, never something to sink into and never an overlap partner. First 400 assets, 4 s budget; the table says when it cut.** Vertical rays only, so every mesh gets a "column index": world vertices once* and, above 1 500 triangles, a uniform XZ grid of triangle buckets. A column@@ -72,6 +74,29 @@ const BARY_TOL = 1e-4;const r3 = (v) => +v.toFixed(3);+/**+ * A mesh that does not WRITE DEPTH is a volumetric pass, not matter: haze shells,+ * god rays, light shafts, glow cards. It cannot support anything, nothing can sink+ * into it, and overlapping it is what it is FOR.+ *+ * Measured on bench/out/scene_baseline (2026-09-05): every scene the generator wrote+ * uses `depthWrite: false` 34-42 times, and two of the six cells failed+ * `scene_placement` on nothing else — "BlackPine_5 is sunken 3.46 m into+ * AtmosphereHaze" (MeshBasicMaterial, opacity 0.035) and "WindowSnowView/Mesh_49 and+ * Environment/MoonlightShaft overlap 100%" (opacity 0.04, AdditiveBlending). Both+ * scenes were correct; the gate was measuring fog.+ *+ * Opacity is deliberately NOT part of the rule: glass sits at 0.3-0.6 and keeps+ * writing depth, and a greenhouse pane really is a surface. A solid wall the model+ * mistakenly wrote `depthWrite: false` on stops being a support — a missed defect,+ * which is the cheaper error, and one that matches how the frame actually renders.+ */+export function nonSolid(mesh) {+ const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];+ const real = mats.filter(Boolean);+ return real.length > 0 && real.every((m) => m.depthWrite === false);+}+/** World-space vertices + XZ triangle buckets for vertical column queries on one mesh. */class ColumnIndex {constructor(mesh) {@@ -193,22 +218,29 @@ function spaced(name) { return String(name || '').replace(/([a-z0-9])([A-Z])/g,function isWaterLike(mesh) { return !!mesh && (WATER_RE.test(spaced(mesh.name)) || WATER_RE.test(spaced(materialNames(mesh))) || WATER_RE.test(spaced(nearestName(mesh)))); }-/** Every visible, non-instanced Mesh with a position attribute → ColumnIndex (skipping giants). */+/**+ * Every visible, non-instanced Mesh with a position attribute → ColumnIndex (skipping+ * giants and volumetrics). A `nonSolid` mesh is collected into `volumetric` instead:+ * it is neither a support, nor something to sink into, nor an overlap partner, but an+ * asset made only of them still has to appear in the table with a reason.+ */function indexMeshes(scene, notes) {const map = new Map();+ const volumetric = new Set();scene.traverse((o) => {if (!o.visible || !o.isMesh || o.isInstancedMesh || !o.geometry || !o.geometry.attributes || !o.geometry.attributes.position) return;if (geometryTriangles(o.geometry) > MAX_INDEXED_TRIS) { notes.push(`skipped ${nearestName(o)}: > ${MAX_INDEXED_TRIS} triangles`); return; }+ if (nonSolid(o)) { volumetric.add(o); return; }const ci = new ColumnIndex(o);if (!ci.empty) map.set(o, ci);});- return map;+ return { map, volumetric };}function isFree(obj) { return !!(obj && obj.userData && obj.userData.placement === 'free'); }/** The placed assets: direct children of each top-level scene child (or a top-level mesh itself). */-function collectAssets(scene, indices, contentBox) {+function collectAssets(scene, indices, volumetrics, contentBox) {const assets = [];let total = 0;const seen = new Set();@@ -220,12 +252,19 @@ function collectAssets(scene, indices, contentBox) {seen.add(child);const meshes = [];let instanced = 0;- child.traverse((o) => { if (!o.visible) return; if (o.isInstancedMesh) instanced += 1; else if (indices.has(o)) meshes.push(indices.get(o)); });- if (!meshes.length && !instanced) continue;+ let volumetric = 0;+ child.traverse((o) => {+ if (!o.visible) return;+ if (o.isInstancedMesh) instanced += 1;+ else if (indices.has(o)) meshes.push(indices.get(o));+ else if (volumetrics.has(o)) volumetric += 1;+ });+ if (!meshes.length && !instanced && !volumetric) continue;total += 1;if (assets.length >= MAX_ASSETS) continue;const a = { obj: child, name: child.name || `${child.type}_${total}`, zone: zone === child ? '' : (zone.name || zone.type), meshes, instanced, exempt: '' };if (isFree(zone) || isFree(child)) a.exempt = 'free';+ else if (!meshes.length && volumetric) a.exempt = 'volumetric';else if (!meshes.length) a.exempt = 'instanced';else {a.min = [Infinity, Infinity, Infinity]; a.max = [-Infinity, -Infinity, -Infinity];@@ -368,8 +407,8 @@ export function placementTable(scene, THREE, opts = {}) {const groundY = Number.isFinite(opts.groundY) ? opts.groundY : null;const notes = [];scene.updateMatrixWorld(true);- const indices = indexMeshes(scene, notes);- const { assets, total } = collectAssets(scene, indices, opts.contentBox || null);+ 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);@@ -455,8 +494,8 @@ export function settleScene(scene, THREE, opts = {}) {const groundY = Number.isFinite(opts.groundY) ? opts.groundY : null;const notes = [];scene.updateMatrixWorld(true);- const indices = indexMeshes(scene, notes);- const { assets } = collectAssets(scene, indices, opts.contentBox || null);+ const { map: indices, volumetric } = indexMeshes(scene, notes);+ const { assets } = collectAssets(scene, indices, volumetric, opts.contentBox || null);const checked = assets.filter((a) => !a.exempt);for (const a of checked) { a.meshSet = new Set(a.meshes); }const meshOwner = new Map();diff --git a/harness/tests/scene_runtime/test_placement_volumetric.py b/harness/tests/scene_runtime/test_placement_volumetric.pynew file mode 100644index 00000000..96f833f0--- /dev/null+++ b/harness/tests/scene_runtime/test_placement_volumetric.py@@ -0,0 +1,121 @@+"""A mesh that writes no depth is fog, not matter: it supports nothing, swallows+nothing and overlaps nothing.++Measured on `bench/out/scene_baseline` (2026-09-05). Two of six scene cells failed+`scene_placement` on nothing but their own atmosphere:++ japanese_garden BambooGroveBorder/BlackPine_5 is sunken 3.46 m into AtmosphereHaze+ cozy_cabin WindowSnowView/Mesh_49 and Environment/MoonlightShaft overlap+ (100% of the smaller box)++Both scenes were correct. `AtmosphereHaze` is four DoubleSide shells of+MeshBasicMaterial at opacity 0.035 with `depthWrite: false`; `MoonlightShaft` is the+same idiom at 0.04 with AdditiveBlending. Every one of the nine recorded scenes uses+`depthWrite: false` 34-42 times, so this is the generator's standard way to write a+volumetric — not an outlier worth a special case.+"""++from __future__ import annotations++import pytest++from codeverse.config import get_settings+from tests.scene_runtime.conftest import needs_node, run_node_json++pytestmark = [pytest.mark.node, needs_node]++RUNTIME_JS = get_settings().runtime_js_dir()++#: `HAZE_DEPTH_WRITE` is the one thing that changes between the two arms below.+SCENE_JS = """+import * as THREE from 'three';+import { sceneCensus } from './lib/host_census.mjs';+const solid = new THREE.MeshStandardMaterial();+const fog = new THREE.MeshBasicMaterial({+ color: 0xffffff, transparent: true, opacity: 0.035,+ depthWrite: HAZE_DEPTH_WRITE, side: THREE.DoubleSide,+});+const box = (name, mat, sx, sy, sz, x, y, z) => {+ const m = new THREE.Mesh(new THREE.BoxGeometry(sx, sy, sz), mat);+ m.name = name; m.position.set(x, y + sy / 2, z); return m;+};+const scene = new THREE.Scene();+const env = new THREE.Group(); env.name = 'Environment'; scene.add(env);+const ground = new THREE.Mesh(new THREE.PlaneGeometry(60, 60, 8, 8), solid);+ground.name = 'Ground'; ground.rotation.x = -Math.PI / 2; env.add(ground);++// the haze: a ground-hugging shell whose TOP surface (3.45 m) cuts through the pine,+// which is the shape that produced "sunken 3.46 m into AtmosphereHaze" — it starts+// just below the pine's foot, so the probe accepts it as a surface above the foot+const haze = new THREE.Group(); haze.name = 'AtmosphereHaze';+haze.add(box('HazeShell', fog, 40, 3.5, 40, 0, -0.05, 0)); env.add(haze);+// the light shaft: a slab driven THROUGH the window, which is what a shaft is for+const shaft = new THREE.Group(); shaft.name = 'MoonlightShaft';+shaft.add(box('ShaftSlab', fog, 1.2, 6, 1.2, 3, 0, 0)); env.add(shaft);++const zone = new THREE.Group(); zone.name = 'Grove'; scene.add(zone);+zone.add(box('BlackPine', solid, 1.2, 6, 1.2, 0, 0, 0)); // stands on the ground+zone.add(box('WindowSnowView', solid, 1.4, 1.4, 0.1, 3, 1.2, 0)); // inside the shaft+scene.updateMatrixWorld(true);+const t = sceneCensus(scene, THREE, { placement: true }).placement;+console.log(JSON.stringify({+ exempt: t.exempt,+ assets: t.assets.map((a) => ({+ name: a.name, exempt: a.exempt, sunk_m: a.sunk_m, sunk_into: a.sunk_into,+ supported: a.supported, floating: a.floating,+ })),+ pairs: t.interpenetrations.map((p) => [p.a, p.b]),+}));+"""+++def _run(depth_write: str) -> dict:+ body = SCENE_JS.replace("HAZE_DEPTH_WRITE", depth_write).replace("'./lib/", f"'{RUNTIME_JS}/lib/")+ return run_node_json(body)+++def _row(out: dict, name: str) -> dict:+ rows = [a for a in out["assets"] if a["name"] == name]+ assert len(rows) == 1, (name, [a["name"] for a in out["assets"]])+ return rows[0]++[email protected](scope="module")+def volumetric() -> dict:+ return _run("false")++[email protected](scope="module")+def solid_control() -> dict:+ return _run("true")+++def test_a_depthless_shell_is_exempt_and_indexes_nothing(volumetric):+ assert volumetric["exempt"].get("volumetric") == 2+ assert _row(volumetric, "AtmosphereHaze")["exempt"] == "volumetric"+ assert _row(volumetric, "MoonlightShaft")["exempt"] == "volumetric"+++def test_a_tree_inside_the_haze_stands_on_the_ground(volumetric):+ pine = _row(volumetric, "BlackPine")+ assert pine["exempt"] == ""+ assert pine["sunk_into"] == "" and pine["sunk_m"] == 0+ assert pine["supported"] is True and pine["floating"] is False+++def test_a_light_shaft_through_a_window_is_not_an_interpenetration(volumetric):+ assert volumetric["pairs"] == []+++def test_the_same_shells_WITH_depth_write_are_still_measured(solid_control):+ """The control: the rule is `depthWrite`, not the name, the opacity or the size.+ Turn depth writing back on and the identical geometry produces exactly the two+ findings the baseline reported."""+ assert "volumetric" not in solid_control["exempt"]+ pine = _row(solid_control, "BlackPine")+ assert pine["sunk_into"] == "AtmosphereHaze" and pine["sunk_m"] == pytest.approx(3.45, abs=0.05)+ pairs = [sorted(p) for p in solid_control["pairs"]]+ assert pairs, "the control must reproduce the findings, or it controls for nothing"+ # every one of them is a solid object against fog — which is the whole point+ assert all("AtmosphereHaze" in p or "MoonlightShaft" in p for p in pairs)+ assert ["AtmosphereHaze", "BlackPine"] in pairs