Skip to content

Official Codebase of 3DCodeVerse

Python

scene_blender frames are rendered by Blender and measured by the JS host in the three.js metrics schema (D102, lane B)

gaoypeng0a5092512f6a
diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.py
index c6bd24ca..548b9199 100644
--- a/harness/codeverse3d/config.py
+++ b/harness/codeverse3d/config.py
@@ -106,6 +106,24 @@ class Render(BaseModel):
"the node side reads too)")
sheet_cols: int = 4
sheet_tile: int = 384
+ # scene_blender pictures (spatial/render_blender.py, owner D1/D8 2026-09-24). Measured on this
+ # box at 1024x576: Cycles CUDA 32 spp + OIDN 0.9 s/frame (light scene) - 3.6 s (heavy), CPU 2.9 s
+ # at 16 spp; EEVEE 64 spp 1.5 - 3.0 s plus a 7-12 s shader compile per process, GPU only under the
+ # Mesa d3d12 env (spatial/gl_render.GPU_ENV) — without it EEVEE silently lands on llvmpipe (10x).
+ blender_engine: Annotated[Literal["cycles", "eevee"], BeforeValidator(lambda v: str(v).strip().lower())] = Field(
+ default="cycles", description="judged-frame engine for scene_blender (C3D_RENDER__BLENDER_ENGINE)")
+ blender_samples: int = Field(
+ default=32, ge=1, description="Cycles samples (adaptive + OIDN) / EEVEE TAA samples; the profile dial sets "
+ "economy 16 · balanced 32 · quality 64 (C3D_RENDER__BLENDER_SAMPLES)")
+ blender_device: Annotated[Literal["gpu", "cpu"], BeforeValidator(lambda v: str(v).strip().lower())] = Field(
+ default="gpu", description="'gpu' takes a machine-wide GPU slot and falls back to the CPU when none frees "
+ "within blender_gpu_wait_s or the GPU render dies; 'cpu' never touches the GPU")
+ blender_gpu_slots: int = Field(
+ default=2, ge=1, description="machine-wide concurrent GPU Blender renders (flock'd files under "
+ "<cache_dir>/slots/blender_gpu/)")
+ blender_gpu_wait_s: float = Field(
+ default=60.0, ge=0, description="how long a render waits for a GPU slot before it renders on the CPU "
+ "(~3.3x slower, measured)")
class Limits(BaseModel):
@@ -365,6 +383,7 @@ class Settings(BaseSettings):
put("default_captioner", p.captioner)
put("default_candidates", p.candidates)
put_section("judge", {"samples": p.judge_samples})
+ put_section("render", {"blender_samples": p.blender_samples})
return p
def resolve_blender(self) -> str:
diff --git a/harness/codeverse3d/conventions.py b/harness/codeverse3d/conventions.py
index 86ff95d4..ff977d82 100644
--- a/harness/codeverse3d/conventions.py
+++ b/harness/codeverse3d/conventions.py
@@ -86,6 +86,15 @@ def glb_basis(language: str) -> tuple[tuple[float, float, float], ...]:
return ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))
+def from_authoring_frame(v: Sequence[float], language: str) -> tuple[float, float, float]:
+ """The inverse of :func:`to_authoring_frame` for a point / direction: ``language``'s frame
+ into the GLB frame — :func:`glb_basis` applied, so the mapping is stated once."""
+ x, y, z = (float(c) for c in v)
+ r = glb_basis(language)
+ return (r[0][0] * x + r[0][1] * y + r[0][2] * z, r[1][0] * x + r[1][1] * y + r[1][2] * z,
+ r[2][0] * x + r[2][1] * y + r[2][2] * z)
+
+
def frame_doc(frame: Frame) -> str:
"""Return the one-paragraph prompt text describing ``frame``."""
if frame is Frame.Z_UP_NEG_Y_FRONT:
diff --git a/harness/codeverse3d/cost/profiles.py b/harness/codeverse3d/cost/profiles.py
index f08a7eaf..43d4b0e9 100644
--- a/harness/codeverse3d/cost/profiles.py
+++ b/harness/codeverse3d/cost/profiles.py
@@ -70,6 +70,8 @@ class Profile:
candidates: int = 1 # best-of-N baselines
judge_samples: int = 1 # VLM judge samples per verdict
texture: bool = False # run the derived texture pass
+ #: scene_blender judged frames: Cycles samples (adaptive + OIDN), owner D1 2026-09-24
+ blender_samples: int = 32
#: budget ceilings a run of this shape should not need to exceed
max_minutes: float = 60.0
#: measured expectation (docs/COST.md) — reported by ``3dcode cost profiles``
@@ -94,7 +96,7 @@ PROFILES: dict[str, Profile] = {
planner=_D.planner,
judge="gemini:gemini-3.7-flash",
captioner=_D.captioner,
- rounds=2, candidates=1, judge_samples=2, texture=False,
+ rounds=2, candidates=1, judge_samples=2, texture=False, blender_samples=16,
max_minutes=30.0,
expected_usd=0.30,
expected_score="graphics 0.81 median (5/6 passed); objects clear the gates less often "
@@ -124,7 +126,7 @@ PROFILES: dict[str, Profile] = {
planner=_D.planner,
judge=_D.judge,
captioner=_D.captioner,
- rounds=4, candidates=2, judge_samples=3, texture=True,
+ rounds=4, candidates=2, judge_samples=3, texture=True, blender_samples=64,
max_minutes=90.0,
expected_usd=3.20,
expected_score="best-of-2 lifted the stool baseline 0.563 → 0.612 and the texture pass "
diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.py
index dc41798b..518bacdb 100644
--- a/harness/codeverse3d/doctor.py
+++ b/harness/codeverse3d/doctor.py
@@ -77,6 +77,80 @@ def check_blender() -> list[Row]:
return [("blender", "OK" if okk else "FAIL", f"{v} @ {b}")]
+#: one headless Blender run: the Cycles CUDA device list and (with EEVEE) a 32x18 EEVEE frame whose GL
+#: renderer string says whether the d3d12 env put it on the GPU or it fell to llvmpipe
+_BLENDER_RENDER_PROBE = """
+import json, sys
+import bpy
+out = {}
+p = bpy.context.preferences.addons["cycles"].preferences
+try:
+ p.compute_device_type = "CUDA"
+ p.refresh_devices()
+ out["cuda"] = [d.name for d in p.devices if d.type == "CUDA"]
+except Exception as e:
+ out["cuda"], out["cuda_error"] = [], str(e)[:200]
+if "--eevee" in sys.argv:
+ try:
+ sc = bpy.context.scene
+ sc.render.engine = "BLENDER_EEVEE"
+ sc.render.resolution_x, sc.render.resolution_y = 32, 18
+ sc.eevee.taa_render_samples = 1
+ bpy.ops.render.render()
+ import gpu
+ out["gl"] = gpu.platform.renderer_get()
+ except Exception as e:
+ out["gl_error"] = str(e)[:200]
+print("C3D_DOCTOR " + json.dumps(out))
+"""
+
+
+def check_blender_render(*, eevee: bool = True, timeout_s: int = 120) -> list[Row]:
+ """What scene_blender's judged frames render on (owner D1/D8): Cycles on CUDA or on the CPU,
+ EEVEE on the GPU or silently on llvmpipe, and the machine-wide GPU render slots."""
+ import json
+
+ from codeverse3d.languages.blender import blender_env
+ from codeverse3d.spatial.gl_render import GPU_ENV
+ from codeverse3d.spatial.render_blender import gpu_slots
+
+ s = get_settings()
+ b = s.resolve_blender()
+ if not b:
+ return [("blender render", "SKIP", "no Blender binary")]
+ cmd = [b, "-b", "--factory-startup", "--python-expr", _BLENDER_RENDER_PROBE, "--"] + (["--eevee"] if eevee else [])
+ try:
+ proc = run_subprocess(cmd, cwd=Path.cwd(), env={**blender_env(), **GPU_ENV}, timeout_s=timeout_s)
+ except OSError as e:
+ return [("blender render", "FAIL", f"could not run {b}: {e}")]
+ line = next((ln for ln in reversed(proc.stdout.splitlines()) if ln.startswith("C3D_DOCTOR ")), "")
+ if proc.timed_out or not line:
+ why = f"timed out after {timeout_s}s" if proc.timed_out else f"exit {proc.returncode}, no probe line"
+ return [("blender render", "FAIL", why)]
+ res = json.loads(line.removeprefix("C3D_DOCTOR "))
+ r = s.render
+ cuda = res.get("cuda") or []
+ rows: list[Row] = [(
+ "blender cycles", "OK" if cuda else "WARN",
+ (f"CUDA: {', '.join(cuda)}" if cuda else f"no CUDA device{' (' + res['cuda_error'] + ')' if res.get('cuda_error') else ''}"
+ " — scene_blender frames render on the CPU (~3.3x slower)")
+ + f"; judged frames: {r.blender_engine} {r.blender_samples} spp, device {r.blender_device}")]
+ if eevee:
+ gl = str(res.get("gl") or "")
+ if res.get("gl_error") or not gl:
+ rows.append(("blender eevee", "FAIL", f"EEVEE smoke frame failed: {res.get('gl_error', 'no GL renderer')}"))
+ else:
+ soft = "llvmpipe" in gl.lower()
+ rows.append(("blender eevee", "WARN" if soft else "OK",
+ f"{gl} — software GL: EEVEE would be ~10x slower (the Cycles default is unaffected)" if soft
+ else f"GPU (Mesa d3d12 env): {gl}"))
+ slots = gpu_slots(s)
+ busy = slots.busy()
+ rows.append(("blender gpu slots", "WARN" if busy >= slots.n else "OK",
+ f"{busy}/{slots.n} busy machine-wide ({slots.root}); a render waits {r.blender_gpu_wait_s:g}s, then the CPU"))
+ return rows
+
+
def check_node() -> list[Row]:
from codeverse3d.spatial.node import NODE_MIN_STR, node_version_error, parse_node_version
@@ -257,6 +331,7 @@ def run_doctor(*, live: bool = False, gpu: bool = True, skills: bool = False) ->
rows: list[Row] = []
rows += check_python_deps()
rows += check_blender()
+ rows += check_blender_render(eevee=gpu)
rows += check_node()
if gpu:
rows += check_gpu_probe()
diff --git a/harness/codeverse3d/languages/wrappers/render_bpy_scene.py b/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
new file mode 100644
index 00000000..053e6522
--- /dev/null
+++ b/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
@@ -0,0 +1,291 @@
+"""Blender render driver for a built ``scene_blender`` workspace — executed BY Blender, never
+imported by the harness.
+
+ blender -b --factory-startup <ws>/artifacts/scene.blend --python render_bpy_scene.py -- <job.json>
+
+The harness (``spatial/render_blender.py``) writes the job; every number in it is already in
+the BLENDER frame (Z-up, -Y front, metres — the harness converts, ``conventions`` owns frames):
+
+ {"out": "/abs/dir", "result": "/abs/dir/blender_frames.json",
+ "engine": "cycles" | "eevee" | "workbench", "samples": 32, "device": "GPU" | "CPU",
+ "width": 1024, "height": 576, "times": [0.0, 1.5], "authored": true,
+ "cameras": [{"name", "kind", "position", "look_at", "fov", "no_fog", "times"}]}
+
+What it does:
+ 1. render settings — ALL harness-owned, whatever the .blend carries: engine, samples,
+ device (Cycles CUDA; no CUDA device → CPU, recorded), adaptive sampling + OIDN, a fixed
+ seed, AgX / look None / exposure 0 on the sRGB display, RGB 8-bit PNG, no transparent film;
+ 2. cameras: with ``authored`` the .blend's own camera objects (``scene["c3d_cameras"]`` gives
+ their order, else the scene camera first then by name; ``cam["c3d_look_at"]`` their target,
+ else 10 m along the view axis), rendered as authored at every time; then one harness camera
+ per job spec (vertical ``fov`` like three.js), at the spec's own times;
+ 3. per time (ascending): ``frame_set(1 + round(t * fps))``, then every camera renders one PNG
+ ``<name>_<tag>.png`` (the three.js driver's file names); ``no_fog`` views render with the
+ world volume unlinked (the overview rig reads structure, not atmosphere);
+ 4. writes the result json atomically: the frames (Blender-frame poses, per-frame wall ms),
+ the device actually used, the GL renderer (EEVEE / Workbench) and every per-frame error.
+
+A frame that fails is recorded and the others still render. Exit codes: 0 = result written;
+2 = driver bug (no result). Standalone: stdlib + bpy only.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+import re
+import sys
+import time
+from typing import Any
+
+sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
+import bpy # noqa: E402
+from _wrapper_common import ( # noqa: E402 (sibling, Blender-executed)
+ _write_json_atomic,
+ exit_after,
+ wrapper_argv,
+)
+from mathutils import Vector # noqa: E402
+
+ENGINES = {"cycles": "CYCLES", "eevee": "BLENDER_EEVEE", "workbench": "BLENDER_WORKBENCH"}
+#: a harness camera's clip range: Cycles has no depth-precision cost, so the far plane is simply out of the way
+CLIP_START, CLIP_END = 0.05, 20000.0
+LOOK_AHEAD_M = 10.0
+
+
+def tag(t: float) -> str:
+ """``0 → t0``, ``1.5 → t1p5``: the three.js driver's ``tag()`` (render_scene.mjs), so both
+ languages name a view's file the same way."""
+ s = f"{t:.2f}".rstrip("0").rstrip(".")
+ return "t" + s.replace(".", "p")
+
+
+def safe_name(name: str) -> str:
+ return re.sub(r"[^A-Za-z0-9_.-]+", "_", name).strip("._") or "camera"
+
+
+def frame_of(t: float, scene: Any) -> int:
+ fps = scene.render.fps / (scene.render.fps_base or 1.0)
+ return 1 + round(t * fps)
+
+
+# --------------------------------------------------------------------------- settings
+def setup_render(scene: Any, job: dict[str, Any]) -> dict[str, Any]:
+ """Engine / device / samples / colour: returns what was actually configured."""
+ engine = str(job.get("engine") or "cycles")
+ samples = int(job.get("samples") or 32)
+ want = str(job.get("device") or "GPU").upper()
+ info: dict[str, Any] = {"engine": engine, "samples": samples, "device": "CPU", "device_names": [], "device_fallback": ""}
+ r = scene.render
+ r.engine = ENGINES[engine]
+ r.resolution_x, r.resolution_y = int(job["width"]), int(job["height"])
+ r.resolution_percentage = 100
+ r.film_transparent = False
+ r.use_border = False
+ img = r.image_settings
+ img.file_format = "PNG"
+ img.color_mode = "RGB"
+ img.color_depth = "8"
+ try:
+ scene.display_settings.display_device = "sRGB"
+ vs = scene.view_settings
+ vs.view_transform = "AgX"
+ vs.look = "None"
+ vs.exposure = 0.0
+ vs.gamma = 1.0
+ vs.use_curve_mapping = False
+ except (TypeError, AttributeError) as e:
+ info["colour_warning"] = str(e)[:200]
+ if engine == "cycles":
+ c = scene.cycles
+ if want == "GPU":
+ prefs = bpy.context.preferences.addons["cycles"].preferences
+ try:
+ prefs.compute_device_type = "CUDA"
+ prefs.refresh_devices()
+ gpus = [d for d in prefs.devices if d.type == "CUDA"]
+ except (TypeError, AttributeError, RuntimeError):
+ gpus = []
+ for d in prefs.devices:
+ d.use = d.type == "CUDA"
+ if gpus:
+ info["device"] = "GPU"
+ info["device_names"] = [d.name for d in gpus]
+ else:
+ info["device_fallback"] = "no CUDA device"
+ c.device = info["device"]
+ c.samples = samples
+ c.use_adaptive_sampling = True
+ c.use_denoising = True
+ c.denoiser = "OPENIMAGEDENOISE"
+ c.denoising_use_gpu = info["device"] == "GPU"
+ c.seed = 0
+ c.use_animated_seed = False
+ elif engine == "eevee":
+ scene.eevee.taa_render_samples = samples
+ info["device"] = want # the GL context decides; the harness picks the env (d3d12 = GPU)
+ else:
+ info["samples"] = 0
+ info["device"] = want
+ return info
+
+
+# --------------------------------------------------------------------------- cameras
+def _vec(v: Any) -> list[float]:
+ return [round(float(x), 5) for x in v]
+
+
+def vertical_fov_deg(cam: Any, aspect: float) -> float:
+ """The camera's VERTICAL field of view at the render aspect (the plan's fov is vertical)."""
+ d = cam.data
+ fit = d.sensor_fit
+ if fit == "VERTICAL":
+ return math.degrees(d.angle_y)
+ if fit == "HORIZONTAL" or aspect >= 1.0:
+ return math.degrees(2 * math.atan(math.tan(d.angle_x / 2) / aspect))
+ return math.degrees(d.angle_x) # AUTO on a portrait frame: the sensor width spans the height
+
+
+def authored_cameras(scene: Any) -> list[Any]:
+ cams = [o for o in scene.objects if o.type == "CAMERA"]
+ order = scene.get("c3d_cameras")
+ if order:
+ names = [str(n) for n in (json.loads(order) if isinstance(order, str) else list(order))]
+ by = {o.name: o for o in cams}
+ return [by[n] for n in names if n in by]
+ cams.sort(key=lambda o: (o is not scene.camera, o.name))
+ return cams
+
+
+def authored_spec(obj: Any, aspect: float, times: list[float]) -> dict[str, Any]:
+ m = obj.matrix_world
+ pos = m.translation.copy()
+ look = obj.get("c3d_look_at")
+ if look is not None and len(look) == 3:
+ target = Vector([float(x) for x in look])
+ else:
+ fwd = (m.to_3x3() @ Vector((0.0, 0.0, -1.0))).normalized()
+ target = pos + fwd * LOOK_AHEAD_M
+ return {"name": obj.name, "kind": "authored", "position": _vec(pos), "look_at": _vec(target),
+ "fov": round(vertical_fov_deg(obj, aspect), 4), "no_fog": False, "times": times, "object": obj}
+
+
+def harness_camera(spec: dict[str, Any]) -> Any:
+ data = bpy.data.cameras.new(f"c3d_{spec['name']}")
+ data.sensor_fit = "VERTICAL"
+ data.angle_y = math.radians(float(spec.get("fov") or 50.0))
+ data.clip_start, data.clip_end = CLIP_START, CLIP_END
+ obj = bpy.data.objects.new(f"c3d_{spec['name']}", data)
+ bpy.context.scene.collection.objects.link(obj)
+ pos, target = Vector(spec["position"]), Vector(spec["look_at"])
+ d = target - pos
+ if d.length < 1e-9:
+ d = Vector((0.0, 1.0, 0.0))
+ obj.location = pos
+ obj.rotation_euler = d.to_track_quat("-Z", "Y").to_euler()
+ return obj
+
+
+# --------------------------------------------------------------------------- fog
+def unlink_world_volume(scene: Any) -> list[tuple[Any, Any]]:
+ """Remove the world output's Volume links; returns them for ``relink``."""
+ w = scene.world
+ if w is None or not w.use_nodes or w.node_tree is None:
+ return []
+ removed = []
+ for n in w.node_tree.nodes:
+ if n.type == "OUTPUT_WORLD" and "Volume" in n.inputs:
+ for link in list(n.inputs["Volume"].links):
+ removed.append((link.from_socket, link.to_socket))
+ w.node_tree.links.remove(link)
+ return removed
+
+
+def relink(scene: Any, links: list[tuple[Any, Any]]) -> None:
+ for a, b in links:
+ scene.world.node_tree.links.new(a, b)
+
+
+def gl_renderer() -> str:
+ try:
+ import gpu
+
+ return f"{gpu.platform.vendor_get()} {gpu.platform.renderer_get()}".strip()
+ except Exception: # noqa: BLE001 — no GL context (Cycles) is not an error
+ return ""
+
+
+# --------------------------------------------------------------------------- main
+def main() -> int:
+ job_path = wrapper_argv()[0]
+ with open(job_path) as fh:
+ job = json.load(fh)
+ t_start = time.perf_counter()
+ scene = bpy.context.scene
+ out = job["out"]
+ os.makedirs(out, exist_ok=True)
+ result: dict[str, Any] = {"ok": False, "blender": bpy.app.version_string, "blend": bpy.data.filepath,
+ "frames": [], "errors": []}
+ result.update(setup_render(scene, job))
+ aspect = float(job["width"]) / float(job["height"])
+ times = sorted({float(t) for t in job.get("times") or [0.0]})
+ scene.frame_set(frame_of(times[0], scene)) # evaluated poses (constraints, keyframed cameras) at the first time
+ specs: list[dict[str, Any]] = []
+ if job.get("authored", True):
+ specs += [authored_spec(o, aspect, times) for o in authored_cameras(scene)]
+ for s in job.get("cameras") or []:
+ specs.append({**s, "kind": s.get("kind") or "orbit", "times": sorted(float(t) for t in s.get("times") or times),
+ "object": None})
+ seen: set[str] = set()
+ unique = []
+ for s in specs:
+ s["file_stem"] = safe_name(str(s["name"]))
+ if s["file_stem"] in seen:
+ continue
+ seen.add(s["file_stem"])
+ unique.append(s)
+ for s in unique:
+ if s["object"] is None:
+ s["object"] = harness_camera(s)
+ result["setup_ms"] = int((time.perf_counter() - t_start) * 1000)
+ all_times = sorted({t for s in unique for t in s["times"]})
+ for t in all_times:
+ frame = frame_of(t, scene)
+ scene.frame_set(frame)
+ for s in unique:
+ if t not in s["times"]:
+ continue
+ path = f"{s['file_stem']}_{tag(t)}.png"
+ scene.camera = s["object"]
+ scene.render.filepath = os.path.join(out, path)
+ fog = unlink_world_volume(scene) if s.get("no_fog") else []
+ t0 = time.perf_counter()
+ try:
+ bpy.ops.render.render(write_still=True)
+ except Exception as e: # noqa: BLE001 — one failed frame must not cost the others
+ result["errors"].append(f"render failed for '{s['name']}' at t={t:g}: {type(e).__name__}: {e}"[:600])
+ continue
+ finally:
+ if fog:
+ relink(scene, fog)
+ ms = int((time.perf_counter() - t0) * 1000)
+ if not os.path.isfile(os.path.join(out, path)):
+ result["errors"].append(f"render of '{s['name']}' at t={t:g} wrote no image")
+ continue
+ result["frames"].append({
+ "name": s["name"], "kind": s["kind"], "path": path, "time_s": t, "frame": frame,
+ "position": s["position"], "look_at": s["look_at"], "fov": s["fov"],
+ "no_fog": bool(s.get("no_fog")), "render_ms": ms,
+ })
+ if result["engine"] in ("eevee", "workbench"):
+ result["gl_renderer"] = gl_renderer()
+ result["cameras"] = [{k: v for k, v in s.items() if k not in ("object", "file_stem")} for s in unique]
+ result["ok"] = bool(result["frames"]) and not result["errors"]
+ result["duration_ms"] = int((time.perf_counter() - t_start) * 1000)
+ _write_json_atomic(job["result"], result)
+ return 0
+
+
+if __name__ == "__main__":
+ exit_after(main)
diff --git a/harness/codeverse3d/spatial/frame_metrics.py b/harness/codeverse3d/spatial/frame_metrics.py
index 9b5584d0..e88a15d4 100644
--- a/harness/codeverse3d/spatial/frame_metrics.py
+++ b/harness/codeverse3d/spatial/frame_metrics.py
@@ -93,6 +93,71 @@ _SMALL_HINT = (
)
+_EYE_HINT = "set position[1] = heightAt(x, z) + 1.6 (eye level) — never below the terrain"
+_LOW_HINT = "human shots: position[1] = heightAt(x, z) + 1.6; establishing: 6–20 m above ground looking down 15–30°"
+
+#: scene_blender's words for the same fixes (D1, lane B): bpy lamps / world nodes / keyframes, the
+#: Blender frame (z up), ``ctx.height_at``. The thresholds are the same; only the advice differs.
+_BPY_HINTS: dict[str, str] = {
+ "dark": (
+ "raise the light in build_env (src/env.py): the Sun lamp's strength (`sun.data.energy` 3–5 for day, 1–2 at golden "
+ "hour; a sun below the horizon is the night rig) and the world Background / Sky Texture Strength (the fill) — do not "
+ "add a second sun; add practical lights where the brief has them (a Point lamp of 20–200 W at each lantern plus an "
+ "Emission shader on the lamp mesh); keep a world Volume thin (density ≤ 0.02) or it swallows the light; dusk/night is "
+ "orange/purple/deep blue, NOT black (check with scene_views: camera_checks.mean_lum)"),
+ "lowkey": (
+ "this frame is DIM BUT LIT — it has real contrast, so do NOT raise the world Background strength or add a big "
+ "area/sun lamp to fix it: flat fill turns a night scene into a grey wash, washes dark materials out and drowns "
+ "emissive effects. Lift the picture where the light actually comes from: raise the Emission Strength of the "
+ "lamps/lanterns, add or brighten a Point lamp at each practical light, give dark materials a low but non-zero Base "
+ "Color so they read as material and not as void, and let the shadowed areas stay dark. Only if the frame is ALSO "
+ "flat (no contrast) does it need key/fill."),
+ "blown": (
+ "lower exposure: Sun lamp strength ≤ 5, world Background / Sky Texture strength ≤ 1.5, no white Emission planes, "
+ "Emission Strength ≤ 5 on large surfaces — the harness renders AgX at exposure 0 and owns the view settings"),
+ "flat": (
+ "one colour dominates the frame: aim the camera at content (look_at the zone centre), add contrast with a Sun lamp "
+ "that casts shadows, vary materials, and make sure the world (Sky Texture / Background) and any Volume are not one "
+ "flat tint"),
+ "near": ("move the camera ≥ 0.5 m away from every surface (raise it above ground/terrain: z = ctx.height_at(x, y) + 1.6, "
+ "pull it out of walls and trees) and keep look_at on the content"),
+ "static": (
+ "nothing moved between the animation times: give the planned motion a visible amplitude — foliage/banner sway "
+ "±0.10–0.20 rad, water surface ≥ 3 cm vertical, particles ≥ 0.6 m of travel per 1.5 s, rotating parts ≥ 20°/s — "
+ "as DATA the .blend plays by itself: keyframes (object location/rotation, node inputs, shape keys), a "
+ "simple-expression driver on `frame` (e.g. `sin(frame*0.2)*0.15`; python-function drivers never run here) or the "
+ "geometry-nodes Scene Time node. The harness renders t = 0 s and t = 1.5 s as frames 1 and 46 (30 fps)"),
+ "small": _SMALL_HINT.replace("lookAt", "look_at"),
+ "eye": "set the camera's z = ctx.height_at(x, y) + 1.6 (eye level) — never below the terrain",
+ "low": "human shots: z = ctx.height_at(x, y) + 1.6; establishing: 6–20 m above ground looking down 15–30°",
+ "unused_glb": (
+ "the hero GLB is imported into ctx.assets['<key>'] and nothing places it — add a collection-instance Empty of "
+ "ctx.assets['<key>'] inside the zone the plan puts it in. If a refine round replaced the hero with a procedural "
+ "rebuild, say so in the plan: `assets[].kind: blender_glb` must not claim a hero the rendered scene does not contain."),
+}
+
+#: fix hints per scene language (``metrics["language"]``; a payload without one is three.js, as
+#: every recorded round is)
+HINTS: dict[str, dict[str, str]] = {
+ "scene_threejs": {"dark": _DARK_HINT, "lowkey": _LOWKEY_HINT, "blown": _BLOWN_HINT, "flat": _FLAT_HINT,
+ "near": _NEAR_HINT, "static": _STATIC_HINT, "small": _SMALL_HINT, "eye": _EYE_HINT, "low": _LOW_HINT},
+ "scene_blender": _BPY_HINTS,
+}
+
+#: a judged Blender frame slower than this (GPU seconds at the configured samples; the CPU
+#: fallback gets ``SLOW_FRAME_CPU_FACTOR`` x) is a WARN naming the heaviest zone (owner D2).
+#: Calibrated 2026-09-24 on this box, Cycles CUDA 32 spp + OIDN at 1024x576: 0.9 s for a
+#: 520 k-tri / 310-object scene, 3.6 s with 72 k GN grass blades + 30 point lights + glass +
+#: a world volume — 10 s is ~3x the heaviest probe scene.
+SLOW_FRAME_S = 10.0
+SLOW_FRAME_CPU_FACTOR = 3.3
+
+
+def hints_for(metrics: dict[str, Any]) -> dict[str, str]:
+ """The fix-hint table for ``metrics``' scene language."""
+ return HINTS.get(str(metrics.get("language") or "scene_threejs"), HINTS["scene_threejs"])
+
+
def _view_kind(chk: dict[str, Any]) -> str:
return str(chk.get("kind") or "authored")
@@ -106,7 +171,7 @@ def _num(chk: dict[str, Any], key: str) -> float | None:
return float(v) if isinstance(v, (int, float)) else None
-def _exposure_findings(chk: dict[str, Any], *, authored: bool) -> list[GateFinding]:
+def _exposure_findings(chk: dict[str, Any], *, authored: bool, hints: dict[str, str]) -> list[GateFinding]:
name = str(chk.get("name", "?"))
sev = Severity.ERROR if authored else Severity.WARN
out: list[GateFinding] = []
@@ -127,19 +192,20 @@ def _exposure_findings(chk: dict[str, Any], *, authored: bool) -> list[GateFindi
msg = (f"frame is dim but lit: mean luminance {mean:.2f} with contrast {std:.2f} "
f"({dark or 0:.0%} of pixels near black) — low-key by design, not unlit")
out.append(_f(Severity.WARN if low_key else sev, name, rig + msg,
- _LOWKEY_HINT if low_key else _DARK_HINT,
+ hints["lowkey"] if low_key else hints["dark"],
kind="dark_frame", view=name, mean_lum=mean, dark_frac=dark))
if blown is not None and blown > BLOWN_FRAC:
- out.append(_f(sev, name, rig + f"frame blown out: {blown:.0%} of pixels pure white", _BLOWN_HINT,
+ out.append(_f(sev, name, rig + f"frame blown out: {blown:.0%} of pixels pure white", hints["blown"],
kind="blown_frame", view=name, blown_frac=blown))
if modal is not None and modal > FLAT_MODAL_FRAC and not is_dark:
flat_sev = sev if modal > FLAT_MODAL_ERROR else Severity.WARN
- out.append(_f(flat_sev, name, rig + f"flat frame: one luminance band holds {modal:.0%} of the pixels", _FLAT_HINT,
+ out.append(_f(flat_sev, name, rig + f"flat frame: one luminance band holds {modal:.0%} of the pixels", hints["flat"],
kind="flat_frame", view=name, modal_frac=modal, mean_lum=mean))
return out
-def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float | None) -> list[GateFinding]:
+def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float | None,
+ hints: dict[str, str]) -> list[GateFinding]:
name = str(chk.get("name", "?"))
sev = Severity.ERROR if authored else Severity.WARN
out: list[GateFinding] = []
@@ -148,7 +214,7 @@ def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float |
rig = "" if authored else "harness rig view (not an authored camera): "
if chk.get("camera_in_geometry") or (near is not None and near < NEAR_HIT_M):
where = f"inside {inside[:3]}" if inside else f"nearest surface {near:.2f} m ({chk.get('nearest_hit_name', '')})"
- out.append(_f(sev, name, rig + f"camera inside / touching geometry: {where}", _NEAR_HINT,
+ out.append(_f(sev, name, rig + f"camera inside / touching geometry: {where}", hints["near"],
kind="camera_in_geometry", view=name, nearest_hit_m=near, inside=inside[:5]))
else:
# The shot is a surface: most of the 3 x 3 sight rays end within arm's reach. cmp6's
@@ -187,7 +253,7 @@ def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float |
buried = _frame_looks_buried(chk)
out.append(_f(Severity.ERROR if buried else Severity.WARN, name,
f"camera is {above_g:.1f} m under {under} — the frame is its underside",
- "set position[1] = heightAt(x, z) + 1.6 (eye level) — never below the terrain",
+ hints["eye"],
kind="camera_underground" if buried else "camera_under_ground_mesh",
view=name, eye_height_m=eye, ground_above_m=above_g))
elif authored and below is not None:
@@ -199,7 +265,7 @@ def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float |
under = str(chk.get("ground_below_name") or "the surface beneath it")
if below < EYE_MIN_ABOVE_GROUND_M:
out.append(_f(Severity.WARN, name, f"camera eye only {below:.2f} m above {under} — ant's-eye view",
- "human shots: position[1] = heightAt(x, z) + 1.6; establishing: 6–20 m above ground looking down 15–30°",
+ hints["low"],
kind="camera_low", view=name, eye_height_m=eye, ground_below_m=below))
elif below > EYE_MAX_ABOVE_GROUND_M:
out.append(_f(Severity.WARN, name, f"camera {below:.0f} m above {under} — satellite view, not a shot",
@@ -219,12 +285,12 @@ def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float |
f"camera is {-above:.1f} m below the scene's highest ground surface ({ground_y:.2f} m)"
+ ("" if buried else " — the frame itself renders fine, so this is probably terrain"
" (a hill / raised bed / backdrop) reaching above the camera, not a buried camera"),
- "set position[1] = heightAt(x, z) + 1.6 (eye level) — never below the terrain",
+ hints["eye"],
kind="camera_underground" if buried else "camera_below_high_ground",
view=name, eye_height_m=eye, ground_y=ground_y))
elif above < EYE_MIN_ABOVE_GROUND_M:
out.append(_f(Severity.WARN, name, f"camera eye only {above:.2f} m above ground — ant's-eye view",
- "human shots: position[1] = heightAt(x, z) + 1.6; establishing: 6–20 m above ground looking down 15–30°",
+ hints["low"],
kind="camera_low", view=name, eye_height_m=eye, ground_y=ground_y))
elif above > EYE_MAX_ABOVE_GROUND_M:
out.append(_f(Severity.WARN, name, f"camera {above:.0f} m above ground — satellite view, not a shot",
@@ -245,7 +311,7 @@ def _frame_looks_buried(chk: dict[str, Any]) -> bool:
return modal is not None and modal > FLAT_MODAL_ERROR
-def _coverage_finding(chk: dict[str, Any], *, role: str) -> GateFinding | None:
+def _coverage_finding(chk: dict[str, Any], *, role: str, hints: dict[str, str]) -> GateFinding | None:
"""role: 'establishing' | 'authored' | 'overview' | 'eye'."""
content = _num(chk, "content_frac")
if content is None or role == "eye":
@@ -254,10 +320,10 @@ def _coverage_finding(chk: dict[str, Any], *, role: str) -> GateFinding | None:
sky, ground = _num(chk, "sky_frac"), _num(chk, "ground_frac")
detail = f"content {content:.0%} of the frame (sky {sky or 0:.0%}, ground {ground or 0:.0%})"
if role == "establishing" and content < CONTENT_MIN_ESTABLISHING:
- return _f(Severity.ERROR, name, f"establishing shot shows too little content: {detail}", _SMALL_HINT,
+ return _f(Severity.ERROR, name, f"establishing shot shows too little content: {detail}", hints["small"],
kind="content_small", view=name, content_frac=content, sky_frac=sky, ground_frac=ground, role=role)
if role == "authored" and content < CONTENT_MIN_AUTHORED:
- return _f(Severity.WARN, name, f"shot shows little content: {detail}", _SMALL_HINT,
+ return _f(Severity.WARN, name, f"shot shows little content: {detail}", hints["small"],
kind="content_small", view=name, content_frac=content, sky_frac=sky, ground_frac=ground, role=role)
if role == "overview" and content < CONTENT_MIN_OVERVIEW:
return _f(Severity.WARN, name, f"overview rig sees sparse content: {detail}",
@@ -283,7 +349,7 @@ def stored_motion(metrics: dict[str, Any]) -> list[MotionRow]:
return out
-def _motion_findings(rows: list[MotionRow]) -> list[GateFinding]:
+def _motion_findings(rows: list[MotionRow], hints: dict[str, str]) -> list[GateFinding]:
"""One finding for the whole scene: frozen (ERROR) or the measured per-camera table (INFO)."""
moves = scene_moves(rows)
if moves is None:
@@ -292,7 +358,7 @@ def _motion_findings(rows: list[MotionRow]) -> list[GateFinding]:
worst = max((r.changed_frac for r in rows if r.authored), default=0.0)
return [_f(Severity.ERROR, "overall",
f"nothing moves: the largest change on an authored camera is {worst:.2%} of pixels between "
- f"t={rows[0].t0:g}s and t={rows[0].t1:g}s (measured, not perceived)", _STATIC_HINT,
+ f"t={rows[0].t0:g}s and t={rows[0].t1:g}s (measured, not perceived)", hints["static"],
kind="no_motion", changed_frac=round(worst, 5),
views=[r.name for r in rows if r.authored][:6])]
moving = [r for r in rows if r.authored and r.moving]
@@ -310,7 +376,10 @@ _UNUSED_GLB_HINT = (
)
-def _glb_findings(census: dict[str, Any]) -> list[GateFinding]:
+HINTS["scene_threejs"]["unused_glb"] = _UNUSED_GLB_HINT
+
+
+def _glb_findings(census: dict[str, Any], hints: dict[str, str]) -> list[GateFinding]:
"""A GLB that was loaded and contributed no geometry to the rendered scene.
Measured 2026-08-25 on tsr_scn_boat_workshop_v2: ``src/scene.js`` loads
@@ -335,7 +404,7 @@ def _glb_findings(census: dict[str, Any]) -> list[GateFinding]:
out.append(_f(Severity.WARN, "overall",
f"{url} is loaded but no geometry from it reaches the rendered scene "
f"({r.get('meshes', 0)} mesh(es) in the file, 0 in the frame)",
- _UNUSED_GLB_HINT, kind="unused_glb_asset", url=url,
+ hints["unused_glb"], kind="unused_glb_asset", url=url,
meshes=r.get("meshes"), meshes_in_scene=r.get("meshes_in_scene")))
return out
@@ -395,6 +464,36 @@ def _hero_findings(checks: list[dict[str, Any]], census: dict[str, Any]) -> list
return out
+def _render_time_findings(metrics: dict[str, Any]) -> list[GateFinding]:
+ """A Blender frame set whose median JUDGED frame took longer than ``SLOW_FRAME_S`` (owner
+ D2: offline rendering has no draw budget; its cost is seconds per frame). WARN, naming the
+ zone with the most triangles — the first place to thin. Silent for every payload without a
+ ``blender`` block (three.js)."""
+ b = metrics.get("blender")
+ if not isinstance(b, dict):
+ return []
+ ms = sorted(float(v["render_ms"]) for v in metrics.get("views") or []
+ if isinstance(v, dict) and v.get("judge", True) and isinstance(v.get("render_ms"), int | float))
+ if not ms:
+ return []
+ median_s = ms[len(ms) // 2] / 1000.0
+ limit = SLOW_FRAME_S * (SLOW_FRAME_CPU_FACTOR if str(b.get("device")).upper() == "CPU" else 1.0)
+ if median_s <= limit:
+ return []
+ groups = [g for g in (metrics.get("census") or {}).get("groups") or []
+ if isinstance(g, dict) and g.get("kind") == "content" and isinstance(g.get("triangles"), int | float)]
+ heavy = max(groups, key=lambda g: g["triangles"], default=None)
+ where = f"; the heaviest zone is {heavy.get('name')} ({int(heavy['triangles']):,} triangles)" if heavy else ""
+ return [_f(Severity.WARN, str(heavy.get("name")) if heavy else "overall",
+ f"a judged frame takes {median_s:.1f} s to render (median, {b.get('engine')} {b.get('samples')} spp on the "
+ f"{b.get('device')}; the ceiling is {limit:.0f} s){where}",
+ "thin what costs render time: instance repeated geometry (collection instances / geometry-nodes Instance on "
+ "Points) instead of copying meshes, fewer lights (a Point lamp per lantern only where it is seen), fewer "
+ "transmissive/glass and volume objects, lower subdivision levels on what is far from every camera",
+ kind="slow_frame", median_s=round(median_s, 2), limit_s=limit, device=b.get("device"),
+ zone=heavy.get("name") if heavy else None)]
+
+
def frame_findings(metrics: dict[str, Any]) -> GateReport:
"""``scene_frames`` gate from a ``metrics.json`` payload (``camera_checks`` + ``census`` + ``motion``)."""
checks: list[dict[str, Any]] = [c for c in metrics.get("camera_checks") or [] if isinstance(c, dict)]
@@ -402,20 +501,22 @@ def frame_findings(metrics: dict[str, Any]) -> GateReport:
ground_y = float(ground_y) if isinstance(ground_y, (int, float)) else None
findings: list[GateFinding] = []
first_authored = next((c for c in checks if _view_kind(c) == "authored"), None)
+ hints = hints_for(metrics)
for chk in checks:
authored = _view_kind(chk) == "authored"
- findings += _exposure_findings(chk, authored=authored)
- findings += _geometry_findings(chk, authored=authored, ground_y=ground_y)
+ findings += _exposure_findings(chk, authored=authored, hints=hints)
+ findings += _geometry_findings(chk, authored=authored, ground_y=ground_y, hints=hints)
if authored:
role = "establishing" if chk is first_authored else "authored"
else:
role = "overview" if str(chk.get("name", "")).startswith("overview") else "eye"
- cov = _coverage_finding(chk, role=role)
+ cov = _coverage_finding(chk, role=role, hints=hints)
if cov is not None:
findings.append(cov)
- findings += _motion_findings(stored_motion(metrics))
- findings += _glb_findings(metrics.get("census") or {})
+ findings += _motion_findings(stored_motion(metrics), hints)
+ findings += _glb_findings(metrics.get("census") or {}, hints)
findings += _hero_findings(checks, metrics.get("census") or {})
+ findings += _render_time_findings(metrics)
if checks and not [f for f in findings if f.severity != Severity.INFO]:
n = len(checks)
findings.append(_f(Severity.INFO, "overall", f"{n} camera frame(s) checked: exposure, geometry and coverage within limits", "",
diff --git a/harness/codeverse3d/spatial/render_blender.py b/harness/codeverse3d/spatial/render_blender.py
new file mode 100644
index 00000000..0baf124d
--- /dev/null
+++ b/harness/codeverse3d/spatial/render_blender.py
@@ -0,0 +1,341 @@
+"""Render a built ``scene_blender`` workspace: Blender makes the pictures, the JS host measures.
+
+``render_blender_scene(ws, out_dir, ...)`` is what ``SceneBlenderRuntime.render_scene`` calls
+(DESIGN §2 "render", owner D1/D3/D8 2026-09-24). Four steps, one output format:
+
+1. **orbit fit** — ``runtime_js/fit_orbit.mjs`` fits ``conventions.SCENE_VIEWS`` to the census
+ the build's probe wrote (``artifacts/census.json``): the same ``orbit.mjs`` the three.js
+ driver runs in-page, so there is one implementation of the fitting;
+2. **pixels** — ``languages/wrappers/render_bpy_scene.py`` inside Blender on the built
+ ``artifacts/scene.blend``: the authored cameras × every time + the first
+ ``MAX_JUDGE_OVERVIEWS`` overview views at the first time (what someone reads — the judge and
+ the motion metric; the eye-level rig views get geometry checks but no pixels). Engine /
+ samples / device come from ``Settings.render.blender_*`` (Cycles CUDA 32 spp + OIDN by
+ 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
+ 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
+ settle, no camera repair, no post chain (D3: the picture is Blender's);
+4. **the RenderSet** — ``render_scene.render_set_from_metrics``, exactly as for three.js:
+ motion, errors, the judge subset, the contact sheet.
+
+``metrics.json`` gains two keys the three.js payload does not carry: ``language``
+(``"scene_blender"``: the frame gate's fix hints are per language) and ``blender`` (engine,
+device, samples, the fallback reason, the per-step wall times).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+from codeverse3d.config import Settings, get_settings
+from codeverse3d.contracts.artifacts import RenderSet
+from codeverse3d.contracts.plan import BBox, CameraPlan
+from codeverse3d.conventions import (
+ SCENE_VIEWS,
+ ViewPreset,
+ from_authoring_frame,
+ to_authoring_frame,
+)
+from codeverse3d.models.retry import KeyPoolExhausted, Slots
+from codeverse3d.proc import ProcResult, read_json_or_none, run_subprocess, write_json_atomic
+from codeverse3d.spatial._render_common import out_directory, view_specs
+from codeverse3d.spatial.render_scene import (
+ MAX_JUDGE_OVERVIEWS,
+ SceneRenderError,
+ plan_bounds,
+ render_set_from_metrics,
+ run_scene_script,
+)
+from codeverse3d.workspace import Workspace
+
+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"
+LANGUAGE = "scene_blender"
+JOB_NAME = "blender_job.json"
+RESULT_NAME = "blender_frames.json"
+EXTERNAL_NAME = "blender_views.json"
+SLOT_DIR = "blender_gpu"
+#: the keys of a view entry — render_scene.mjs's own view schema
+_VIEW_KEYS = ("name", "kind", "path", "time_s", "position", "lookAt", "fov", "render_ms")
+
+
+def gpu_slots(settings: Settings | None = None) -> Slots:
+ """The machine-wide GPU Blender render slots (``<cache_dir>/slots/blender_gpu/NN.lock``)."""
+ s = settings or get_settings()
+ return Slots(s.render.blender_gpu_slots, s.cache_dir / "slots" / SLOT_DIR)
+
+
+def _to_blender(v: Sequence[float]) -> list[float]:
+ return list(to_authoring_frame(v, FRAME_LANGUAGE))
+
+
+def _to_glb(v: Sequence[float]) -> list[float]:
+ return [round(c, 5) for c in from_authoring_frame(v, FRAME_LANGUAGE)]
+
+
+def _blender_env(engine: str, device: str) -> dict[str, str]:
+ """A headless Blender child's env; EEVEE / Workbench on the GPU need the Mesa d3d12 env
+ (without it they silently land on llvmpipe — measured 10x slower, no error)."""
+ from codeverse3d.languages.blender import blender_env
+ from codeverse3d.spatial.gl_render import GPU_ENV
+
+ env = blender_env()
+ if engine != "cycles" and device == "GPU":
+ env.update(GPU_ENV)
+ return env
+
+
+# --------------------------------------------------------------------------- pixels
+def _run_driver(blend: Path, job: dict[str, Any], out_dir: Path, *, device: str, timeout_s: float,
+ settings: Settings) -> tuple[ProcResult, dict[str, Any] | None]:
+ job = {**job, "device": device}
+ job_path = out_dir / JOB_NAME
+ result_path = out_dir / RESULT_NAME
+ result_path.unlink(missing_ok=True)
+ write_json_atomic(job_path, job)
+ blender = settings.resolve_blender()
+ if not blender:
+ raise SceneRenderError("no Blender binary (set C3D_BINARIES__BLENDER or put blender-5.0 on PATH)")
+ cmd = [blender, "-b", "--factory-startup", str(blend), "--python", str(DRIVER), "--", str(job_path)]
+ proc = run_subprocess(cmd, cwd=out_dir, env=_blender_env(str(job["engine"]), device), timeout_s=timeout_s)
+ result = read_json_or_none(result_path)
+ return proc, result if isinstance(result, dict) and proc.returncode == 0 else None
+
+
+def _failure(proc: ProcResult) -> str:
+ from codeverse3d.languages._common import strip_blender_noise
+
+ tail = strip_blender_noise(proc.stderr + "\n" + proc.stdout)[-800:]
+ return f"exit {proc.returncode}" + (f": {tail}" if tail else "")
+
+
+def render_frames(blend: Path, out_dir: Path, job: dict[str, Any], *, timeout_s: float,
+ settings: Settings | None = None) -> dict[str, Any]:
+ """Run the Blender driver under the GPU-slot policy; its result json + ``fallback`` / ``slot_wait_ms``.
+
+ ``blender_device == "gpu"``: take a slot (wait ≤ ``blender_gpu_wait_s``) and render on the
+ GPU; all slots busy → CPU; a GPU run that dies without a result → one CPU run. A timeout
+ is the scene's weight, not the device's: it raises ``SceneRenderError`` with no retry."""
+ s = settings or get_settings()
+ fallback = ""
+ wait_ms = 0
+ if s.render.blender_device == "cpu":
+ device = "CPU"
+ else:
+ slots = gpu_slots(s)
+ t0 = time.monotonic()
+ try:
+ fd: int | None = slots.take(s.render.blender_gpu_wait_s)
+ except KeyPoolExhausted:
+ fd = None
+ fallback = f"all {slots.n} GPU render slots busy for {s.render.blender_gpu_wait_s:g}s ({slots.root})"
+ wait_ms = int((time.monotonic() - t0) * 1000)
+ device = "GPU" if fd is not None else "CPU"
+ if fd is not None:
+ try:
+ proc, result = _run_driver(blend, job, out_dir, device="GPU", timeout_s=timeout_s, settings=s)
+ finally:
+ Slots.give(fd)
+ if proc.timed_out:
+ raise SceneRenderError(f"blender render timed out after {timeout_s:.0f}s on the GPU")
+ if result is not None:
+ return {**result, "fallback": result.get("device_fallback") or "", "slot_wait_ms": wait_ms}
+ fallback = f"GPU render failed ({_failure(proc)[:300]})"
+ device = "CPU"
+ if fallback:
+ log.warning("scene_blender render on the CPU: %s", fallback)
+ proc, result = _run_driver(blend, job, out_dir, device=device, timeout_s=timeout_s, settings=s)
+ if proc.timed_out:
+ raise SceneRenderError(f"blender render timed out after {timeout_s:.0f}s on the {device}")
+ if result is None:
+ raise SceneRenderError(f"blender render driver failed: {_failure(proc)}")
+ return {**result, "fallback": fallback or result.get("device_fallback") or "", "slot_wait_ms": wait_ms}
+
+
+# --------------------------------------------------------------------------- orbit
+def fit_orbit(census_path: Path, views: Sequence[ViewPreset], *, width: int, height: int,
+ bounds: BBox | None, timeout_s: float = 60.0) -> dict[str, Any]:
+ """``fit_orbit.mjs`` on a census: ``{framing_bbox, cameras}`` in the GLB frame (``{}`` on failure)."""
+ args = ["--census", str(census_path), "--orbit-views", json.dumps(view_specs(views)),
+ "--width", str(width), "--height", str(height)]
+ if bounds is not None:
+ args += ["--bounds", json.dumps({"min": list(bounds.min), "max": list(bounds.max)})]
+ try:
+ return dict(run_scene_script("fit_orbit.mjs", args, timeout_s=timeout_s).summary)
+ except SceneRenderError as e:
+ log.warning("orbit fit failed: %s", e)
+ return {}
+
+
+def _pixel_orbit(specs: list[dict[str, Any]]) -> set[str]:
+ """The rig views that get Blender pixels: the first ``MAX_JUDGE_OVERVIEWS`` overviews."""
+ return set([str(o["name"]) for o in specs if str(o["name"]).startswith("overview")][:MAX_JUDGE_OVERVIEWS])
+
+
+# --------------------------------------------------------------------------- entry
+def render_blender_scene(
+ ws: Workspace,
+ out_dir: Path,
+ *,
+ cameras: list[CameraPlan] | None = None,
+ orbit: bool = True,
+ times: Sequence[float] = (0.0, 1.5),
+ width: int = 1024,
+ height: int = 576,
+ sheet: bool = True,
+ orbit_views: Sequence[ViewPreset] = SCENE_VIEWS,
+ timeout_s: float | None = None,
+ bounds: BBox | None = None,
+ blend: Path | None = None,
+ census: Path | None = None,
+ scene_rel: str = "src/scene.js",
+ engine: str | None = None,
+ samples: int | None = None,
+) -> RenderSet:
+ """Authored cameras (+ the orbit rig) × ``times`` rendered by Blender → a RenderSet whose
+ ``metrics.json`` has the three.js driver's schema.
+
+ ``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``
+ / ``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``."""
+ s = get_settings()
+ 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"
+ 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()
+ if not blend.is_file():
+ return _empty(out_dir, f"no {blend.name}: the build did not save the scene (see build.json)",
+ width=width, height=height, orbit_views=orbit_views)
+ # 1. the orbit rig, fitted to the census content (GLB frame)
+ t0 = time.monotonic()
+ fit: dict[str, Any] = {}
+ if orbit and orbit_views:
+ if census.is_file():
+ fit = fit_orbit(census, orbit_views, width=width, height=height, bounds=bounds or plan_bounds(ws))
+ else:
+ log.warning("no %s: the orbit rig is not rendered", census)
+ orbit_specs: list[dict[str, Any]] = list(fit.get("cameras") or [])
+ fit_ms = int((time.monotonic() - t0) * 1000)
+ # 2. pixels
+ pixel = _pixel_orbit(orbit_specs)
+ job_cams = [{"name": c.name, "kind": "authored", "position": _to_blender(c.position), "look_at": _to_blender(c.look_at),
+ "fov": c.fov, "no_fog": False, "times": times} for c in cameras or []]
+ job_cams += [{"name": o["name"], "kind": "orbit", "position": _to_blender(o["position"]),
+ "look_at": _to_blender(o["lookAt"]), "fov": o.get("fov") or 50.0, "no_fog": bool(o.get("noFog")),
+ "times": times[:1]} for o in orbit_specs if o["name"] in pixel]
+ job = {"out": str(out_dir), "result": str(out_dir / RESULT_NAME), "engine": engine or s.render.blender_engine,
+ "samples": int(samples or s.render.blender_samples), "width": width, "height": height, "times": times,
+ "authored": cameras is None, "cameras": job_cams}
+ t0 = time.monotonic()
+ frames = render_frames(blend, out_dir, job, timeout_s=tmo, settings=s)
+ blender_ms = int((time.monotonic() - t0) * 1000)
+ views = [_glb_view(f) for f in frames.get("frames") or []]
+ write_json_atomic(out_dir / EXTERNAL_NAME, views)
+ # 3. geometry: every camera the scene has (authored as Blender saw them) + the whole rig
+ specs = [{"name": c["name"], "kind": c.get("kind") or "authored", "position": _to_glb(c["position"]),
+ "lookAt": _to_glb(c["look_at"]), "fov": c.get("fov")}
+ for c in frames.get("cameras") or [] if c.get("kind") == "authored"]
+ 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)
+ 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
+ # 4. merge the Blender facts; one schema downstream
+ errors = [f"blender: {e}" for e in frames.get("errors") or []]
+ if geometry_error:
+ errors.append(geometry_error)
+ metrics["console_errors"] = list(metrics.get("console_errors") or []) + [e for e in errors
+ if e not in (metrics.get("console_errors") or [])]
+ metrics["ok"] = bool(metrics.get("ok", True)) and not errors and bool(views)
+ metrics["language"] = LANGUAGE
+ metrics["renderer"] = _renderer_line(frames)
+ if fit.get("framing_bbox") is not None:
+ metrics["framing_bbox"] = fit["framing_bbox"]
+ warnings = list(metrics.get("host_warnings") or [])
+ if frames.get("engine") in ("eevee", "workbench") and "llvmpipe" in str(frames.get("gl_renderer") or "").lower():
+ warnings.append(f"{frames['engine']} rendered on llvmpipe (software GL): {frames.get('gl_renderer')}")
+ if frames.get("fallback"):
+ warnings.append(f"rendered on the CPU: {frames['fallback']}")
+ metrics["host_warnings"] = warnings
+ metrics["blender"] = {
+ "engine": frames.get("engine"), "device": frames.get("device"), "device_names": frames.get("device_names") or [],
+ "samples": frames.get("samples"), "fallback": frames.get("fallback") or "", "version": frames.get("blender"),
+ "gl_renderer": frames.get("gl_renderer") or "", "n_frames": len(views),
+ "frame_ms": [v["render_ms"] for v in views],
+ "timings_ms": {"fit": fit_ms, "slot_wait": frames.get("slot_wait_ms", 0), "blender": blender_ms,
+ "blender_setup": frames.get("setup_ms", 0), "geometry": geometry_ms,
+ "total": int((time.monotonic() - t_all) * 1000)},
+ }
+ metrics["duration_ms"] = metrics["blender"]["timings_ms"]["total"]
+ write_json_atomic(out_dir / "metrics.json", metrics)
+ write_json_atomic(out_dir / "views.json", metrics["views"])
+ for w in warnings:
+ log.warning("render_blender_scene: %s", w)
+ return render_set_from_metrics(out_dir, metrics, width=width, height=height, orbit_views=orbit_views, sheet=sheet,
+ duration_ms=metrics["duration_ms"])
+
+
+def _glb_view(f: dict[str, Any]) -> dict[str, Any]:
+ """A Blender frame record → a render_scene.mjs view entry (GLB frame)."""
+ v = {"name": f["name"], "kind": f.get("kind") or "authored", "path": f["path"], "time_s": f["time_s"],
+ "position": _to_glb(f["position"]), "lookAt": _to_glb(f["look_at"]), "fov": f.get("fov"),
+ "render_ms": f.get("render_ms")}
+ return {k: v[k] for k in _VIEW_KEYS}
+
+
+def _renderer_line(frames: dict[str, Any]) -> str:
+ bits = [f"Blender {frames.get('blender', '?')}", str(frames.get("engine", "?")), str(frames.get("device", "?"))]
+ if frames.get("device_names"):
+ bits.append("/".join(frames["device_names"]))
+ if frames.get("samples"):
+ bits.append(f"{frames['samples']} spp")
+ if frames.get("gl_renderer"):
+ bits.append(str(frames["gl_renderer"]))
+ return " · ".join(bits)
+
+
+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]:
+ """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,
+ "--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)),
+ "--no-settle", "--no-post", "--external-frames", str(out_dir / EXTERNAL_NAME)]
+ try:
+ run_scene_script("render_scene.mjs", args, timeout_s=timeout_s + 30)
+ except SceneRenderError as e:
+ metrics = read_json_or_none(out_dir / "metrics.json") or {}
+ return metrics, f"geometry pass: {str(e).splitlines()[0][:400]}"
+ return read_json_or_none(out_dir / "metrics.json") or {}, ""
+
+
+def _empty(out_dir: Path, error: str, *, width: int, height: int, orbit_views: Sequence[ViewPreset]) -> RenderSet:
+ metrics = {"ok": False, "language": LANGUAGE, "renderer": "", "views": [], "camera_checks": [], "fps": None,
+ "census": None, "shader_errors": [], "console_errors": [error]}
+ write_json_atomic(out_dir / "metrics.json", metrics)
+ write_json_atomic(out_dir / "views.json", [])
+ return render_set_from_metrics(out_dir, metrics, width=width, height=height, orbit_views=orbit_views)
diff --git a/harness/codeverse3d/spatial/render_scene.py b/harness/codeverse3d/spatial/render_scene.py
index 1b8a62c9..6b18e3a8 100644
--- a/harness/codeverse3d/spatial/render_scene.py
+++ b/harness/codeverse3d/spatial/render_scene.py
@@ -227,6 +227,22 @@ def render_scene(
metrics = read_json_or_none(out_dir / "metrics.json") or {}
for w in metrics.get("host_warnings") or []: # e.g. a post chain that could not be built: judged RAW
log.warning("render_scene host warning: %s", w)
+ extra = [driver_error] if driver_error else []
+ if not metrics and res.summary.get("error"):
+ extra.append(str(res.summary["error"]))
+ return render_set_from_metrics(out_dir, metrics, width=width, height=height, orbit_views=orbit_views, sheet=sheet,
+ duration_ms=res.duration_ms, renderer=str(res.summary.get("renderer") or ""),
+ extra_errors=extra)
+
+
+def render_set_from_metrics(out_dir: Path, metrics: dict[str, Any], *, width: int, height: int,
+ orbit_views: Sequence[ViewPreset] = SCENE_VIEWS, sheet: bool = True, duration_ms: int = 0,
+ renderer: str = "", extra_errors: Sequence[str] = ()) -> RenderSet:
+ """A scene driver's ``metrics.json`` payload → the RenderSet every scene language returns:
+ motion measured and persisted, the views, the console / shader / driver errors, the judge
+ subset stamped once (``select_judge_views``) into the views and ``views.json``, the contact
+ sheet. ``render_scene`` (three.js pixels) and ``render_blender.render_blender_scene``
+ (Blender pixels) both end here, so the two languages cannot drift apart downstream."""
_store_motion(out_dir, metrics)
views: list[RenderView] = []
for v in metrics.get("views", []):
@@ -239,13 +255,12 @@ def render_scene(
errors = list(metrics.get("console_errors", []))
for e in metrics.get("shader_errors", []):
errors.append(f"shader[{e.get('stage')}]: {e.get('message')} — {e.get('source_line', '')}".strip())
- if driver_error and driver_error not in errors:
- errors.append(driver_error)
- if not metrics and res.summary.get("error"):
- errors.append(str(res.summary["error"]))
+ for e in extra_errors:
+ if e and e not in errors:
+ errors.append(e)
rs = RenderSet(
- views=views, renderer=str(metrics.get("renderer") or res.summary.get("renderer") or ""),
- duration_ms=res.duration_ms, console_errors=errors, fps=float(fps) if fps is not None else None,
+ views=views, renderer=str(metrics.get("renderer") or renderer or ""),
+ duration_ms=duration_ms, console_errors=errors, fps=float(fps) if fps is not None else None,
out_dir=str(out_dir),
)
# stamp the judge subset ONCE (select_judge_views stays a pure function)
diff --git a/harness/codeverse3d/spatial/scene_placement.py b/harness/codeverse3d/spatial/scene_placement.py
index d81a757a..44745957 100644
--- a/harness/codeverse3d/spatial/scene_placement.py
+++ b/harness/codeverse3d/spatial/scene_placement.py
@@ -179,6 +179,48 @@ def is_interior(plan: Any) -> bool:
return bool(flag) or infer_indoor(setting_text(plan))
+#: the fix hints / messages that name a language's API, per scene language (``census["language"]``;
+#: a census without one is three.js, as every recorded round is). The checks and their numbers
+#: are the same for every language; only the words that tell the author what to type differ.
+LANGUAGE_WORDS: dict[str, dict[str, str]] = {
+ "scene_threejs": {
+ "seat": "seat it with heightAt(x, z) or on the surface it stands on",
+ "free": "{name}.userData.placement = 'free'",
+ "no_fog_msg": "scene.fog is not set — frames read as thin_atmosphere (32/48 measured runs)",
+ "no_fog": "in buildEnv set scene.fog = new THREE.Fog(<sky horizon hex>, near, far) with the plan's numbers",
+ "no_background_msg": "scene.background is not set (renders on the raw clear colour)",
+ "no_background": "in buildEnv set scene.background to the sky colour or sky texture the plan names",
+ "fog_far": ("fog far >= {need:.0f} m ({spans:g} x the plan span; the starter's shell fog is scaled to it: keep "
+ "`scene.fog = shell.fog`, or lengthen yours) and let the horizon ridge / outskirts close the world"),
+ "underdressed": ("the layout's dressing counts are binding: add the missing props and the instanced ground cover "
+ "(tufts/pebbles count via InstancedMesh.count)"),
+ "ring": ("vary them — at least 3 silhouettes, scale 0.6-1.6x, radius +-25 %, random yaw, clusters rather than a "
+ "ring — or drop the ring and let the starter's worldShell ridge and makeOutskirts hills close the horizon"),
+ "place": "import its builder / clone its GLB",
+ },
+ "scene_blender": {
+ "seat": "seat it with ctx.height_at(x, y) or on the surface it stands on",
+ "free": '{name}["placement"] = "free"',
+ "no_fog_msg": "the scene has no atmosphere: no world Volume, bounded fog volume or mist — frames read as thin_atmosphere",
+ "no_fog": ("in build_env link a Volume Scatter / Principled Volume to the World Output's Volume (density "
+ "0.002-0.02, tinted like the sky horizon) or place a bounded fog volume over the play area"),
+ "no_background_msg": "the world has no sky: no Sky Texture or Background colour on the world output",
+ "no_background": "in build_env give scene.world a Sky Texture (or the plan's sky colour on its Background node)",
+ "fog_far": ("thin the fog so 1/density >= {need:.0f} m ({spans:g} x the plan span) and let the horizon ridge / "
+ "outskirts close the world"),
+ "underdressed": ("the layout's dressing counts are binding: add the missing props and the instanced ground cover "
+ "(every collection instance / geometry-nodes instance counts)"),
+ "ring": ("vary them — at least 3 silhouettes, scale 0.6-1.6x, radius +-25 %, random yaw, clusters rather than a "
+ "ring — or drop the ring and close the horizon with terrain ridges and hills"),
+ "place": "place a collection-instance Empty of ctx.assets['<snake>']",
+ },
+}
+
+
+def placement_words(language: str | None) -> dict[str, str]:
+ return LANGUAGE_WORDS.get(str(language or "scene_threejs"), LANGUAGE_WORDS["scene_threejs"])
+
+
def _f(sev: Severity, msg: str, *, target: str, hint: str = "", kind: str, **data: Any) -> GateFinding:
return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data={"kind": kind, **data})
@@ -206,7 +248,8 @@ def _sunk_severity(row: AssetRow) -> Severity | None:
return Severity.WARN if row.sunk_m > SUNK_M else None
-def _asset_findings(rows: list[AssetRow], *, floating_m: float, ground_y: float | None) -> list[GateFinding]:
+def _asset_findings(rows: list[AssetRow], *, floating_m: float, ground_y: float | None,
+ words: dict[str, str]) -> list[GateFinding]:
out: list[GateFinding] = []
floating: list[tuple[AssetRow, float]] = []
for row in rows:
@@ -228,7 +271,7 @@ def _asset_findings(rows: list[AssetRow], *, floating_m: float, ground_y: float
else:
out.append(_f(Severity.WARN, f"{q} is unsupported: hovers {gap:.2f} m above {support} and touches nothing", target=q,
hint=f"lower {q} by {gap:.2f} m onto {support}, or attach it to a neighbour; "
- f"if it is meant to hang free set {row.name}.userData.placement = 'free'",
+ f"if it is meant to hang free set {words['free'].format(name=row.name)}",
kind="unsupported", gap_m=gap, zone=row.zone))
many = len(floating) > FLOATING_ERROR_COUNT
for row, gap in floating:
@@ -236,8 +279,8 @@ def _asset_findings(rows: list[AssetRow], *, floating_m: float, ground_y: float
support = _support_label(row, ground_y)
sev = Severity.ERROR if (many or gap > FLOATING_ERROR_M) else Severity.WARN
out.append(_f(sev, f"{q} is floating {gap:.2f} m above {support} (touches nothing)", target=q,
- hint=f"lower {q} by {gap:.2f} m onto {support} — seat it with heightAt(x, z) or on the surface it stands on; "
- f"a deliberately airborne thing gets {row.name}.userData.placement = 'free'",
+ hint=f"lower {q} by {gap:.2f} m onto {support} — {words['seat']}; "
+ f"a deliberately airborne thing gets {words['free'].format(name=row.name)}",
kind="floating", gap_m=gap, zone=row.zone))
return out
@@ -280,7 +323,8 @@ def _cap_per_kind(findings: list[GateFinding]) -> list[GateFinding]:
return out
-def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool = False) -> GateReport:
+def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool = False,
+ language: str | None = None) -> GateReport:
"""The ``scene_placement`` GateReport for one census placement table (pure)."""
t = table if isinstance(table, PlacementTable) else PlacementTable.model_validate(table or {})
if t.error:
@@ -289,7 +333,8 @@ def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool =
hint="harness instrumentation, not your code; the placement check was skipped this round")])
floating_m = FLOATING_INDOOR_M if indoor else FLOATING_OUTDOOR_M
rows = [r for r in t.assets if not r.exempt]
- findings = _cap_per_kind(_asset_findings(rows, floating_m=floating_m, ground_y=t.ground_y) + _pair_findings(t.interpenetrations))
+ findings = _cap_per_kind(_asset_findings(rows, floating_m=floating_m, ground_y=t.ground_y, words=placement_words(language))
+ + _pair_findings(t.interpenetrations))
counts = {k: sum(1 for f in findings if f.data.get("kind") == k and f.severity != Severity.INFO)
for k in ("floating", "sunken", "unsupported", "interpenetration")}
n_exempt = sum(t.exempt.values())
@@ -415,6 +460,7 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
"clone its GLB"."""
if not isinstance(census, dict) or plan is None:
return []
+ words = placement_words(census.get("language"))
out: list[GateFinding] = []
# -- density: the layout's counts are binding, and the census counts every instance
groups = {to_snake(g.get("name", "")): g for g in (census.get("groups") or [])
@@ -432,17 +478,13 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
f"zone {zone_name} holds ~{have} instances but its layout budgeted {budget} "
f"(placements + mid/small props + ground cover)",
target=zone_name, kind="underdressed", have=have, budget=budget,
- hint="the layout's dressing counts are binding: add the missing props and the "
- "instanced ground cover (tufts/pebbles count via InstancedMesh.count)"))
+ hint=words["underdressed"]))
# -- atmosphere: the two env facts the census measures on every boot
if "fog" in census and census.get("fog") is None:
- out.append(_f(Severity.ERROR, "scene.fog is not set — frames read as thin_atmosphere (32/48 measured runs)",
- target="env", kind="no_fog",
- hint="in buildEnv set scene.fog = new THREE.Fog(<sky horizon hex>, near, far) with the plan's numbers"))
+ out.append(_f(Severity.ERROR, words["no_fog_msg"], target="env", kind="no_fog", hint=words["no_fog"]))
if "background" in census and census.get("background") is None:
- out.append(_f(Severity.ERROR, "scene.background is not set (renders on the raw clear colour)",
- target="env", kind="no_background",
- hint="in buildEnv set scene.background to the sky colour or sky texture the plan names"))
+ out.append(_f(Severity.ERROR, words["no_background_msg"], target="env", kind="no_background",
+ hint=words["no_background"]))
# -- fog that ends inside the world: measured 2026-09-08 over eleven exterior runs, every
# one with fog far >= 2 x the plan span scored >= 0.60 and the three at 1.4-1.6 x scored
# 0.42-0.60 with "no aerial perspective", "world edge", "backdrop floating in the sky" —
@@ -461,9 +503,7 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
out.append(_f(Severity.WARN, short + " — past it the land is the background colour while the unfogged sky "
"stays sharp: a world edge and backdrops floating in the sky",
target="env", kind="fog_short", fog=fog, plan_span_m=round(span, 1),
- hint=f"fog far >= {FOG_FAR_MIN_SPANS * span:.0f} m ({FOG_FAR_MIN_SPANS:g} x the plan span; the starter's "
- "shell fog is scaled to it: keep `scene.fog = shell.fog`, or lengthen yours) and let the horizon "
- "ridge / outskirts close the world"))
+ hint=words["fog_far"].format(need=FOG_FAR_MIN_SPANS * span, spans=FOG_FAR_MIN_SPANS)))
# -- a stamped ring: >= 8 same-size copies evenly on a circle round the world's edge.
# Five of six exteriors on 2026-09-09 drew their horizon as "a ring of identical cones
# stamped round the perimeter" / "rocks in a perfect circle" and the judge called each a
@@ -487,9 +527,7 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
f"(radius spread {rcv:.0%}, spacing spread {gcv:.0%}, size spread {scv:.0%}) — a toy backdrop",
target=str(g.get("name", "overall")), kind="stamped_ring", n=n, radius_m=r,
radius_cv=rcv, gap_cv=gcv, size_cv=scv,
- hint="vary them — at least 3 silhouettes, scale 0.6-1.6x, radius +-25 %, random yaw, "
- "clusters rather than a ring — or drop the ring and let the starter's worldShell "
- "ridge and makeOutskirts hills close the horizon"))
+ hint=words["ring"]))
# -- backdrop ring: outdoor worlds must have geometry past the play area
groups = census.get("groups")
if bounds and isinstance(groups, list) and not is_interior(plan):
@@ -543,7 +581,7 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
f"zone {zone_name} is missing planned contents: {', '.join(missing[:5])}"
+ (f" (+{len(missing) - 5} more)" if len(missing) > 5 else ""),
target=zone_name, kind="missing_content", missing=missing[:8],
- hint="place each listed asset (import its builder / clone its GLB) inside this "
+ hint=f"place each listed asset ({words['place']}) inside this "
"zone's bbox AND give the object the plan's name for it — every gate and the "
"judge find it by that name, so a lantern called 'LanternPost1' reads as absent"))
# -- plausible scale vs the plan's approx_size_m
@@ -643,7 +681,7 @@ def placement_gate_safe(census: dict[str, Any] | None, *, plan: Any = None,
table = (census or {}).get("placement")
if not isinstance(table, dict):
return None
- report = placement_findings(table, indoor=is_interior(plan))
+ report = placement_findings(table, indoor=is_interior(plan), language=(census or {}).get("language"))
extra = _cap_per_kind(contract_findings(census, plan, layouts=layouts, unavailable=unavailable))
if extra:
report = GateReport.of(GATE, report.findings + extra, duration_ms=report.duration_ms)
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 72b0e6b8..aae2d1ea 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -126,11 +126,14 @@ codeverse3d/
data (starter/, opengl_python/wrappers/run_gl.py; the contract text is
prompts/<lang>/contract.md, found like every per-language prompt file by
prompts/catalog.language_prompt — a runtime holds no prompt text); wrappers/
- holds the python build wrappers (run_bpy, run_bpy_links, run_cq, run_bpy_scene) and what they
+ holds the python build wrappers (run_bpy, run_bpy_links, run_cq, run_bpy_scene), the
+ scene_blender render driver (render_bpy_scene) and what they
share (_wrapper_common: script run + error mapping + report; _census: the Blender census;
_census_glb: scene_blender's census GLB writer, D102)
spatial/ node.py, render.py, observe.py, tool_common.py (shared tool plumbing),
render_scene.py (judge view subset, content-fitted orbit),
+ render_blender.py (scene_blender: Blender pixels under a GPU slot + CPU fallback,
+ the JS host's camera checks on them, the same metrics.json),
frame_metrics.py (scene_frames gate), frame_motion.py (measured inter-frame motion),
scene_placement.py (scene_placement gate = the check_placement tool's verdict,
placement_gate(ws, census, plan) for both: floating / sunken /
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.md
index 09d9ebf9..d56753b7 100644
--- a/harness/docs/INSTALL.md
+++ b/harness/docs/INSTALL.md
@@ -472,6 +472,10 @@ that the keys work end to end):
| `python deps` | FAIL | a core import is missing/broken | `pip install -e 'harness[all]'`; a broken native lib (`fcl`, `manifold3d`) shows up here too — reinstall that wheel (`pip install --force-reinstall python-fcl`) |
| `python deps` | WARN | only optional-extra modules missing (`manifold3d` / `shapely` / `yourdfpy` / `mcp` / `moderngl` / `cadquery`) | install the extra the row names, e.g. `pip install -e 'harness[mesh,urdf,mcp,graphics,cad]'` (§4) |
| `blender` | FAIL | no binary found, or `--version` failed | §6 — install Blender, or `export C3D_BINARIES__BLENDER=/path/to/blender`. If it is found but fails, run it by hand: a `libSM.so.6`/`libICE.so.6` error means you need the `LD_LIBRARY_PATH` wrapper |
+| `blender cycles` | WARN | Cycles sees no CUDA device | scene_blender's judged frames render on the CPU (~3.3x slower, measured) — fine without an NVIDIA GPU; on WSL2 install the vendor WSL GPU driver. The row also names the judged-frame engine / samples / device (`C3D_RENDER__BLENDER_*`) |
+| `blender eevee` | WARN / FAIL | the EEVEE smoke frame ran on llvmpipe (software GL), or did not render | only matters with `C3D_RENDER__BLENDER_ENGINE=eevee`: the harness runs EEVEE under the Mesa d3d12 env (`spatial/gl_render.GPU_ENV`); llvmpipe here means that env found no GPU. `--no-gpu` skips the smoke frame |
+| `blender render` | FAIL / SKIP | the render probe could not run Blender (or there is none) | see the `blender` row |
+| `blender gpu slots` | WARN | every machine-wide GPU Blender render slot is held right now | other renders are on the GPU; a render waits `C3D_RENDER__BLENDER_GPU_WAIT_S` for a slot and then renders on the CPU — nothing to fix unless it stays full. `C3D_RENDER__BLENDER_GPU_SLOTS` sizes it |
| `node` | FAIL | node missing or older than 20.6.0 (§2.1) | install a newer node (`nvm install --lts`) or point `binaries.node` / `C3D_BINARIES__NODE` at one. The same check fires from every node workload (`codeverse3d.spatial.node.run_node`), so a too-old node cannot fail obscurely mid-render |
| `runtime_js` | FAIL | the node runtime directory cannot be resolved | use a full checkout, or set `C3D_RUNTIME_JS=/path/to/harness/runtime_js`; then run `npm ci` there (§5) |
| `three` | FAIL | `runtime_js/node_modules/three` missing | `cd harness/runtime_js && npm ci` (§5) |
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index ee76ee4f..d1aca0a5 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -329,6 +329,14 @@ render_scene(ws, out_dir, *, cameras=None, orbit=True, times=(0.0, 1.5), width=1
bounds=None) -> RenderSet
# Δ bounds default from ws plan.json → orbit rig frustum-fits the CONTENT box (not ground/sky);
# contact sheet = judge subset only; views.json entries get judge: true|false
+from codeverse3d.spatial.render_scene import render_set_from_metrics # metrics.json payload → RenderSet (both scene languages)
+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,
+ # 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
from codeverse3d.spatial.frame_metrics import frame_gate_from_renders, frame_findings, frame_summary_text, FRAME_GATE
diff --git a/harness/runtime_js/fit_orbit.mjs b/harness/runtime_js/fit_orbit.mjs
new file mode 100644
index 00000000..e4ae6e82
--- /dev/null
+++ b/harness/runtime_js/fit_orbit.mjs
@@ -0,0 +1,35 @@
+#!/usr/bin/env node
+/**
+ * Fit the overview orbit rig to a census WITHOUT a browser (scene_blender, D1): the same
+ * `framingBox` + `fitOrbitCameras` render_scene.mjs runs in-page, on the census the build's
+ * probe already wrote — one implementation of the fitting, so a Blender render frames its
+ * overviews exactly as the three.js driver would.
+ *
+ * node fit_orbit.mjs --census <census.json> --orbit-views '<json [{name,azimuth,elevation}]>'
+ * [--bounds '{"min":[x,y,z],"max":[x,y,z]}'|none] [--width 1024] [--height 576]
+ *
+ * Last stdout line: {ok, framing_bbox, cameras: [{name, position, lookAt, fov, kind:'orbit', noFog}]}
+ * (Y-up GLB frame). Exit 0 ok, 2 bad input.
+ */
+
+import fs from 'node:fs';
+import { fail, finish, parseCli, readJsonArg } from './lib/cli.mjs';
+import { fitOrbitCameras, framingBox } from './lib/orbit.mjs';
+
+const args = parseCli({
+ census: {}, 'orbit-views': { default: '[]' }, bounds: { default: 'none' },
+ width: { default: '1024' }, height: { default: '576' },
+});
+
+try {
+ if (!args.census) throw new Error('--census is required');
+ const census = JSON.parse(fs.readFileSync(args.census, 'utf8'));
+ const views = readJsonArg(args['orbit-views'], 'orbit-views') || [];
+ const bounds = args.bounds && args.bounds !== 'none' ? readJsonArg(args.bounds, 'bounds') : null;
+ const bbox = framingBox(census, bounds);
+ const aspect = parseInt(args.width, 10) / parseInt(args.height, 10);
+ const cameras = fitOrbitCameras(bbox, views, { aspect, groundY: census.ground_y });
+ finish({ ok: true, framing_bbox: bbox, cameras });
+} catch (e) {
+ fail(`fit_orbit failed: ${e.message}`);
+}
diff --git a/harness/runtime_js/lib/host_metrics.mjs b/harness/runtime_js/lib/host_metrics.mjs
index da80cb8f..89128786 100644
--- a/harness/runtime_js/lib/host_metrics.mjs
+++ b/harness/runtime_js/lib/host_metrics.mjs
@@ -51,6 +51,21 @@ export function frameStats(canvas) {
};
}
+/** The keys `frameStats` returns — what an external frame replaces in a camera check. */
+export const FRAME_STAT_KEYS = ['mean_lum', 'lum_std', 'dark_frac', 'blown_frac', 'modal_frac'];
+
+/**
+ * `frameStats` of an image another renderer wrote (scene_blender: the Blender PNG of a view,
+ * handed in as a data URL): the SAME sampling grid and the same statistics as a canvas frame,
+ * so both languages' metrics.json read through one implementation and one set of thresholds.
+ */
+export async function imageFrameStats(url) {
+ const img = new Image();
+ img.src = url;
+ await img.decode();
+ return frameStats(img);
+}
+
// six skewed directions, not the axes: a ray straight up from a round camera position hits the
// centre line of an axis-aligned ceiling, i.e. the diagonal both triangles share, twice
const PARITY_DIRS = [[1, 0.37, 0.23], [-1, 0.29, -0.41], [0.31, 1, 0.19], [-0.27, -1, 0.35], [0.23, 0.41, 1], [-0.39, 0.17, -1]];
diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjs
index e799803a..be402f53 100644
--- a/harness/runtime_js/lib/scene_host.mjs
+++ b/harness/runtime_js/lib/scene_host.mjs
@@ -18,7 +18,7 @@ import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { sceneCensus } from './host_census.mjs';
import { settleScene } from './host_placement.mjs';
-import { frameStats, nearGeometry, repairCameraSpec } from './host_metrics.mjs';
+import { FRAME_STAT_KEYS, frameStats, imageFrameStats, nearGeometry, repairCameraSpec } from './host_metrics.mjs';
import { frameCoverage, glbCoverage } from './host_coverage.mjs';
import { classifyBackdrop, nonSolid, drawableBox } from './backdrop.mjs';
import { installShaderErrorHook } from './host_shader_errors.mjs';
@@ -618,6 +618,18 @@ function cameraChecks(spec) {
return { name: spec.name, ...near, ...stats, ...coverage, glb_frac: glbFrac, hero_for: heroFor };
}
+/**
+ * `cameraChecks` for a view whose PIXELS another renderer made (scene_blender, D1): the
+ * geometry instruments (near geometry, coverage masks) still come from this scene, the
+ * luminance statistics from `dataUrl` — the other renderer's frame — and a camera with no
+ * external frame carries no luminance at all (this scene's own pixels are not the picture).
+ */
+async function externalCameraChecks(spec, dataUrl) {
+ const chk = cameraChecks(spec);
+ for (const k of FRAME_STAT_KEYS) delete chk[k];
+ return dataUrl ? { ...chk, ...(await imageFrameStats(dataUrl)) } : chk;
+}
+
/** Force-compile every material as seen from spec (or the first camera). */
function compileAll(spec) {
const cam = buildCamera(spec || state.cameras[0] || { position: [10, 10, 10], lookAt: [0, 0, 0], fov: 50 });
@@ -696,6 +708,7 @@ window.__c3v = {
boot,
renderAt,
cameraChecks,
+ externalCameraChecks,
cameraRepairs,
compileAll,
census,
diff --git a/harness/runtime_js/render_scene.mjs b/harness/runtime_js/render_scene.mjs
index 54f00886..a1f5fdbd 100644
--- a/harness/runtime_js/render_scene.mjs
+++ b/harness/runtime_js/render_scene.mjs
@@ -9,12 +9,20 @@
* [--times 0,1.5] [--width 1024] [--height 576] [--gpu auto|on|off]
* [--fps-seconds 2] [--timeout-ms 240000]
* [--no-post] [--post-options '{"ao":0.45,"bloomStrength":0.22}']
+ * [--scene src/scene.js] (the entry the host imports, workspace-relative)
+ * [--external-frames <views.json>] (scene_blender, D1: the PIXELS come from another
+ * renderer — a list of {name, kind, path, time_s, position, lookAt, fov, render_ms}
+ * whose PNGs are already in --out; needs explicit --cameras. This driver then renders
+ * nothing: camera checks (near geometry, coverage) run on the loaded scene, luminance
+ * statistics are frameStats of the external PNG, and views.json / metrics.json keep
+ * the one schema)
*
* Writes PNG per (camera, time), views.json, metrics.json
* {console_errors, shader_errors, fps, census, camera_checks, ...}.
* Last stdout line = JSON summary. Exit 0 ok, 1 scene failed, 2 driver error.
*/
+import fs from 'node:fs';
import path from 'node:path';
import { armWatchdog, dataUrlToPng, ensureDir, fail, finish, parseCli, readJsonArg, safeName, writeJson } from './lib/cli.mjs';
import { createTimeoutMs, errorSummary, openHost } from './lib/host_page.mjs';
@@ -32,6 +40,7 @@ const args = parseCli({
times: { default: '0,1.5' }, width: { default: '1024' }, height: { default: '576' },
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: '' },
});
function tag(t) {
@@ -45,12 +54,29 @@ function outFile(outDir, file) {
return p;
}
+/** The external views (`--external-frames`) whose PNG exists in outDir; null when not external. */
+function externalViews(outDir) {
+ if (!args['external-frames']) return null;
+ if (args.cameras === 'authored' || args.cameras === 'none') throw new Error('--external-frames needs explicit --cameras');
+ const list = JSON.parse(fs.readFileSync(args['external-frames'], 'utf8'));
+ if (!Array.isArray(list)) throw new Error('--external-frames must hold a JSON list of views');
+ return list.filter((v) => v && typeof v.path === 'string' && fs.existsSync(outFile(outDir, v.path)));
+}
+
+/** The camera's earliest external frame as a data URL (its luminance statistics), else null. */
+function externalFrameUrl(external, outDir, name) {
+ const mine = external.filter((v) => v.name === name).sort((a, b) => (a.time_s || 0) - (b.time_s || 0));
+ if (!mine.length) return null;
+ return 'data:image/png;base64,' + fs.readFileSync(outFile(outDir, mine[0].path)).toString('base64');
+}
+
async function main() {
if (!args.ws || !args.out) throw new Error('--ws and --out are required');
const width = parseInt(args.width, 10), height = parseInt(args.height, 10);
const times = String(args.times).split(',').map((s) => parseFloat(s)).filter((x) => Number.isFinite(x) && x >= 0).sort((a, b) => a - b);
if (!times.length) throw new Error('--times must list non-negative numbers');
const outDir = ensureDir(path.resolve(args.out));
+ const external = externalViews(outDir);
const timeoutMs = parseInt(args['timeout-ms'], 10);
const watchdog = armWatchdog(timeoutMs);
const t0 = Date.now();
@@ -58,7 +84,7 @@ async function main() {
let host;
try {
host = await openHost(args.ws, {
- width, height, gpu: args.gpu, logDepth: args['log-depth'],
+ width, height, gpu: args.gpu, logDepth: args['log-depth'], sceneRel: args.scene.replace(/^\.?\//, ''),
createSceneTimeoutMs: createTimeoutMs(timeoutMs),
settle: !args['no-settle'],
cameraRepair: !!args['camera-repair'],
@@ -105,12 +131,15 @@ async function main() {
// instruments per camera (at t=0, before any stepping)
for (const c of cams) {
try {
- const chk = await page.evaluate((spec) => window.__c3v.cameraChecks(spec), c);
+ const chk = external
+ ? await page.evaluate((spec, url) => window.__c3v.externalCameraChecks(spec, url), c, externalFrameUrl(external, outDir, c.name))
+ : await page.evaluate((spec) => window.__c3v.cameraChecks(spec), c);
metrics.camera_checks.push({ kind: c.kind, ...chk });
} catch (e) { sceneErr(`camera checks failed for '${c.name}'`, e); }
}
- // renders: times ascending (sim time cannot rewind)
- for (const t of times) {
+ // renders: times ascending (sim time cannot rewind); external pixels are views already
+ if (external) metrics.views.push(...external);
+ for (const t of external ? [] : times) {
for (const c of cams) {
try {
const r = await page.evaluate((spec, tt) => window.__c3v.renderAt(spec, tt), c, t);
diff --git a/harness/tests/core/test_doctor.py b/harness/tests/core/test_doctor.py
index 8d74e165..c348928d 100644
--- a/harness/tests/core/test_doctor.py
+++ b/harness/tests/core/test_doctor.py
@@ -33,3 +33,41 @@ def test_a_torn_package_json_is_a_failed_row_not_a_crash(tmp_path: Path, monkeyp
rows = {name: (status, detail) for name, status, detail in check_node()}
assert rows["three"][0] == "FAIL" and "unreadable" in rows["three"][1]
assert rows["puppeteer"][0] == "FAIL"
+
+
+def _fake_probe(monkeypatch, tmp_path: Path, payload: dict) -> list:
+ from codeverse3d import doctor
+ from codeverse3d.proc import ProcResult
+
+ seen: dict = {}
+
+ def run(cmd, **kw):
+ seen["cmd"], seen["env"] = cmd, kw.get("env") or {}
+ return ProcResult(0, "Blender 5.0.1\nC3D_DOCTOR " + json.dumps(payload) + "\nBlender quit\n", "", False, 5)
+
+ monkeypatch.setenv("C3D_CACHE_DIR", str(tmp_path))
+ monkeypatch.setattr(doctor, "run_subprocess", run)
+ rows = doctor.check_blender_render(eevee=True)
+ assert seen["env"].get("GALLIUM_DRIVER") == "d3d12", "EEVEE is probed under the d3d12 env it renders with"
+ return rows
+
+
+def test_doctor_reports_the_blender_render_capability(tmp_path: Path, monkeypatch):
+ rows = {r[0]: r for r in _fake_probe(monkeypatch, tmp_path, {"cuda": ["RTX"], "gl": "D3D12 (NVIDIA RTX)"})}
+ assert rows["blender cycles"][1] == "OK" and "CUDA: RTX" in rows["blender cycles"][2]
+ assert "cycles 32 spp" in rows["blender cycles"][2]
+ assert rows["blender eevee"][1] == "OK" and rows["blender gpu slots"][1] == "OK"
+ soft = {r[0]: r for r in _fake_probe(monkeypatch, tmp_path, {"cuda": [], "gl": "llvmpipe (LLVM 19.1.1, 256 bits)"})}
+ assert soft["blender cycles"][1] == "WARN" and "CPU" in soft["blender cycles"][2]
+ assert soft["blender eevee"][1] == "WARN" and "software GL" in soft["blender eevee"][2]
+
+
+def test_doctor_blender_render_probe_runs_for_real():
+ from codeverse3d.config import get_settings
+ from codeverse3d.doctor import check_blender_render
+
+ if not get_settings().resolve_blender():
+ pytest.skip("no Blender binary")
+ rows = {r[0]: r for r in check_blender_render(eevee=False)}
+ assert rows["blender cycles"][1] in ("OK", "WARN") and "blender eevee" not in rows
diff --git a/harness/tests/cost/test_profiles.py b/harness/tests/cost/test_profiles.py
index d5ff64a5..6e50192c 100644
--- a/harness/tests/cost/test_profiles.py
+++ b/harness/tests/cost/test_profiles.py
@@ -154,3 +154,17 @@ def test_each_profile_resolves_to_its_documented_dial(name, expected, monkeypatc
assert dial.profile == name
for field, want in expected.items():
assert getattr(dial, field) == want, f"{name}.{field}"
+
+
[email protected](("name", "spp"), [("economy", 16), ("balanced", 32), ("quality", 64)])
+def test_the_profile_sets_the_blender_samples_unless_the_user_stated_them(name, spp, monkeypatch):
+ """scene_blender's judged-frame samples are a profile dial (owner D1: economy 16 · 32 · quality 64)."""
+ s = Settings()
+ s.apply_profile(name)
+ assert s.render.blender_samples == spp
+ monkeypatch.setenv("C3D_RENDER__BLENDER_SAMPLES", "8")
+ stated = Settings()
+ stated.apply_profile(name)
+ assert stated.render.blender_samples == 8
+ stated.apply_profile(name, force=True)
+ assert stated.render.blender_samples == spp
diff --git a/harness/tests/scene_gates/test_frame_metrics.py b/harness/tests/scene_gates/test_frame_metrics.py
index a29086b0..71425baa 100644
--- a/harness/tests/scene_gates/test_frame_metrics.py
+++ b/harness/tests/scene_gates/test_frame_metrics.py
@@ -186,3 +186,47 @@ def test_auto_exposure_lifts_a_frame_past_the_gates_dark_line():
host = (runtime_js_dir() / "lib" / "scene_host.mjs").read_text()
lo = float(re.search(r"const EXPOSURE_BAND = \[([\d.]+),", host).group(1))
assert lo == DARK_MEAN_LUM
+
+
+def test_a_blender_payload_gets_bpy_fix_hints_and_three_js_keeps_its_own():
+ """The thresholds are one; the words are the language's (``metrics["language"]``)."""
+ from codeverse3d.spatial.frame_metrics import HINTS
+
+ dark = _chk("Establishing", mean_lum=0.04, lum_std=0.03, dark_frac=0.8)
+ low = _chk("Street", eye_height_m=0.1, ground_below_m=0.1, ground_below_name="Ground")
+ three = frame_findings(_metrics(dark, low))
+ bpy = frame_findings({**_metrics(dark, low), "language": "scene_blender"})
+ assert [(f.data["kind"], f.severity) for f in three.findings] == [(f.data["kind"], f.severity) for f in bpy.findings]
+ t_hints = {f.data["kind"]: f.fix_hint for f in three.findings}
+ b_hints = {f.data["kind"]: f.fix_hint for f in bpy.findings}
+ assert t_hints["dark_frame"] == HINTS["scene_threejs"]["dark"] and "sunRig" in t_hints["dark_frame"]
+ assert "sun.data.energy" in b_hints["dark_frame"] and "sunRig" not in b_hints["dark_frame"]
+ assert "heightAt" in t_hints["camera_low"] and "ctx.height_at" in b_hints["camera_low"]
+ assert set(HINTS["scene_blender"]) == set(HINTS["scene_threejs"]), "every hint has a bpy wording"
+
+
+def test_a_slow_blender_frame_set_warns_and_names_the_heaviest_zone():
+ """Owner D2: offline rendering has no draw budget; seconds per judged frame is its cost."""
+ from codeverse3d.spatial.frame_metrics import SLOW_FRAME_CPU_FACTOR, SLOW_FRAME_S
+
+ def payload(ms: float, device: str = "GPU") -> dict:
+ views = [{"name": "A", "kind": "authored", "path": "a.png", "time_s": t, "position": [0, 1, 5],
+ "lookAt": [0, 0, 0], "fov": 50, "render_ms": ms} for t in (0.0, 1.5)]
+ groups = [{"name": "Market", "kind": "content", "triangles": 900_000},
+ {"name": "Harbour", "kind": "content", "triangles": 120_000},
+ {"name": "Ground", "kind": "ground", "triangles": 5_000_000}]
+ return {**_metrics(_chk("A")), "views": views, "census": {"ground_y": 0.0, "groups": groups},
+ "language": "scene_blender", "blender": {"engine": "cycles", "samples": 32, "device": device}}
+
+ slow = [f for f in frame_findings(payload(SLOW_FRAME_S * 1000 + 500)).findings if f.data.get("kind") == "slow_frame"]
+ assert len(slow) == 1 and slow[0].severity == Severity.WARN and slow[0].target == "Market"
+ assert "Market" in slow[0].message and "900,000" in slow[0].message
+ assert not [f for f in frame_findings(payload(SLOW_FRAME_S * 1000 - 500)).findings if f.data.get("kind") == "slow_frame"]
+ # the CPU fallback is ~3.3x slower by construction: the same frame there is not the scene's fault
+ cpu = payload(SLOW_FRAME_S * 1000 + 500, device="CPU")
+ assert not [f for f in frame_findings(cpu).findings if f.data.get("kind") == "slow_frame"]
+ assert [f for f in frame_findings(payload(SLOW_FRAME_S * SLOW_FRAME_CPU_FACTOR * 1000 + 500, "CPU")).findings
+ if f.data.get("kind") == "slow_frame"]
+ # a three.js payload (no blender block) never reads render_ms
+ three = {k: v for k, v in payload(60_000).items() if k not in ("blender", "language")}
+ assert not [f for f in frame_findings(three).findings if f.data.get("kind") == "slow_frame"]
diff --git a/harness/tests/scene_gates/test_placement.py b/harness/tests/scene_gates/test_placement.py
index 91f1fb02..45b2e459 100644
--- a/harness/tests/scene_gates/test_placement.py
+++ b/harness/tests/scene_gates/test_placement.py
@@ -308,3 +308,18 @@ def test_a_ring_of_identical_copies_round_the_world_is_warned_but_not_a_rotunda(
assert not [f for f in placement_gate_safe(census, plan=plan).findings if f.data.get("kind") == "stamped_ring"]
census["groups"][0]["stamps"] = [dict(ring, name="Column", n=12, radius_m=4.0)] # a rotunda: inside the content
assert not [f for f in placement_gate_safe(census, plan=plan).findings if f.data.get("kind") == "stamped_ring"]
+
+
+def test_blender_census_gets_bpy_words_in_placement_hints():
+ """Same checks, same numbers; a scene_blender census (``census["language"]``) is told what to type in bpy."""
+ t = _table(_row("Lantern", gap=0.3))
+ three = placement_findings(t)
+ bpy = placement_findings(t, language="scene_blender")
+ f3, fb = _by_kind(three, "floating")[0], _by_kind(bpy, "floating")[0]
+ assert f3.severity == fb.severity and f3.message == fb.message
+ assert "userData.placement" in f3.fix_hint and "heightAt" in f3.fix_hint
+ assert 'Lantern["placement"] = "free"' in fb.fix_hint and "ctx.height_at" in fb.fix_hint
+ census = {"placement": t, "fog": None, "background": None, "language": "scene_blender"}
+ gate = placement_gate_safe(census, plan={"title": "t", "setting": "outdoor", "zones": []})
+ no_fog = next(f for f in gate.findings if f.data.get("kind") == "no_fog")
+ assert "Volume" in no_fog.fix_hint and "THREE.Fog" not in no_fog.fix_hint
diff --git a/harness/tests/scene_runtime/blender_scene_fixture.py b/harness/tests/scene_runtime/blender_scene_fixture.py
new file mode 100644
index 00000000..932dbece
--- /dev/null
+++ b/harness/tests/scene_runtime/blender_scene_fixture.py
@@ -0,0 +1,117 @@
+"""A small built ``scene_blender``-shaped workspace for the Blender render tests (lane B).
+
+Until the language's build wrapper exists this stands in for its outputs: ``artifacts/scene.blend``
+(ground, a tower, a sphere that moves between t = 0 and t = 1.5 — or does not — a sun, two
+authored cameras with ``c3d_look_at`` and ``scene["c3d_cameras"]``), the geometry as a GLB, a
+host entry that loads it (the shape of the census-GLB adapter), and ``artifacts/census.json``
+from the unchanged probe. Blender frame: Z-up, -Y front; the GLB and every spec are Y-up.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse3d.config import get_settings
+from codeverse3d.languages.blender import blender_env
+from codeverse3d.proc import run_subprocess
+from codeverse3d.workspace import Workspace
+
+BUILD_BPY = r'''
+import sys
+import bpy
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+blend, glb, moving = argv[0], argv[1], argv[2] == "1"
+bpy.ops.wm.read_factory_settings(use_empty=True)
+sc = bpy.context.scene
+sc.render.fps = 30
+sc.frame_start, sc.frame_end = 1, 46
+
+
+def mat(name, rgb):
+ m = bpy.data.materials.new(name)
+ m.use_nodes = True
+ m.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (*rgb, 1.0)
+ return m
+
+
+bpy.ops.mesh.primitive_plane_add(size=40)
+g = bpy.context.object
+g.name = "Ground"
+g.data.materials.append(mat("GroundMat", (0.35, 0.33, 0.3)))
+bpy.ops.mesh.primitive_cube_add(size=2, location=(0, 0, 1))
+t = bpy.context.object
+t.name = "Tower"
+t.data.materials.append(mat("TowerMat", (0.8, 0.2, 0.1)))
+bpy.ops.mesh.primitive_uv_sphere_add(radius=1, location=(-4, 0, 1))
+s = bpy.context.object
+s.name = "Mover"
+s.data.materials.append(mat("MoverMat", (0.1, 0.3, 0.9)))
+if moving:
+ s.location.x = -4
+ s.keyframe_insert("location", frame=1)
+ s.location.x = 4
+ s.keyframe_insert("location", frame=46)
+sun = bpy.data.objects.new("Sun", bpy.data.lights.new("Sun", "SUN"))
+sun.data.energy = 4.0
+sun.rotation_euler = (0.7, 0.2, 0.5)
+sc.collection.objects.link(sun)
+w = bpy.data.worlds.new("World")
+w.use_nodes = True
+w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.4, 0.55, 0.8, 1.0)
+w.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.8
+sc.world = w
+for name, pos in (("Front", (0, -14, 4)), ("Side", (14, 0, 4))):
+ cam = bpy.data.objects.new(name, bpy.data.cameras.new(name))
+ cam.data.sensor_fit = "VERTICAL"
+ cam.data.angle_y = 0.7
+ cam.location = pos
+ cam["c3d_look_at"] = [0.0, 0.0, 1.0]
+ from mathutils import Vector
+ cam.rotation_euler = (Vector((0, 0, 1)) - Vector(pos)).to_track_quat("-Z", "Y").to_euler()
+ sc.collection.objects.link(cam)
+sc["c3d_cameras"] = ["Front", "Side"]
+sc.camera = bpy.data.objects["Front"]
+bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", export_cameras=False, export_lights=False,
+ export_animations=False)
+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 };
+}
+"""
+
+
+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)."""
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ script = ws.root / "build_fixture.py"
+ script.write_text(BUILD_BPY)
+ glb = ws.root / "public" / "assets" / "scene.glb"
+ glb.parent.mkdir(parents=True, exist_ok=True)
+ blend = ws.artifacts / "scene.blend"
+ blender = get_settings().resolve_blender()
+ 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)
+ if probe:
+ from codeverse3d.spatial.probes import probe_scene
+
+ res = probe_scene(ws, timeout_s=90)
+ assert res.census, res.errors
+ return ws
+
+
+def blender_available() -> bool:
+ b = get_settings().resolve_blender()
+ return bool(b) and Path(b).exists()
diff --git a/harness/tests/scene_runtime/test_render_blender.py b/harness/tests/scene_runtime/test_render_blender.py
new file mode 100644
index 00000000..53779e0d
--- /dev/null
+++ b/harness/tests/scene_runtime/test_render_blender.py
@@ -0,0 +1,283 @@
+"""scene_blender rendering (lane B, D1/D3/D8): Blender makes the pixels, the JS host measures them.
+
+Real Blender + headless Chrome on a small fixture scene (``blender_scene_fixture``), rendered at
+192x108 with 4 Cycles samples on the CPU (the GPU is shared on this box) — plus pure-python tests
+of the GPU-slot policy with a fake driver.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from codeverse3d.config import get_settings
+from codeverse3d.contracts.artifacts import Severity
+from codeverse3d.conventions import from_authoring_frame, to_authoring_frame
+from codeverse3d.proc import ProcResult, read_json_or_none
+from codeverse3d.spatial import render_blender as rb
+from codeverse3d.spatial.frame_metrics import frame_findings
+from codeverse3d.spatial.render_scene import SceneRenderError, render_scene
+from codeverse3d.workspace import Workspace
+from tests.scene_runtime.blender_scene_fixture import blender_available, build_fixture
+from tests.scene_runtime.conftest import needs_browser
+
+needs_blender = pytest.mark.skipif(not blender_available(), reason="Blender binary required")
+W, H = 192, 108
+STAT_KEYS = {"mean_lum", "lum_std", "dark_frac", "blown_frac", "modal_frac"}
+
+
+def _cpu_env(mp: pytest.MonkeyPatch, cache: Path) -> None:
+ mp.setenv("C3D_RENDER__BLENDER_DEVICE", "cpu")
+ mp.setenv("C3D_CACHE_DIR", str(cache))
+ get_settings.cache_clear()
+
+
[email protected](scope="module")
+def moving(tmp_path_factory):
+ """The moving fixture, rendered once: 2 authored cameras x (0, 1.5) + the orbit rig."""
+ root = tmp_path_factory.mktemp("sb_moving")
+ with pytest.MonkeyPatch.context() as mp:
+ _cpu_env(mp, root / "cache")
+ ws = build_fixture(Workspace(root / "run").create(), moving=True)
+ rs = rb.render_blender_scene(ws, root / "renders", width=W, height=H, samples=4)
+ get_settings.cache_clear()
+ return ws, rs, json.loads((root / "renders" / "metrics.json").read_text())
+
+
[email protected]("v", [(1.0, 2.0, 3.0), (-4.5, 0.25, 7.0)])
+def test_the_frame_round_trip_is_the_identity(v):
+ z_up = to_authoring_frame(v, "blender")
+ assert z_up == (v[0], -v[2], v[1])
+ assert from_authoring_frame(z_up, "blender") == pytest.approx(v)
+ assert from_authoring_frame(v, "scene_threejs") == v
+
+
+@needs_blender
+@needs_browser
+def test_a_fixture_scene_renders_two_cameras_at_two_times(moving):
+ ws, rs, m = moving
+ out = Path(rs.out_dir)
+ authored = {(v.name, v.time_s) for v in rs.views if v.name in ("Front", "Side")}
+ assert authored == {("Front", 0.0), ("Front", 1.5), ("Side", 0.0), ("Side", 1.5)}
+ for v in rs.views:
+ with Image.open(v.path) as im:
+ assert im.size == (W, H)
+ # the three overviews get pixels at t0 only; the eye-level rig is measured, never rendered
+ rig = sorted((v.name, v.time_s) for v in rs.views if v.name.startswith(("overview", "eye")))
+ assert rig == [("overview_back_left", 0.0), ("overview_front_right", 0.0), ("overview_top", 0.0)]
+ checks = {c["name"]: c for c in m["camera_checks"]}
+ assert set(checks) >= {"Front", "Side", "overview_top", "eye_front", "eye_right", "eye_back_left"}
+ assert set(checks["Front"]) >= STAT_KEYS and not STAT_KEYS & set(checks["eye_front"])
+ assert checks["Front"]["kind"] == "authored" and checks["eye_front"]["kind"] == "orbit"
+ assert 0.05 < checks["Front"]["mean_lum"] < 0.95 and checks["Front"]["content_frac"] > 0.01
+ # the authored camera came out of the .blend (Z-up) into the GLB frame: (0, -14, 4) -> (0, 4, 14)
+ front = next(v for v in m["views"] if v["name"] == "Front")
+ assert front["position"] == pytest.approx([0, 4, 14]) and front["lookAt"] == pytest.approx([0, 1, 0])
+ assert front["fov"] == pytest.approx(40.107, abs=0.01)
+ assert m["language"] == "scene_blender" and m["blender"]["device"] == "CPU" and m["blender"]["samples"] == 4
+ assert m["blender"]["engine"] == "cycles" and len(m["blender"]["frame_ms"]) == 7
+ assert "Blender" in rs.renderer and "cycles" in rs.renderer
+ assert rs.console_errors == [] and rs.contact_sheet and Path(rs.contact_sheet).is_file()
+ judged = {(v.name, v.time_s) for v in rs.views if v.judge}
+ assert ("Front", 0.0) in judged and ("overview_top", 0.0) in judged
+ assert [e["judge"] for e in json.loads((out / "views.json").read_text())].count(True) == len(judged)
+
+
+@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)
+ 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)}"
+ assert {k for v in bm["views"] for k in v} == {k for v in tm["views"] for k in v} - {"repaired_position"}
+ b_checks = {c["name"]: set(c) for c in bm["camera_checks"]}
+ t_checks = {c["name"]: set(c) for c in tm["camera_checks"]}
+ for name in ("Front", "overview_top"):
+ assert b_checks[name] == t_checks[name], name
+ assert b_checks["eye_front"] == t_checks["eye_front"] - STAT_KEYS
+ assert {k for r in bm["motion"] for k in r} == {k for r in tm["motion"] for k in r}
+
+
+@needs_blender
+@needs_browser
+def test_motion_is_measured_on_a_keyframed_object_and_not_on_a_static_scene(moving, tmp_path, monkeypatch):
+ _, _, m = moving
+ rows = {r["name"]: r for r in m["motion"]}
+ assert rows["Front"]["moving"] and rows["Side"]["moving"]
+ assert [f.data["kind"] for f in frame_findings(m).findings if f.data.get("kind") in ("motion", "no_motion")] == ["motion"]
+ _cpu_env(monkeypatch, tmp_path / "cache")
+ ws = build_fixture(Workspace(tmp_path / "still").create(), moving=False, probe=False)
+ rb.render_blender_scene(ws, tmp_path / "r", orbit=False, width=W, height=H, samples=4)
+ still = json.loads((tmp_path / "r" / "metrics.json").read_text())
+ assert [r["moving"] for r in still["motion"]] == [False, False]
+ assert max(r["changed_frac"] for r in still["motion"]) == 0.0 # a fixed seed: Cycles noise is not motion
+ frozen = [f for f in frame_findings(still).findings if f.data.get("kind") == "no_motion"]
+ assert frozen and frozen[0].severity == Severity.ERROR
+ assert "keyframes" in frozen[0].fix_hint and "update(t, dt)" not in frozen[0].fix_hint # the bpy words
+
+
+def _half_png(path: Path) -> None:
+ im = Image.new("RGB", (W, H), (0, 0, 0))
+ im.paste((255, 255, 255), (W // 2, 0, W, H))
+ im.save(path)
+
+
+@needs_browser
+def test_exposure_statistics_of_a_known_png_come_from_the_external_frame(tmp_path):
+ """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")
+ out = tmp_path / "out"
+ out.mkdir()
+ _half_png(out / "K_t0.png")
+ views = [{"name": "K", "kind": "authored", "path": "K_t0.png", "time_s": 0.0, "position": [0, 3, 10],
+ "lookAt": [0, 0, 0], "fov": 50, "render_ms": 1}]
+ (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")
+ 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)
+ assert k["dark_frac"] == pytest.approx(0.5, abs=0.03) and k["blown_frac"] == pytest.approx(0.5, abs=0.03)
+ assert k["modal_frac"] == pytest.approx(0.5, abs=0.03) and k["lum_std"] == pytest.approx(0.5, abs=0.03)
+ assert k["ground_frac"] > 0.2 # coverage still measured on the loaded scene
+ blank = next(c for c in metrics["camera_checks"] if c["name"] == "Blank")
+ assert not STAT_KEYS & set(blank), "no external frame → no luminance at all"
+ assert [v["name"] for v in metrics["views"]] == ["K"]
+
+
+@needs_blender
+def test_a_held_gpu_slot_sends_a_real_render_to_the_cpu(tmp_path, monkeypatch):
+ monkeypatch.setenv("C3D_CACHE_DIR", str(tmp_path / "cache"))
+ monkeypatch.setenv("C3D_RENDER__BLENDER_GPU_SLOTS", "1")
+ monkeypatch.setenv("C3D_RENDER__BLENDER_GPU_WAIT_S", "0.2")
+ get_settings.cache_clear()
+ ws = build_fixture(Workspace(tmp_path / "run").create(), probe=False)
+ out = tmp_path / "out"
+ out.mkdir()
+ job = {"out": str(out), "result": str(out / rb.RESULT_NAME), "engine": "cycles", "samples": 2, "width": 64,
+ "height": 36, "times": [0.0], "authored": True, "cameras": []}
+ held = rb.gpu_slots().take(1.0)
+ try:
+ res = rb.render_frames(ws.artifacts / "scene.blend", out, job, timeout_s=120)
+ finally:
+ rb.Slots.give(held)
+ assert res["device"] == "CPU" and "busy" in res["fallback"] and len(res["frames"]) == 2
+ free = rb.render_frames(ws.artifacts / "scene.blend", out, job, timeout_s=120)
+ assert free["device"] == "GPU" or free["fallback"] == "no CUDA device"
+
+
+def test_a_missing_blend_is_an_empty_renderset_that_says_why(tmp_path):
+ ws = Workspace(tmp_path / "run").create()
+ rs = rb.render_blender_scene(ws, tmp_path / "out")
+ assert rs.views == [] and "scene.blend" in rs.console_errors[0]
+ assert read_json_or_none(tmp_path / "out" / "metrics.json")["language"] == "scene_blender"
+
+
+# --------------------------------------------------------------------------- the slot policy (no Blender)
+class FakeDriver:
+ """Stands in for ``_run_driver``: records the device of every run, can fail / time out on the GPU,
+ and checks the slot is HELD while a GPU run is out."""
+
+ def __init__(self, gpu: str = "ok"):
+ self.gpu = gpu
+ self.devices: list[str] = []
+ self.slot_free_during_gpu: bool | None = None
+
+ def __call__(self, blend, job, out_dir, *, device, timeout_s, settings):
+ self.devices.append(device)
+ if device == "GPU":
+ probe = rb.gpu_slots(settings).try_take()
+ self.slot_free_during_gpu = probe is not None
+ if probe is not None:
+ rb.Slots.give(probe)
+ if self.gpu == "crash":
+ return ProcResult(1, "", "CUDA error: out of memory", False, 5), None
+ if self.gpu == "timeout":
+ return ProcResult(-9, "", "", True, 5), None
+ return ProcResult(0, "", "", False, 5), {"device": device, "frames": [], "device_fallback": ""}
+
+
+def one_slot(tmp_path, monkeypatch):
+ monkeypatch.setenv("C3D_CACHE_DIR", str(tmp_path / "cache"))
+ monkeypatch.setenv("C3D_RENDER__BLENDER_GPU_SLOTS", "1")
+ monkeypatch.setenv("C3D_RENDER__BLENDER_GPU_WAIT_S", "0.3")
+ get_settings.cache_clear()
+ return tmp_path
+
+
+def test_a_free_slot_renders_on_the_gpu_and_holds_the_slot_meanwhile(one_slot, monkeypatch):
+ fake = FakeDriver()
+ monkeypatch.setattr(rb, "_run_driver", fake)
+ res = rb.render_frames(one_slot / "x.blend", one_slot, {}, timeout_s=10)
+ assert fake.devices == ["GPU"] and res["device"] == "GPU" and res["fallback"] == ""
+ assert fake.slot_free_during_gpu is False, "the one slot must be held while the GPU render runs"
+ assert rb.gpu_slots().busy() == 0, "and handed back after it"
+
+
+def test_all_slots_busy_falls_back_to_the_cpu_after_the_wait(one_slot, monkeypatch):
+ fake = FakeDriver()
+ monkeypatch.setattr(rb, "_run_driver", fake)
+ held = rb.gpu_slots().take(1.0)
+ try:
+ t0 = time.monotonic()
+ res = rb.render_frames(one_slot / "x.blend", one_slot, {}, timeout_s=10)
+ waited = time.monotonic() - t0
+ finally:
+ rb.Slots.give(held)
+ assert fake.devices == ["CPU"] and res["device"] == "CPU"
+ assert "busy" in res["fallback"] and 0.25 <= waited < 3.0 and res["slot_wait_ms"] >= 250
+
+
+def test_a_gpu_render_that_dies_is_rendered_again_on_the_cpu(one_slot, monkeypatch):
+ fake = FakeDriver(gpu="crash")
+ monkeypatch.setattr(rb, "_run_driver", fake)
+ res = rb.render_frames(one_slot / "x.blend", one_slot, {}, timeout_s=10)
+ assert fake.devices == ["GPU", "CPU"] and res["device"] == "CPU"
+ assert "GPU render failed" in res["fallback"] and "out of memory" in res["fallback"]
+ assert rb.gpu_slots().busy() == 0
+
+
+def test_a_timeout_is_the_scene_not_the_device_no_cpu_retry(one_slot, monkeypatch):
+ fake = FakeDriver(gpu="timeout")
+ monkeypatch.setattr(rb, "_run_driver", fake)
+ with pytest.raises(SceneRenderError, match="timed out"):
+ rb.render_frames(one_slot / "x.blend", one_slot, {}, timeout_s=10)
+ assert fake.devices == ["GPU"] and rb.gpu_slots().busy() == 0
+
+
+def test_device_cpu_never_touches_a_slot(one_slot, monkeypatch, switch):
+ switch("C3D_RENDER__BLENDER_DEVICE", "cpu")
+ fake = FakeDriver()
+ monkeypatch.setattr(rb, "_run_driver", fake)
+ held = rb.gpu_slots().take(1.0)
+ try:
+ t0 = time.monotonic()
+ res = rb.render_frames(one_slot / "x.blend", one_slot, {}, timeout_s=10)
+ finally:
+ rb.Slots.give(held)
+ assert fake.devices == ["CPU"] and res["fallback"] == "" and time.monotonic() - t0 < 0.2