Official Codebase of 3DCodeVerse
Python
Dedupe small copies: blender_binary, PLACEHOLDER_GROUND_SPANS; delete phantom runtime params (blend/stl/seed, rlimit_gb, tolerances, overwrite, runtime_checkable, dead import aliases)
gaoypeng6e79b0cc9566
diff --git a/harness/codeverse3d/languages/base.py b/harness/codeverse3d/languages/base.pyindex bb2351af..97b928d5 100644--- a/harness/codeverse3d/languages/base.py+++ b/harness/codeverse3d/languages/base.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom collections.abc import Callable, Sequencefrom importlib import import_modulefrom pathlib import Path-from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable+from typing import TYPE_CHECKING, Any, Protocolfrom pydantic import BaseModel, Field@@ -28,7 +28,6 @@ class AssembleResult(BaseModel):census: dict[str, Any] = Field(default_factory=dict)-@runtime_checkableclass LanguageRuntime(Protocol):language: Language#: files the agent is expected to author (globs relative to workspace root)@@ -55,7 +54,6 @@ class LanguageRuntime(Protocol):...-@runtime_checkableclass SceneRuntime(LanguageRuntime, Protocol):"""What the scene track asks of its language: zone / asset locations, entry assembly, probe and render."""diff --git a/harness/codeverse3d/languages/blender/__init__.py b/harness/codeverse3d/languages/blender/__init__.pyindex cf11b6c5..02786a51 100644--- a/harness/codeverse3d/languages/blender/__init__.py+++ b/harness/codeverse3d/languages/blender/__init__.py@@ -30,7 +30,7 @@ from codeverse3d.workspace import WorkspaceGATE = "lint:blender"ALLOWED_IMPORTS = {- "bpy", "bmesh", "mathutils", "math", "random", "numpy", "np", "itertools", "functools",+ "bpy", "bmesh", "mathutils", "math", "random", "numpy", "itertools", "functools","collections", "typing", "dataclasses", "colorsys", "statistics", "operator", "enum", "copy","sys", "os", "__future__", "bpy_extras","parts", # the workspace's own src/parts/<snake>.py modules (multi-file layout)@@ -702,6 +702,13 @@ class BlenderNotFoundError(RuntimeError):"""No usable Blender binary (configure ``C3D_BINARIES__BLENDER`` or put blender on PATH)."""+def blender_binary(override: str | None, settings: Settings) -> str:+ b = override or settings.resolve_blender()+ if not b or not Path(b).exists():+ raise BlenderNotFoundError("Blender binary not found; set C3D_BINARIES__BLENDER=/path/to/blender")+ return b++def blender_env() -> dict[str, str]:"""Environment for a headless Blender child: host python cannot leak in, credential-shaped vars are stripped."""env = scrub_secrets(dict(os.environ))@@ -723,30 +730,9 @@ class BlenderRuntime(RuntimeLayout):self._blender = blender# ------------------------------------------------------------------ helpers- def blender_binary(self) -> str:- b = self._blender or self._settings.resolve_blender()- if not b or not Path(b).exists():- raise BlenderNotFoundError("Blender binary not found; set C3D_BINARIES__BLENDER=/path/to/blender")- return b-def entry_file(self, ws: Workspace) -> Path:return ws.root / ENTRY_REL- def build_command(- self, ws: Workspace, *, stl: bool = True, blend: bool = False, seed: int = 0,- ) -> list[str]:- cmd = [- self.blender_binary(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",- "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts),- "--rlimit-gb", str(self._settings.limits.bpy_rlimit_gb),- "--seed", str(seed),- ]- if stl:- cmd.append("--stl")- if blend:- cmd.append("--blend")- return cmd-# ------------------------------------------------------------------ protocoldef skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:if not isinstance(plan, StaticPlan): # ArticulatedPlan is a StaticPlan subclass → allowed@@ -756,12 +742,12 @@ class BlenderRuntime(RuntimeLayout):def lint(self, ws: Workspace) -> GateReport:return lint_workspace(ws)- def build(- self, ws: Workspace, *, timeout_s: int | None = None, stl: bool = True, blend: bool = False,- seed: int = 0,- ) -> BuildResult:+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:+ def argv() -> list[str]:+ return [blender_binary(self._blender, self._settings), "-b", "--factory-startup", "--python", str(WRAPPER), "--",+ "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts),+ "--rlimit-gb", str(self._settings.limits.bpy_rlimit_gb), "--stl"]+return run_wrapper_build(- ws, language=self.language, extras={"stl": "object.stl", "blend": "object.blend"},- argv=lambda: self.build_command(ws, stl=stl, blend=blend, seed=seed),+ ws, language=self.language, extras={"stl": "object.stl"}, argv=argv,env=blender_env(), timeout_s=timeout_s or self._settings.limits.build_timeout_s, output_filter=strip_blender_noise)-diff --git a/harness/codeverse3d/languages/cadquery/__init__.py b/harness/codeverse3d/languages/cadquery/__init__.pyindex 621e7173..ca1d9a4e 100644--- a/harness/codeverse3d/languages/cadquery/__init__.py+++ b/harness/codeverse3d/languages/cadquery/__init__.py@@ -30,7 +30,7 @@ from codeverse3d.workspace import Workspace# ===================================================================== lintGATE = "lint:cadquery"-ALLOWED_IMPORTS = {"cadquery", "cq", "math", "random", "numpy", "np", "itertools", "functools", "collections",+ALLOWED_IMPORTS = {"cadquery", "math", "random", "numpy", "itertools", "functools", "collections","typing", "dataclasses", "enum", "copy", "statistics", "operator", "__future__"}FORBIDDEN_IMPORTS = frozenset(BASE_FORBIDDEN_IMPORTS | {"os", "sys", "pathlib", # no file-system / interpreter access (unlike blender, nothing legitimate needs them)@@ -317,20 +317,16 @@ class CadQueryRuntime(RuntimeLayout):language = Language.CADQUERYentry_globs: tuple[str, ...] = (ENTRY_FILE[Language.CADQUERY],)- def __init__(self, *, python: str | None = None, settings: Settings | None = None, rlimit_gb: float = 8.0):+ def __init__(self, *, python: str | None = None, settings: Settings | None = None):self._settings = settings or get_settings()self._python = python or sys.executable- self._rlimit_gb = rlimit_gbdef entry_file(self, ws: Workspace) -> Path:return ws.src / "model.py"- def build_command(self, ws: Workspace, *, seed: int = 0) -> list[str]:- """The wrapper's own tolerance defaults are the tessellation."""- return [- self._python, str(WRAPPER), "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts),- "--rlimit-gb", str(self._rlimit_gb), "--seed", str(seed),- ]+ def build_command(self, ws: Workspace) -> list[str]:+ """The wrapper's own constants are the tessellation and the seed."""+ return [self._python, str(WRAPPER), "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts)]# ------------------------------------------------------------------ protocoldef skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:@@ -341,9 +337,9 @@ class CadQueryRuntime(RuntimeLayout):def lint(self, ws: Workspace) -> GateReport:return lint_cadquery_file(self.entry_file(ws))- def build(self, ws: Workspace, *, timeout_s: int | None = None, seed: int = 0) -> BuildResult:+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:return run_wrapper_build(ws, language=self.language, extras={"step": "object.step", "stl": "object.stl"},- argv=lambda: self.build_command(ws, seed=seed),+ argv=lambda: self.build_command(ws),env=cadquery_env(), timeout_s=timeout_s or self._settings.limits.build_timeout_s)diff --git a/harness/codeverse3d/languages/scene_blender/__init__.py b/harness/codeverse3d/languages/scene_blender/__init__.pyindex 73763962..d0d34ee7 100644--- a/harness/codeverse3d/languages/scene_blender/__init__.py+++ b/harness/codeverse3d/languages/scene_blender/__init__.py@@ -56,6 +56,7 @@ from codeverse3d.languages.base import AssembleResult, scene_files_forfrom codeverse3d.languages.blender import (BlenderNotFoundError,BpyCollector,+ blender_binary,blender_env,call_traps,finish_for,@@ -401,14 +402,10 @@ def _v(v: Sequence[float], *, extents: bool = False) -> tuple[float, float, floareturn tuple(round(c, 3) for c in to_authoring_frame(v, LANGUAGE.value, extents=extents))-#: the placeholder plate's side as a multiple of the plan span-PLACEHOLDER_GROUND_SPANS = 3.0--def _env_source(plan: ScenePlan) -> str:"""``src/env.py`` as an interface stub: the plan's data, the two exports the wrapper calls and aplaceholder ground plate. No world, lamp or atmosphere, so it fails the probe until the author writes them."""- from codeverse3d.languages.scene_threejs import sun_from_plan+ from codeverse3d.languages.scene_threejs import PLACEHOLDER_GROUND_SPANS, sun_from_planc, e = _v(plan.bounds.center), _v(plan.bounds.extents, extents=True)span = max(e[0], e[1], 1.0)@@ -695,18 +692,12 @@ class SceneBlenderRuntime:return f"{ENV_FILE}: {dark.message}" if dark is not None else ""# ------------------------------------------------------------------ the Blender process- def blender_binary(self) -> str:- b = self._blender or self._settings.resolve_blender()- if not b or not Path(b).exists():- raise BlenderNotFoundError("Blender binary not found; set C3D_BINARIES__BLENDER=/path/to/blender")- return b-def run_wrapper(self, ws: Workspace, out_dir: Path, *, zones: dict[str, str] | None = None, blend: bool = True,timeout_s: float | None = None, entry: str = ENTRY_REL) -> WrapperRun:"""Build the workspace in Blender into ``out_dir``; ``zones`` overrides ZONES, ``entry`` is another data entry."""out_dir.mkdir(parents=True, exist_ok=True)basis = ",".join(f"{v:g}" for row in glb_basis(LANGUAGE.value) for v in row)- cmd = [self.blender_binary(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",+ cmd = [blender_binary(self._blender, self._settings), "-b", "--factory-startup", "--python", str(WRAPPER), "--","--scene", str(ws.root / entry), "--out", str(out_dir), "--basis", basis, "--zone-key", ZONE_ROOT_KEY,"--fps", str(FPS), "--frames", f"{frame_of(TIMES[0])},{frame_of(TIMES[-1])}","--rlimit-gb", str(self._settings.limits.bpy_rlimit_gb), "--seed", "0"]diff --git a/harness/codeverse3d/languages/threejs/__init__.py b/harness/codeverse3d/languages/threejs/__init__.pyindex 95357293..413eaad0 100644--- a/harness/codeverse3d/languages/threejs/__init__.py+++ b/harness/codeverse3d/languages/threejs/__init__.py@@ -261,15 +261,15 @@ def render_object(plan: StaticPlan) -> str:return OBJECT_HEADER.format(object_name=to_pascal(plan.object_name), imports=imports, adds=adds)-def write_skeleton(ws: Workspace, plan: Plan, *, overwrite: bool = False) -> list[Path]:- """Write ``src/package.json``, ``src/object.js`` and ``src/parts/*.js``; existing files are kept unless ``overwrite``."""+def write_skeleton(ws: Workspace, plan: Plan) -> list[Path]:+ """Write ``src/package.json``, ``src/object.js`` and ``src/parts/*.js``; existing files are kept."""if not isinstance(plan, StaticPlan):raise TypeError(f"threejs skeleton needs a StaticPlan, got {type(plan).__name__}")written: list[Path] = [](ws.src / "parts").mkdir(parents=True, exist_ok=True)def _put(path: Path, text: str) -> None:- if path.exists() and not overwrite:+ if path.exists():returnpath.write_text(text)written.append(path)diff --git a/harness/codeverse3d/languages/wrappers/run_bpy.py b/harness/codeverse3d/languages/wrappers/run_bpy.pyindex 9ef53892..1dec6d24 100644--- a/harness/codeverse3d/languages/wrappers/run_bpy.py+++ b/harness/codeverse3d/languages/wrappers/run_bpy.py@@ -1,11 +1,11 @@"""Blender build wrapper; runs inside Blender, never imported by the harness.blender -b --factory-startup --python run_bpy.py -- \- --script /abs/src/model.py --out /abs/artifacts [--stl] [--blend] [--rlimit-gb 12] [--seed 0]+ --script /abs/src/model.py --out /abs/artifacts [--stl] [--rlimit-gb 12] [--seed 0]Caps memory, clears the factory scene, seeds RNGs, runs the agent's ``model.py`` with ``<ws>/src``on ``sys.path``, collects the census and contract warnings, refuses non-finite geometry, exports-``object.glb`` (+ optional stl / blend) and writes ``build.json`` + ``census.json``.+``object.glb`` (+ optional stl) and writes ``build.json`` + ``census.json``.Exit 0 = reported (even if the script failed); 2 = wrapper bug."""from __future__ import annotations@@ -34,7 +34,6 @@ from _wrapper_common import ( # noqa: E402GLB_NAME = "object.glb"STL_NAME = "object.stl"-BLEND_NAME = "object.blend"EXPORT_TYPES = {"MESH", "CURVE", "SURFACE", "FONT", "META", "EMPTY"}MEMORY_HINT = ("a geometry bomb (tiny remesh voxel_size, huge subdivision/array counts, nested loops ""creating millions of faces). Reduce it.")@@ -45,7 +44,6 @@ def parse_args(argv: list[str]) -> argparse.Namespace:p.add_argument("--script", required=True)p.add_argument("--out", required=True)p.add_argument("--stl", action="store_true")- p.add_argument("--blend", action="store_true")p.add_argument("--rlimit-gb", type=float, default=12.0)p.add_argument("--seed", type=int, default=0)return p.parse_args(argv)@@ -216,13 +214,6 @@ def main() -> int:report["exported"]["stl"] = stlexcept Exception as e: # noqa: BLE001report["warnings"].append(f"STL export failed: {e}")- if args.blend:- blend = os.path.join(out_dir, BLEND_NAME)- try:- report["warnings"].extend(save_blend(bpy, blend))- report["exported"]["blend"] = blend- except Exception as e: # noqa: BLE001- report["warnings"].append(f".blend save failed: {e}")elif not report["error_type"]:report.update(error_type="EmptyScene", error_message="the script created no visible mesh objects")diff --git a/harness/codeverse3d/languages/wrappers/run_cq.py b/harness/codeverse3d/languages/wrappers/run_cq.pyindex 4fd40620..f722bc1b 100644--- a/harness/codeverse3d/languages/wrappers/run_cq.py+++ b/harness/codeverse3d/languages/wrappers/run_cq.py@@ -1,7 +1,7 @@"""CadQuery build wrapper; run by the harness in a subprocess, never imported.python run_cq.py --script /abs/src/model.py --out /abs/artifacts \- [--rlimit-gb 8] [--tolerance 0.001] [--angular-tolerance 0.15] [--seed 0]+ [--rlimit-gb 8] [--seed 0]Runs ``model.py``, reads its module-level ``result`` (Assembly, Workplane or Shape), tessellateseach part and writes ``object.glb`` (Y-up, +Z front), ``.step``, ``.stl``, ``census.json`` and@@ -31,6 +31,7 @@ from _wrapper_common import ( # noqa: E402GLB_NAME, STEP_NAME, STL_NAME = "object.glb", "object.step", "object.stl"PASCAL_RE = re.compile(r"^[A-Z][A-Za-z0-9]*(?:_\d+)?$")DEFAULT_RGBA = (0.7, 0.7, 0.7, 1.0)+TOLERANCE, ANGULAR_TOLERANCE = 0.001, 0.15 # tessellationMEMORY_HINT = "reduce boolean/pattern counts or tessellation density."@@ -39,8 +40,6 @@ def parse_args(argv: list[str]) -> argparse.Namespace:p.add_argument("--script", required=True)p.add_argument("--out", required=True)p.add_argument("--rlimit-gb", type=float, default=8.0)- p.add_argument("--tolerance", type=float, default=0.001)- p.add_argument("--angular-tolerance", type=float, default=0.15)p.add_argument("--seed", type=int, default=0)return p.parse_args(argv)@@ -208,7 +207,7 @@ def main() -> int:report["warnings"].append("result is a bare Workplane/Shape: exported as ONE node 'Object' — prefer cq.Assembly with named, coloured parts")meshes = []for p in parts:- verts, tris = tessellate(p, args.tolerance, args.angular_tolerance)+ verts, tris = tessellate(p, TOLERANCE, ANGULAR_TOLERANCE)meshes.append((p, verts, tris))rec = part_census(p, len(tris))census["parts"].append(rec)@@ -222,7 +221,7 @@ def main() -> int:glb = os.path.join(out_dir, GLB_NAME)build_glb(meshes, glb)report["exported"]["glb"] = glb- export_step_stl(cq, ns["result"], parts, out_dir, args.tolerance, args.angular_tolerance, report)+ export_step_stl(cq, ns["result"], parts, out_dir, TOLERANCE, ANGULAR_TOLERANCE, report)except Exception as e: # noqa: BLE001err = script_error(e, script)if not err["error_file"]: