Official Codebase of 3DCodeVerse
Python
three.js export: an InstancedMesh becomes sibling meshes Name_0.. in its place, so the contract gate counts every copy
gaoypeng6f1290e7dcc0
diff --git a/harness/codeverse3d/prompts/threejs/contract.md b/harness/codeverse3d/prompts/threejs/contract.mdindex adcd975f..99732e6a 100644--- a/harness/codeverse3d/prompts/threejs/contract.md+++ b/harness/codeverse3d/prompts/threejs/contract.md@@ -44,8 +44,8 @@ packages other than `three`, no `import ... from 'codeverse3d'` / `../runtime_js`MeshPhysicalMaterial` only. Colours via `new THREE.Color(0xRRGGBB)`; vertex coloursallowed (`geometry.setAttribute('color', …)` + `vertexColors: true`).* Use `InstancedMesh` or merged geometries for repeats. `InstancedMesh`- named `Posts` is exported as a group `Posts` of meshes `Posts_0 … Posts_{n-1}`- (instance matrices and colours baked), so gates and the census see every copy.+ named `Posts` is exported as sibling meshes `Posts_0 … Posts_{n-1}` in its place+ (instance matrices and colours baked), so gates see every copy as an instance of `Posts`.## Self-check (optional, keep it tiny, at the end of object.js)If `object.js` exports `selfcheck(THREE, root)`, the harness calls it on the groupdiff --git a/harness/runtime_js/export_glb.mjs b/harness/runtime_js/export_glb.mjsindex 92730b43..3c2c3fc3 100644--- a/harness/runtime_js/export_glb.mjs+++ b/harness/runtime_js/export_glb.mjs@@ -7,8 +7,8 @@// Runs in plain node (no browser). The agent module must `export function build(THREE)`// returning a THREE.Group (or a Promise of one); an optional `export function// selfcheck(THREE, root)` is called on the built group and fails the build when it-// 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+// throws. InstancedMesh objects are baked into sibling plain meshes `Name_0..`+// (lib/instances.mjs) so trimesh-based gates see every copy as an instance. 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.// Last stdout line is a JSON record:@@ -24,7 +24,7 @@ import { pathToFileURL } from 'node:url';import { finish, parseCli } from './lib/cli.mjs';import { installExporterPolyfills } from './lib/node_polyfills.mjs';import { findNonFinitePositions, worldBox } from './lib/census.mjs';-import { bakeInstancedMeshes, expandInstancedMesh } from './lib/instances.mjs';+import { bakeInstancedMeshes } from './lib/instances.mjs';import { errorRecord } from './lib/stack.mjs';import { findSyntaxError } from './lib/syntax_check.mjs';@@ -180,12 +180,8 @@ async function main() {if (group && typeof group.then === 'function') group = await group;validateGroup(THREE, group, args.entry);const selfchecked = await runSelfcheck(mod, THREE, group);- let bakedInstances = 0;- if (group.isInstancedMesh) {- group = expandInstancedMesh(THREE, group); // a bare InstancedMesh root has no parent to swap it in- bakedInstances += 1;- }- bakedInstances += bakeInstancedMeshes(THREE, group);+ const baked = bakeInstancedMeshes(THREE, group);+ group = baked.root;const tickPresent = typeof (group.userData && group.userData.tick) === 'function';if (tickPresent) delete group.userData.tick; // functions cannot be serialised into glTF extras@@ -195,7 +191,7 @@ async function main() {stripTextures(group, warnings);// what only the export knows; the object's measurements are read off the GLB (spatial/measure.py)- const census = { placement_offset: offset, instanced_meshes_baked: bakedInstances,+ const census = { placement_offset: offset, instanced_meshes_baked: baked.count,selfcheck_ran: selfchecked, tick_present: tickPresent };let unnamed = 0;group.traverse((o) => {diff --git a/harness/runtime_js/lib/instances.mjs b/harness/runtime_js/lib/instances.mjsindex ead71193..46602c5b 100644--- a/harness/runtime_js/lib/instances.mjs+++ b/harness/runtime_js/lib/instances.mjs@@ -4,15 +4,18 @@// EXT_mesh_gpu_instancing extension. Browser loaders understand that, but the// python side (trimesh: measure / connectivity / contract / cross-sections) does// not and sees a single copy at the node origin. Baking every instance into a-// named child mesh keeps the GLB, the census and every gate consistent.+// named mesh keeps the GLB, the census and every gate consistent.//// import { bakeInstancedMeshes } from './instances.mjs';-// const baked = bakeInstancedMeshes(THREE, root); // -> number of InstancedMesh objects replaced+// const { root: baked, count } = bakeInstancedMeshes(THREE, root);//-// Each `InstancedMesh` named `Posts` becomes a `Group` named `Posts` (same local-// transform, userData, visibility) holding meshes `Posts_0 .. Posts_{n-1}` that-// share the source geometry (the exporter dedupes it) and material; per-instance-// colours (`instanceColor`) become per-colour material clones.+// Each `InstancedMesh` named `Posts` is REPLACED, in its parent, by sibling meshes+// `Posts_0 .. Posts_{n-1}` (no wrapper group: the contract gate counts top-level+// `Name_i` nodes as the instances of plan part `Name`, conventions.split_instance).+// They share the source geometry (the exporter dedupes it) and material, carry the+// InstancedMesh's own transform times each instance matrix, and per-instance colours+// (`instanceColor`) become per-colour material clones. A bare InstancedMesh root has+// no parent, so it becomes a Group of the same name holding the meshes.function instanceMaterial(THREE, source, color, cache) {if (!color) return source;@@ -28,16 +31,16 @@ function instanceMaterial(THREE, source, color, cache) {return m;}-/** Replace one InstancedMesh by a Group of plain meshes; returns the Group. */-export function expandInstancedMesh(THREE, inst) {- const group = new THREE.Group();- group.name = inst.name || '';+/** The plain objects that replace one InstancedMesh, posed in its parent's frame. */+function expand(THREE, inst) {if (inst.matrixAutoUpdate) inst.updateMatrix();- group.matrix.copy(inst.matrix);- group.matrix.decompose(group.position, group.quaternion, group.scale);- group.visible = inst.visible;- group.userData = inst.userData;- group.renderOrder = inst.renderOrder;+ const out = [];+ const pose = (obj, local) => {+ obj.matrix.multiplyMatrices(inst.matrix, local);+ obj.matrix.decompose(obj.position, obj.quaternion, obj.scale);+ obj.visible = obj.visible && inst.visible;+ out.push(obj);+ };const count = Math.max(0, Number(inst.count) || 0);const m4 = new THREE.Matrix4();const color = new THREE.Color();@@ -50,36 +53,48 @@ export function expandInstancedMesh(THREE, inst) {mat = instanceMaterial(THREE, inst.material, color, matCache);}const mesh = new THREE.Mesh(inst.geometry, mat);- mesh.name = group.name ? `${group.name}_${i}` : '';- mesh.matrix.copy(m4);- mesh.matrix.decompose(mesh.position, mesh.quaternion, mesh.scale);+ mesh.name = inst.name ? `${inst.name}_${i}` : '';+ mesh.userData = inst.userData;+ mesh.renderOrder = inst.renderOrder;mesh.castShadow = inst.castShadow;mesh.receiveShadow = inst.receiveShadow;- group.add(mesh);+ pose(mesh, m4.clone());}- // nested children (rare) ride along unchanged- for (const child of [...inst.children]) group.add(child);- return group;+ // nested children (rare) ride along in the same frame+ for (const child of [...inst.children]) {+ if (child.matrixAutoUpdate) child.updateMatrix();+ inst.remove(child);+ pose(child, child.matrix.clone());+ }+ return out;}/*** Bake every InstancedMesh under `root` (root itself included) in place, keeping- * child order so census part order is unchanged. Returns how many were baked.+ * child order. Returns `{ root, count }`: `root` is a new Group only when `root`+ * itself was an InstancedMesh; `count` is how many InstancedMesh objects were baked.*/export function bakeInstancedMeshes(THREE, root) {const found = [];root.traverse((o) => {if (o.isInstancedMesh) found.push(o);});+ let out = root;for (const inst of found) {- const parent = inst.parent;- const group = expandInstancedMesh(THREE, inst);- if (!parent) continue; // a bare InstancedMesh root cannot be swapped; caller wraps it+ const parent = inst === root ? null : inst.parent;+ const parts = expand(THREE, inst);+ if (!parent) {+ out = new THREE.Group();+ out.name = inst.name || '';+ out.userData = inst.userData; // the root's userData (e.g. tick) stays on the root+ for (const p of parts) out.add(p);+ continue;+ }const idx = parent.children.indexOf(inst);- parent.children[idx] = group;- group.parent = parent;+ for (const p of parts) p.parent = parent;+ parent.children.splice(idx, 1, ...parts);inst.parent = null;}- root.updateWorldMatrix(true, true);- return found.length;+ out.updateWorldMatrix(true, true);+ return { root: out, count: found.length };}diff --git a/harness/tests/threejs_render/test_build.py b/harness/tests/threejs_render/test_build.pyindex 52aece0a..162b5e9f 100644--- a/harness/tests/threejs_render/test_build.py+++ b/harness/tests/threejs_render/test_build.py@@ -92,35 +92,51 @@ def test_build_keeps_source_placement_and_warns(stool_ws: Workspace):assert abs(lo[1] - 0.2) < 2e-3 and abs(lo[0] - 0.33) < 2e-3-def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace):- """InstancedMesh is baked (trimesh ignores EXT_mesh_gpu_instancing)."""[email protected]("bare_root", [False, True])+def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace, bare_root: bool):+ """InstancedMesh is baked (trimesh ignores EXT_mesh_gpu_instancing) into SIBLING meshes+ ``Posts_0..9``, so the contract gate counts them as the plan's ×10 instances (audit+ 2026-09-24 N2: a wrapper Group ``Posts`` was one part, "found 1 instance(s)" + a bbox ERROR)."""+ from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlanfrom codeverse3d.spatial.connectivity import check_connectivity-- (stool_ws.src / "object.js").write_text(- "import * as THREE from 'three';\nexport function build(T) { const g = new THREE.Group(); g.name = 'Fence';\n"- " const mat = new THREE.MeshStandardMaterial({ color: 0x885533 });\n"- " const posts = new THREE.InstancedMesh(new THREE.BoxGeometry(0.05, 1, 0.05), mat, 10); posts.name = 'Posts';\n"- " const m = new THREE.Matrix4();\n"- " for (let i = 0; i < 10; i++) { m.makeTranslation(-2.25 + i * 0.5, 0.5, 0); posts.setMatrixAt(i, m); posts.setColorAt(i, new THREE.Color(i % 2 ? 0xff0000 : 0x00ff00)); }\n"- " posts.instanceMatrix.needsUpdate = true; g.add(posts);\n"- " const rail = new THREE.Mesh(new THREE.BoxGeometry(4.6, 0.05, 0.03), mat); rail.name = 'Rail'; rail.position.set(0, 1.025, 0); g.add(rail);\n"- " return g; }\n")+ from codeverse3d.spatial.contract import check_contract++ posts = (" const mat = new THREE.MeshStandardMaterial({ color: 0x885533 });\n"+ " const posts = new THREE.InstancedMesh(new THREE.BoxGeometry(0.05, 1, 0.05), mat, 10); posts.name = 'Posts';\n"+ " const m = new THREE.Matrix4();\n"+ " for (let i = 0; i < 10; i++) { m.makeTranslation(-2.25 + i * 0.5, 0.5, 0); posts.setMatrixAt(i, m); posts.setColorAt(i, new THREE.Color(i % 2 ? 0xff0000 : 0x00ff00)); }\n"+ " posts.instanceMatrix.needsUpdate = true;\n")+ if bare_root:+ body = posts + " return posts; }\n"+ else:+ body = (" const g = new THREE.Group(); g.name = 'Fence';\n" + posts + " g.add(posts);\n"+ " const rail = new THREE.Mesh(new THREE.BoxGeometry(4.6, 0.05, 0.03), mat); rail.name = 'Rail'; rail.position.set(0, 1.025, 0); g.add(rail);\n"+ " return g; }\n")+ (stool_ws.src / "object.js").write_text("import * as THREE from 'three';\nexport function build(T) {\n" + body)res = ThreeJsRuntime().build(stool_ws)assert res.ok, res.error_messageassert res.census["instanced_meshes_baked"] == 1header = _glb_json(res.glb_path)assert "EXT_mesh_gpu_instancing" not in (header.get("extensionsUsed") or [])- assert len(header["materials"]) == 3 # base + two instance colours- scene = trimesh.load(res.glb_path, force="scene")- assert {"Posts_0", "Posts_9", "Rail"} <= set(scene.graph.nodes) and len(scene.graph.nodes_geometry) == 11+ assert len(header["materials"]) == (2 if bare_root else 3) # (base +) two instance colours+ names = [f"Posts_{i}" for i in range(10)] + ([] if bare_root else ["Rail"])m = measure_glb(res.glb_path)- assert sorted(p.name for p in m.parts) == ["Posts", "Rail"]- assert m.tri_count == 132 and abs(m.ground_gap_m) < 1e-3- posts = next(p for p in m.parts if p.name == "Posts")- assert np.allclose(posts.bbox_min, [-2.275, 0.0, -0.025], atol=1e-3)- assert np.allclose(posts.bbox_max, [2.275, 1.0, 0.025], atol=1e-3)- assert posts.tri_count == 120- assert check_connectivity(res.glb_path).passed+ assert sorted(p.name for p in m.parts) == sorted(names)+ assert m.tri_count == 12 * len(names) and abs(m.ground_gap_m) < 1e-3+ p9 = next(p for p in m.parts if p.name == "Posts_9")+ assert np.allclose(p9.bbox_min, [2.225, 0.0, -0.025], atol=1e-3)+ assert np.allclose(p9.bbox_max, [2.275, 1.0, 0.025], atol=1e-3)+ parts = [PartPlan(name="Posts", role="r", description="d", instances=10,+ bbox=BBox(center=(0, 0.5, 0), extents=(0.05, 1.0, 0.05)))]+ if not bare_root:+ parts.append(PartPlan(name="Rail", role="r", description="d",+ bbox=BBox(center=(0, 1.025, 0), extents=(4.6, 0.05, 0.03))))+ plan = StaticPlan(object_name="Fence", summary="s", overall_bbox=BBox(center=(0, 0.525, 0), extents=(4.6, 1.05, 0.05)),+ parts=parts)+ assert [f.message for f in check_contract(m, plan, language="threejs").findings+ if f.severity.value != "info"] == []+ if not bare_root:+ assert check_connectivity(res.glb_path).passeddef test_build_nan_geometry_names_mesh_part_and_file(stool_ws: Workspace):