Skip to content

Official Codebase of 3DCodeVerse

Python

scene_blender: the runtime renders through Blender and measures on the census GLB — lanes A and B joined

gaoypenge36520718773
diff --git a/harness/codeverse3d/languages/scene_blender/__init__.py b/harness/codeverse3d/languages/scene_blender/__init__.py
index 7d82b983..2668a7b6 100644
--- a/harness/codeverse3d/languages/scene_blender/__init__.py
+++ b/harness/codeverse3d/languages/scene_blender/__init__.py
@@ -870,9 +870,10 @@ class SceneBlenderRuntime:
def render_scene(self, ws: Workspace, out_dir: Path, *, cameras: list[CameraPlan] | None = None, orbit: bool = True,
times: Sequence[float] = TIMES, width: int = 1024, height: int = 576, sheet: bool = True) -> RenderSet:
- raise NotImplementedError(
- "scene_blender rendering is DESIGN phase 2 (render_bpy_scene.py + spatial/render_blender.py), not landed yet: "
- "a scene_blender workspace builds and passes its geometry gates but cannot be rendered or judged")
+ from codeverse3d.spatial.render_blender import render_blender_scene
+
+ return render_blender_scene(ws, out_dir, cameras=cameras, orbit=orbit, times=times, width=width,
+ height=height, sheet=sheet)
def stage_findings(report: dict[str, Any]) -> list[GateFinding]:
diff --git a/harness/codeverse3d/spatial/render_blender.py b/harness/codeverse3d/spatial/render_blender.py
index 0baf124d..8054a729 100644
--- a/harness/codeverse3d/spatial/render_blender.py
+++ b/harness/codeverse3d/spatial/render_blender.py
@@ -14,7 +14,7 @@
default); a GPU render holds one of ``blender_gpu_slots`` machine-wide flock'd slots and
falls back to the CPU when none frees within ``blender_gpu_wait_s`` or the GPU run dies;
3. **geometry** — ``runtime_js/render_scene.mjs --external-frames`` on the census GLB the build
- wrote (loaded through the language's host entry, ``scene_rel``): camera checks (near
+ wrote (``--glb``: booted through ``runtime_js/lib/glb_scene.mjs``): camera checks (near
geometry, inside a mesh, ground below/above, line of sight, coverage masks) from the scene,
luminance statistics from the Blender PNG (``host_metrics.imageFrameStats`` — the one
``frameStats``), ``views.json`` / ``metrics.json`` in the three.js driver's schema, with no
@@ -62,7 +62,7 @@ log = logging.getLogger(__name__)
DRIVER = Path(__file__).resolve().parent.parent / "languages" / "wrappers" / "render_bpy_scene.py"
#: the language whose authoring frame the .blend is in. scene_blender's LANGUAGE_FRAME row
#: (lane A) is Z-up / -Y front, the same frame as blender's; switch to it once that row lands.
-FRAME_LANGUAGE = "blender"
+FRAME_LANGUAGE = "scene_blender"
LANGUAGE = "scene_blender"
JOB_NAME = "blender_job.json"
RESULT_NAME = "blender_frames.json"
@@ -201,7 +201,7 @@ def render_blender_scene(
bounds: BBox | None = None,
blend: Path | None = None,
census: Path | None = None,
- scene_rel: str = "src/scene.js",
+ glb: Path | None = None,
engine: str | None = None,
samples: int | None = None,
) -> RenderSet:
@@ -211,7 +211,7 @@ def render_blender_scene(
``cameras=None`` renders the cameras the .blend carries (the build made them from the
plan); explicit ``cameras`` (GLB frame, like every plan camera) replace them. ``blend``
defaults to ``artifacts/scene.blend``, ``census`` (the orbit fit) to ``artifacts/census.json``;
- ``scene_rel`` is the host entry that loads the census GLB for the geometry pass. ``engine``
+ ``glb`` (default ``artifacts/census.glb``) is what the geometry pass boots through the host. ``engine``
/ ``samples`` override Settings (a tool's preview tier: ``engine="workbench"``). A missing
.blend yields an empty RenderSet whose ``console_errors`` say why; a driver that cannot run
raises ``SceneRenderError``."""
@@ -219,6 +219,7 @@ def render_blender_scene(
out_dir = out_directory(out_dir, clean=("metrics.json", "views.json", RESULT_NAME, EXTERNAL_NAME))
blend = blend or ws.artifacts / "scene.blend"
census = census or ws.artifacts / "census.json"
+ glb = glb or ws.artifacts / "census.glb"
times = sorted({float(t) for t in times}) or [0.0]
tmo = float(timeout_s or s.limits.render_timeout_s)
t_all = time.monotonic()
@@ -257,7 +258,7 @@ def render_blender_scene(
specs += [{**o, "kind": "orbit"} for o in orbit_specs]
t0 = time.monotonic()
metrics, geometry_error = _geometry_pass(ws, out_dir, specs, times=times, width=width, height=height,
- timeout_s=tmo, scene_rel=scene_rel)
+ timeout_s=tmo, glb=glb)
geometry_ms = int((time.monotonic() - t0) * 1000)
if not metrics.get("views"):
metrics["views"] = views # the pictures exist even when the geometry pass could not run
@@ -316,11 +317,11 @@ def _renderer_line(frames: dict[str, Any]) -> str:
def _geometry_pass(ws: Workspace, out_dir: Path, specs: list[dict[str, Any]], *, times: Sequence[float], width: int,
- height: int, timeout_s: float, scene_rel: str) -> tuple[dict[str, Any], str]:
+ height: int, timeout_s: float, glb: Path) -> tuple[dict[str, Any], str]:
"""render_scene.mjs --external-frames → (its metrics payload, an error line or '')."""
if not specs:
return {"views": [], "camera_checks": [], "console_errors": []}, ""
- args = ["--ws", str(ws.root), "--out", str(out_dir), "--scene", scene_rel,
+ args = ["--ws", str(ws.root), "--out", str(out_dir), "--glb", str(glb),
"--cameras", json.dumps(specs), "--orbit-views", "none",
"--times", ",".join(f"{t:g}" for t in times), "--width", str(width), "--height", str(height),
"--fps-seconds", "0", "--timeout-ms", str(int(timeout_s * 1000)),
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index d1aca0a5..bc9e8ab9 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -333,9 +333,9 @@ from codeverse3d.spatial.render_scene import render_set_from_metrics # metrics
from codeverse3d.spatial.render_blender import render_blender_scene # scene_blender (lane B): Blender pixels, JS camera checks
render_blender_scene(ws, out_dir, *, cameras=None, orbit=True, times=(0.0, 1.5), width=1024, height=576, sheet=True,
orbit_views=SCENE_VIEWS, timeout_s=None, bounds=None, blend=None, census=None,
- scene_rel="src/scene.js", engine=None, samples=None) -> RenderSet
- # blend = artifacts/scene.blend, census = artifacts/census.json (orbit fit); scene_rel = the host entry that loads the
- # census GLB; metrics.json = the three.js schema + {"language": "scene_blender", "blender": {engine, device, samples,
+ glb=None, engine=None, samples=None) -> RenderSet
+ # blend = artifacts/scene.blend, census = artifacts/census.json (orbit fit), glb = artifacts/census.glb (booted by
+ # render_scene.mjs --glb through lib/glb_scene.mjs); metrics.json = the three.js schema + {"language": "scene_blender", "blender": {engine, device, samples,
# fallback, frame_ms, timings_ms}}; Settings.render.blender_{engine,samples,device,gpu_slots,gpu_wait_s}
from codeverse3d.spatial.render_scene import select_judge_views, JUDGE_MAX_VIEWS, plan_bounds
select_judge_views(rs, max_n=10) -> RenderSet # priority: authored@t0, 2 overview@t0, 2 authored@t_last, rest
diff --git a/harness/runtime_js/render_scene.mjs b/harness/runtime_js/render_scene.mjs
index a1f5fdbd..0c6ca4d9 100644
--- a/harness/runtime_js/render_scene.mjs
+++ b/harness/runtime_js/render_scene.mjs
@@ -41,6 +41,7 @@ const args = parseCli({
gpu: { default: process.env.C3D_RENDER_GPU || 'auto' }, 'fps-seconds': { default: '2' },
'timeout-ms': { default: '240000' }, 'log-depth': { type: 'boolean', default: false },
scene: { default: 'src/scene.js' }, 'external-frames': { default: '' },
+ glb: { default: '' }, // scene_blender: the census GLB, booted through lib/glb_scene.mjs (D102)
});
function tag(t) {
@@ -85,6 +86,7 @@ async function main() {
try {
host = await openHost(args.ws, {
width, height, gpu: args.gpu, logDepth: args['log-depth'], sceneRel: args.scene.replace(/^\.?\//, ''),
+ glb: args.glb ? path.resolve(args.glb) : null,
createSceneTimeoutMs: createTimeoutMs(timeoutMs),
settle: !args['no-settle'],
cameraRepair: !!args['camera-repair'],
diff --git a/harness/tests/scene_blender/test_build.py b/harness/tests/scene_blender/test_build.py
index 798ae7d9..84ddff78 100644
--- a/harness/tests/scene_blender/test_build.py
+++ b/harness/tests/scene_blender/test_build.py
@@ -4,6 +4,7 @@ the unchanged JS census / placement code measures it (real Blender + headless Ch
from __future__ import annotations
import json
+from pathlib import Path
import pytest
@@ -105,6 +106,25 @@ def test_the_skeleton_builds_and_passes(tmp_ws) -> None:
assert [cam["name"] for cam in probe["boot"]["cameras"]] == [to_snake(c.name) for c in plan.cameras[:6]]
+def test_the_skeleton_renders_through_the_runtime(tmp_ws, switch) -> None:
+ """plan → skeleton → build → ``runtime.render_scene``: Blender pictures for every plan camera at
+ both times, measured by the JS host on the census GLB (lanes A + B joined, DESIGN §2)."""
+ switch("C3D_RENDER__BLENDER_DEVICE", "cpu")
+ switch("C3D_RENDER__BLENDER_SAMPLES", "4")
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ rt = _rt()
+ rt.skeleton(tmp_ws, plan)
+ rt.assemble(tmp_ws, plan)
+ assert rt.build(tmp_ws).ok
+ rs = rt.render_scene(tmp_ws, tmp_ws.root / "renders", times=(0.0, 1.5), width=96, height=54, sheet=False)
+ names = [to_snake(c.name) for c in plan.cameras[:6]]
+ authored = {(v.name, v.time_s) for v in rs.views if v.name in names}
+ assert authored == {(n, t) for n in names for t in (0.0, 1.5)}, rs.views
+ assert all((tmp_ws.root / "renders" / Path(v.path).name).is_file() or Path(v.path).is_file() for v in rs.views)
+ metrics = json.loads((tmp_ws.root / "renders" / "metrics.json").read_text())
+ assert metrics["language"] == "scene_blender" and {c["name"] for c in metrics["camera_checks"]} >= set(names)
+
+
def test_assemble_leaves_a_failing_zone_out(tmp_ws) -> None:
write_fixture(tmp_ws)
plan = ScenePlan.model_validate(plan_example(Track.SCENE))
diff --git a/harness/tests/scene_blender/test_layout.py b/harness/tests/scene_blender/test_layout.py
index 8b880b78..e6111552 100644
--- a/harness/tests/scene_blender/test_layout.py
+++ b/harness/tests/scene_blender/test_layout.py
@@ -36,12 +36,6 @@ def test_scene_blender_is_a_scene_language_with_a_runtime() -> None:
assert ENTRY_FILE[Language.SCENE_BLENDER] == "src/scene.py" == rt.entry_globs[0]
-def test_render_scene_is_not_there_yet(tmp_ws) -> None:
- """Phase 2 (lane B) lands it; until then a clear error, never a silent empty RenderSet."""
- with pytest.raises(NotImplementedError, match="phase 2"):
- get_runtime(Language.SCENE_BLENDER).render_scene(tmp_ws, tmp_ws.artifacts / "renders")
-
-
def test_the_file_table() -> None:
rt = get_runtime(Language.SCENE_BLENDER)
plan = _plan()
diff --git a/harness/tests/scene_runtime/blender_scene_fixture.py b/harness/tests/scene_runtime/blender_scene_fixture.py
index 932dbece..deb7e02b 100644
--- a/harness/tests/scene_runtime/blender_scene_fixture.py
+++ b/harness/tests/scene_runtime/blender_scene_fixture.py
@@ -77,21 +77,29 @@ bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", export_cameras=Fals
bpy.ops.wm.save_as_mainfile(filepath=blend, compress=True)
'''
-#: the census-GLB host entry's shape (lane A owns the real one): load the GLB, hoist its roots
-ADAPTER_JS = """import * as THREE from 'three';
-export async function createScene({ loaders }) {
- const scene = new THREE.Scene();
- const gltf = await loaders.gltf.loadAsync('/assets/scene.glb');
- for (const c of [...gltf.scene.children]) scene.add(c);
- scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 1.0));
- const cameras = [{ name: 'Front', position: [0, 4, 14], lookAt: [0, 1, 0], fov: 40.1 }];
- return { scene, cameras };
-}
-"""
+#: the harness cameras the census GLB carries (``extras.c3d_cameras``, GLB frame — the shape
+#: ``_census_glb._glb_camera`` writes): Blender (x, y, z) → GLB (x, z, -y), vertical fov 0.7 rad
+GLB_CAMERAS = [{"name": "Front", "position": [0, 4, 14], "lookAt": [0, 1, 0], "fov": 40.107},
+ {"name": "Side", "position": [14, 4, 0], "lookAt": [0, 1, 0], "fov": 40.107}]
+
+
+def _with_scene_extras(glb: bytes, extras: dict) -> bytes:
+ """``glb`` with ``extras`` on its first scene (the census writer's camera channel)."""
+ import json
+ import struct
+
+ n = struct.unpack("<I", glb[12:16])[0]
+ doc = json.loads(glb[20:20 + n])
+ doc["scenes"][0]["extras"] = extras
+ body = json.dumps(doc, separators=(",", ":")).encode()
+ body += b" " * (-len(body) % 4)
+ rest = glb[20 + n:]
+ return struct.pack("<4sII", b"glTF", 2, 12 + 8 + len(body) + len(rest)) + struct.pack("<I4s", len(body), b"JSON") + body + rest
def build_fixture(ws: Workspace, *, moving: bool = True, probe: bool = True) -> Workspace:
- """Write the fixture into ``ws`` (Blender + optionally the three.js probe for census.json)."""
+ """Write the fixture into ``ws``: the .blend, its census GLB (cameras in the extras) and, with
+ ``probe``, census.json from the JS probe of that GLB — the path ``SceneBlenderRuntime`` takes."""
ws.artifacts.mkdir(parents=True, exist_ok=True)
script = ws.root / "build_fixture.py"
script.write_text(BUILD_BPY)
@@ -102,13 +110,14 @@ def build_fixture(ws: Workspace, *, moving: bool = True, probe: bool = True) ->
proc = run_subprocess([blender, "-b", "--factory-startup", "--python", str(script), "--",
str(blend), str(glb), "1" if moving else "0"], cwd=ws.root, env=blender_env(), timeout_s=120)
assert proc.returncode == 0 and blend.is_file() and glb.is_file(), proc.stderr[-2000:]
- ws.src.mkdir(parents=True, exist_ok=True)
- (ws.src / "scene.js").write_text(ADAPTER_JS)
+ census_glb = ws.artifacts / "census.glb"
+ census_glb.write_bytes(_with_scene_extras(glb.read_bytes(), {"c3d_cameras": GLB_CAMERAS}))
if probe:
- from codeverse3d.spatial.probes import probe_scene
+ from codeverse3d.spatial.probes import run_probe
- res = probe_scene(ws, timeout_s=90)
- assert res.census, res.errors
+ _, _, census = run_probe(ws, glb=census_glb, timeout_s=90)
+ assert census, "the census-GLB probe produced no census"
+ ws.write_json(ws.artifacts / "census.json", {**census, "language": "scene_blender"})
return ws
diff --git a/harness/tests/scene_runtime/test_render_blender.py b/harness/tests/scene_runtime/test_render_blender.py
index 53779e0d..78979509 100644
--- a/harness/tests/scene_runtime/test_render_blender.py
+++ b/harness/tests/scene_runtime/test_render_blender.py
@@ -89,13 +89,34 @@ def test_a_fixture_scene_renders_two_cameras_at_two_times(moving):
assert [e["judge"] for e in json.loads((out / "views.json").read_text())].count(True) == len(judged)
+#: a three.js scene of the fixture (its GLB as an asset, the same Front camera): the schema reference
+THREE_REFERENCE_JS = """import * as THREE from 'three';
+export async function createScene({ loaders }) {
+ const scene = new THREE.Scene();
+ const gltf = await loaders.gltf.loadAsync('/assets/scene.glb');
+ for (const c of [...gltf.scene.children]) scene.add(c);
+ scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 1.0));
+ const cameras = [{ name: 'Front', position: [0, 4, 14], lookAt: [0, 1, 0], fov: 40.1 }];
+ return { scene, cameras };
+}
+"""
+
+
@pytest.mark.blender
@pytest.mark.node
@needs_blender
@needs_browser
def test_metrics_schema_equals_the_threejs_one(moving, tmp_path):
ws, _, bm = moving
- render_scene(ws, tmp_path / "three", width=W, height=H, fps_seconds=0.2)
+ # the three.js reference: the same geometry and cameras as a three.js scene (the fixture GLB as an asset)
+ import shutil
+
+ three = Workspace(tmp_path / "three_ws").create()
+ (three.root / "public" / "assets").mkdir(parents=True, exist_ok=True)
+ shutil.copy(ws.root / "public" / "assets" / "scene.glb", three.root / "public" / "assets" / "scene.glb")
+ three.src.mkdir(parents=True, exist_ok=True)
+ (three.src / "scene.js").write_text(THREE_REFERENCE_JS)
+ render_scene(three, tmp_path / "three", width=W, height=H, fps_seconds=0.2)
tm = json.loads((tmp_path / "three" / "metrics.json").read_text())
assert set(bm) - set(tm) == {"language", "blender"}, "Blender metrics add only language + blender"
assert set(tm) - set(bm) == set(), f"keys the three.js payload has and Blender's lacks: {set(tm) - set(bm)}"
@@ -140,14 +161,11 @@ def test_exposure_statistics_of_a_known_png_come_from_the_external_frame(tmp_pat
"""Half black, half white: mean 0.5, half near-black, half blown, the modal bucket 50 % — from
the Blender PNG, not from the host's own (bright grey) render of the same camera."""
ws = Workspace(tmp_path / "run").create()
- ws.src.mkdir(parents=True, exist_ok=True)
- (ws.src / "scene.js").write_text(
- "import * as THREE from 'three';\n"
- "export function createScene() {\n"
- " const scene = new THREE.Scene(); scene.background = new THREE.Color(0x888888);\n"
- " const g = new THREE.Mesh(new THREE.PlaneGeometry(40, 40).rotateX(-Math.PI / 2), new THREE.MeshBasicMaterial({ color: 0x888888 }));\n"
- " g.name = 'Ground'; scene.add(g);\n"
- " return { scene, cameras: [{ name: 'K', position: [0, 3, 10], lookAt: [0, 0, 0], fov: 50 }] };\n}\n")
+ import trimesh # a 40 m ground as the census GLB the geometry pass boots (lib/glb_scene.mjs)
+
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ ground = trimesh.creation.box(extents=(40.0, 0.01, 40.0))
+ trimesh.Scene({"Ground": ground}, metadata={"c3d_cameras": [{"name": "K", "position": [0, 3, 10], "lookAt": [0, 0, 0], "fov": 50}]}).export(ws.artifacts / "census.glb")
out = tmp_path / "out"
out.mkdir()
_half_png(out / "K_t0.png")
@@ -156,7 +174,7 @@ def test_exposure_statistics_of_a_known_png_come_from_the_external_frame(tmp_pat
(out / rb.EXTERNAL_NAME).write_text(json.dumps(views))
specs = [{"name": "K", "kind": "authored", "position": [0, 3, 10], "lookAt": [0, 0, 0], "fov": 50},
{"name": "Blank", "kind": "orbit", "position": [5, 3, 10], "lookAt": [0, 0, 0], "fov": 50}]
- metrics, err = rb._geometry_pass(ws, out, specs, times=(0.0,), width=W, height=H, timeout_s=90, scene_rel="src/scene.js")
+ metrics, err = rb._geometry_pass(ws, out, specs, times=(0.0,), width=W, height=H, timeout_s=90, glb=ws.artifacts / "census.glb")
assert err == ""
k = next(c for c in metrics["camera_checks"] if c["name"] == "K")
assert k["mean_lum"] == pytest.approx(0.5, abs=0.02)