Skip to content

Official Codebase of 3DCodeVerse

Python

assembler: name a loaded GLB root after its asset, in the one place that loads them

ziyaofd217bb76523
diff --git a/harness/codeverse/languages/scene_threejs/__init__.py b/harness/codeverse/languages/scene_threejs/__init__.py
index 8b3474e1..e9c57262 100644
--- a/harness/codeverse/languages/scene_threejs/__init__.py
+++ b/harness/codeverse/languages/scene_threejs/__init__.py
@@ -302,17 +302,15 @@ def _scene_for_plan(plan: ScenePlan) -> str:
)
glb_block = ""
if glbs:
- files = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
- glb_block = f'''
- // Blender-built assets (public/assets/*.glb) are preloaded once; zones clone ctx.assets.<name>.
- const assetFiles = {{ {files} }};
- const assets = {{}};
- for (const [key, url] of Object.entries(assetFiles)) {{
- try {{ assets[key] = (await loaders.gltf.loadAsync(url)).scene; }}
- catch (e) {{ console.warn(`[assets] missing ${{url}} (${{e && e.message}}) — build it with Blender into public/assets/`); }}
- }}
- ctx.assets = assets;
-'''
+ preload = _glb_preload_js(
+ glbs, target="ctx.assets",
+ on_error="console.warn(`[assets] missing ${a.url} (${e && e.message}) — build it with Blender into public/assets/`);",
+ )
+ glb_block = (
+ "\n // Blender-built assets (public/assets/*.glb) are preloaded once, NAMED after the\n"
+ " // plan's asset, and cloned by the zones from ctx.assets.<key>.\n"
+ + preload + "\n"
+ )
async_kw = "async " if glbs else ""
header = (STARTER_DIR / "scene.js").read_text().split("import * as THREE")[0]
return f'''{header}// PLAN: {plan.title} — {plan.summary.strip()}
@@ -425,9 +423,46 @@ def sun_azimuth(ws: Workspace, default: float = 45.0) -> float:
# --------------------------------------------------------------------------- probing
+#: How a Blender-built asset is preloaded in EVERY assembled entry point. One
+#: spelling, because there are three of them (the assembled `src/scene.js`, the
+#: assembler's probe module, and `render_scene_js`) and they had drifted into three.
+#:
+#: The loaded root is NAMED after its asset. A glTF root arrives called whatever the
+#: exporter wrote — Blender writes "Scene" — and every check that reads the scene
+#: graph by name then cannot see it. Measured on bench/out/scene_baseline
+#: (2026-09-05): rooftop_garden's `lounge_sofa.glb` loaded fine (`glb_assets:
+#: meshes_in_scene 1, in_scene true`) and `scene_placement` still reported
+#: "zone PergolaLounge is missing planned contents: LoungeSofa", because the object
+#: in the zone was called "Scene". `to_pascal` on the file key rebuilds exactly the
+#: plan's asset name, which is where the key came from.
+def _glb_preload_js(glbs: list[str], *, target: str, on_error: str, indent: str = " ") -> str:
+ """The `assetFiles` literal + preload loop, or "" when the plan has no GLB asset.
+
+ ``target`` is the assets object to fill (``assets`` / ``ctx.assets``); ``on_error``
+ is the JS statement run in the catch, with ``e`` and ``a`` (the asset entry) bound.
+ """
+ if not glbs:
+ return ""
+ files = ", ".join(f"{g}: {{ name: '{to_pascal(g)}', url: '/assets/{g}.glb' }}" for g in glbs)
+ body = [
+ f"const assetFiles = {{ {files} }};",
+ "for (const [key, a] of Object.entries(assetFiles)) {",
+ " try {",
+ " const root = (await loaders.gltf.loadAsync(a.url)).scene;",
+ " root.name = a.name; // a glTF root is called 'Scene' until someone names it",
+ f" {target}[key] = root;",
+ " } catch (e) { " + on_error + " }",
+ "}",
+ ]
+ return "\n".join(indent + line for line in body)
+
+
def _probe_module(zones: list[Path], glbs: list[str]) -> str:
entries = ",\n".join(f" ['{to_snake(p.stem)}', './zones/{p.name}']" for p in zones)
- glb_lines = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
+ glb_preload = _glb_preload_js(
+ glbs, target="ctx.assets",
+ on_error=f"console.error('{_PREFIX} asset ' + key + ' failed: ' + ((e && e.message) || e));",
+ )
return f"""// generated by codeverse assembler — probes env + zone modules independently; deleted after use
import * as THREE from 'three';
const ZONES = [
@@ -436,11 +471,7 @@ const ZONES = [
export async function createScene({{ renderer, loaders }}) {{
const scene = new THREE.Scene();
const ctx = {{ THREE, scene, renderer, loaders, heightAt: () => 0, assets: {{}}, env: {{}} }};
- const assetFiles = {{ {glb_lines} }};
- for (const [k, url] of Object.entries(assetFiles)) {{
- try {{ ctx.assets[k] = (await loaders.gltf.loadAsync(url)).scene; }}
- catch (e) {{ console.error('{_PREFIX} asset ' + k + ' failed: ' + ((e && e.message) || e)); }}
- }}
+{glb_preload}
let env = null;
try {{
const m = await import('./env.js');
@@ -572,7 +603,10 @@ def render_scene_js(zones: list[str], cameras: list[CameraPlan], glbs: list[str]
# buildEnv/build may be async (lint + the assembler probe both accept it): await consistently
env_build = " const env = (await buildEnv(ctx)) || {};\n ctx.env = env;" if env_ok else " const env = {};"
height = "heightAt" if env_ok else "() => 0"
- glb_lines = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
+ glb_preload = _glb_preload_js(
+ glbs, target="ctx.assets",
+ on_error="console.error(`[assets] failed to load ${a.url}: ${e && e.message}`);",
+ )
cams = "\n".join(_cam_literal(c) for c in cameras)
return f"""// src/scene.js — ASSEMBLED BY THE HARNESS (codeverse assembler). Edit zones/env instead; re-assembly overwrites this file.
import * as THREE from 'three';
@@ -582,11 +616,7 @@ import * as THREE from 'three';
export async function createScene({{ renderer, loaders }}) {{
const scene = new THREE.Scene();
const ctx = {{ THREE, scene, renderer, loaders, heightAt: {height}, assets: {{}} }};
- const assetFiles = {{ {glb_lines} }};
- for (const [key, url] of Object.entries(assetFiles)) {{
- try {{ ctx.assets[key] = (await loaders.gltf.loadAsync(url)).scene; }}
- catch (e) {{ console.error(`[assets] failed to load ${{url}}: ${{e && e.message}}`); }}
- }}
+{glb_preload}
{env_build}
const zones = [];
diff --git a/harness/tests/scene_runtime/test_assemble.py b/harness/tests/scene_runtime/test_assemble.py
index 7d6d5381..f9d1ac00 100644
--- a/harness/tests/scene_runtime/test_assemble.py
+++ b/harness/tests/scene_runtime/test_assemble.py
@@ -63,7 +63,9 @@ def test_render_scene_js_contents():
src = render_scene_js(["harbour", "fish_market"], cams, ["crane"], env_ok=True)
assert "import { build as buildHarbour } from './zones/harbour.js';" in src
assert "addZone(buildFishMarket, 'FishMarket');" in src
- assert "crane: '/assets/crane.glb'" in src
+ # the loader carries the URL *and* the name to stamp on the loaded root
+ assert "crane: { name: 'Crane', url: '/assets/crane.glb' }" in src
+ assert "root.name = a.name;" in src
assert "name: 'overview', position: [1, 2, 3]" in src
assert "import { buildEnv, heightAt } from './env.js';" in src
assert "const addZone = async (build, name) => {" in src
diff --git a/harness/tests/scene_runtime/test_glb_asset_naming.py b/harness/tests/scene_runtime/test_glb_asset_naming.py
new file mode 100644
index 00000000..a06966f9
--- /dev/null
+++ b/harness/tests/scene_runtime/test_glb_asset_naming.py
@@ -0,0 +1,83 @@
+"""A loaded GLB root is named after its asset, or nothing can find it.
+
+Measured on `bench/out/scene_baseline` (2026-09-05). rooftop_garden's plan asked for
+one `blender_glb` asset, `LoungeSofa`; the Blender sub-run built it (asset judge
+0.618), the assembler wrote the loader, the browser loaded it and put it in the scene
+-- `glb_assets: {meshes_in_scene: 1, in_scene: true}` -- and `scene_placement` still
+raised two ERRORs:
+
+ zone PergolaLounge is missing planned contents: LoungeSofa
+ zone BotanicalAlley is missing planned contents: LoungeSofa
+
+because the object standing in both zones was called **`Scene`**. A glTF root carries
+whatever the exporter wrote, and Blender writes "Scene"; the assembler handed that
+straight to the zones. Re-probing the recorded workspace with the naming in place
+takes those two ERRORs to zero.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from codeverse.contracts.plan import CameraPlan
+from codeverse.languages.scene_threejs import render_scene_js
+from codeverse.spatial.node import run_node
+from tests.scene_runtime.conftest import needs_node
+
+pytestmark = [pytest.mark.node, needs_node]
+
+ZONE_JS = """
+import * as THREE from 'three';
+export function build(ctx) {
+ const g = new THREE.Group();
+ const sofa = ctx.assets.lounge_sofa;
+ // what the zone sees is what every by-name check downstream sees
+ g.userData.sofaName = sofa ? sofa.name : '<absent>';
+ if (sofa) g.add(sofa.clone());
+ return g;
+}
+"""
+
+#: the glTF root arrives UNNAMED, exactly as three's GLTFLoader hands over a Blender
+#: export whose scene node carries no name of its own
+DRIVER_JS = """
+import * as THREE from 'three';
+import { createScene } from './src/scene.js';
+const loaders = { gltf: { loadAsync: async () => ({ scene: new THREE.Group() }) } };
+const { scene } = await createScene({ renderer: null, loaders });
+console.log(JSON.stringify({
+ zoneSees: scene.children.map((c) => c.userData.sofaName),
+ cloneNames: scene.children.flatMap((c) => c.children.map((k) => k.name)),
+}));
+"""
+
+
+def loaded(tmp_path) -> dict:
+ (tmp_path / "src" / "zones").mkdir(parents=True)
+ (tmp_path / "src" / "zones" / "pergola_lounge.js").write_text(ZONE_JS)
+ cam = CameraPlan(name="establishing", position=[5, 2, 5], look_at=[0, 1, 0], fov=45)
+ (tmp_path / "src" / "scene.js").write_text(
+ render_scene_js(["pergola_lounge"], [cam], ["lounge_sofa"], env_ok=False)
+ )
+ driver = tmp_path / "driver.mjs"
+ driver.write_text(DRIVER_JS)
+ res = run_node(driver, [], cwd=tmp_path, three_hook=True, timeout_s=60)
+ return json.loads(res.stdout.strip().splitlines()[-1])
+
+
+def test_the_zone_sees_the_asset_under_its_planned_name(loaded):
+ assert loaded["zoneSees"] == ["LoungeSofa"], "a glTF root is called 'Scene' until someone names it"
+
+
+def test_the_clone_the_zone_places_carries_the_name_too(loaded):
+ """`.clone()` copies the name, so the object actually standing in the zone — the
+ one `scene_placement` matches against the plan — carries it as well."""
+ assert loaded["cloneNames"] == ["LoungeSofa"]
+
+
+def test_a_plan_without_glb_assets_emits_no_loader():
+ src = render_scene_js(["z"], [], [], env_ok=False)
+ assert "assetFiles" not in src and "loadAsync" not in src