Skip to content

Official Codebase of 3DCodeVerse

Python

scene: a deterministic placement gate — floating, sunken, unsupported, interpenetrating assets are measured, not guessed

gaoypeng51d5219e6442
diff --git a/harness/codeverse/judges/rubrics/scene_v1.yaml b/harness/codeverse/judges/rubrics/scene_v1.yaml
index ac26b5a5..e2244582 100644
--- a/harness/codeverse/judges/rubrics/scene_v1.yaml
+++ b/harness/codeverse/judges/rubrics/scene_v1.yaml
@@ -206,6 +206,16 @@ defects:
penalty: 0.03
caps:
+ - id: floating_or_sunken_asset
+ when: gate
+ gate: "scene_placement"
+ severity: error
+ kinds: [floating, sunken, unsupported]
+ cap: 0.7
+ note: >
+ the scene_placement gate (2026-08-26) measures every placed asset's gap to what is under it;
+ an ERROR there caps at 0.7, and because this id matches the checklist defect of the same
+ name, a PASSED gate vetoes the VLM's "floating or sunken asset" claim (judges/caps.measured_absent)
- id: build_error
when: gate
gate: "build*"
diff --git a/harness/codeverse/languages/scene_threejs/CONTRACT.md b/harness/codeverse/languages/scene_threejs/CONTRACT.md
index 5b5f9083..67d891b1 100644
--- a/harness/codeverse/languages/scene_threejs/CONTRACT.md
+++ b/harness/codeverse/languages/scene_threejs/CONTRACT.md
@@ -67,6 +67,8 @@ export function createScene({ THREE, renderer, loaders }) { // may be async
* No network, no CDN, no DOM besides `document.createElement('canvas')` for procedural textures.
## Harness tools you can call
-`build` (probe + shader preflight), `scene_probe` (census: meshes, tris, lights,
-zone bboxes, overlaps), `shader_probe` (does your shader actually change the frame?),
+`build` (probe + shader preflight), `check_placement` (per placed asset: floating / sunken /
+unsupported / interpenetration with "lower X by 0.23 m onto Terrain" hints; escape hatch for a
+deliberately airborne thing: `obj.userData.placement = 'free'`), `scene_probe` (census: meshes,
+tris, lights, zone bboxes, overlaps), `shader_probe` (does your shader actually change the frame?),
`render_views` / `render_sheet` (authored + overview cameras at t = 0 and 1.5 s).
diff --git a/harness/codeverse/prompts/scene_threejs/cookbook.md b/harness/codeverse/prompts/scene_threejs/cookbook.md
index 3c13174c..0344325a 100644
--- a/harness/codeverse/prompts/scene_threejs/cookbook.md
+++ b/harness/codeverse/prompts/scene_threejs/cookbook.md
@@ -642,6 +642,14 @@ const campfireDemo = buildCampfire(THREE, { heightAt }); campfireDemo.userData.u
Rules: ≤ 3 shadow-casting lights per scene (the sun + 1–2 heroes); decorative lights get
`castShadow = false` and distance-limited falloff.
+Placement is MEASURED (`check_placement`; the `scene_placement` gate runs on every build): each
+direct child of your zone group is an asset; from its lowest vertices the harness looks down for the
+nearest surface and up for one passing through it. Gap > 5 cm (2 cm indoors) → `floating`; foot
+> 10 cm under a surface → `sunken` (rocks/posts/bushes may sit half their height in the ground; a basin
+or pit never counts; a foot at/under water is fine); bbox touching nothing → `unsupported`; boxes sharing
+> 20 % → `interpenetration`. Seat things with `heightAt(x, z)` and they pass. A thing MEANT to hang in
+the air (bird, drone): `obj.userData.placement = 'free'` on it or its zone = exempt. Instanced meshes are not checked.
+
## Assets (`src/assets/*.js`) and GLB assets from Blender
```js
@@ -934,8 +942,9 @@ Composition self-check on every authored frame (the judge grades exactly these):
* shade is coloured (sky-tinted), not black; key and fill hues differ;
* t=0 and t=1.5 are visibly different.
-Then: `build` → `scene_probe` (draws/tris/fps/console) → `scene_views` (authored cameras +
+Then: `build` → `check_placement` (floating/sunken/interpenetration + the fix per asset) → `scene_probe` (draws/tris/fps/console) → `scene_views` (authored cameras +
overview rig, with `camera_checks`) → `shader_probe` if you wrote GLSL → fix the worst →
repeat. Look at every camera's frame AND its numbers: `mean_lum` ≥ 0.15 (no black frames),
`blown_frac` ≤ 0.10 (no white-out), `content_frac` ≥ 0.25 on the establishing shot (the
-subject, not sky/ground, fills the frame), `camera_in_geometry` false, nothing floating.
+subject, not sky/ground, fills the frame), `camera_in_geometry` false, and `check_placement`
+clean (nothing floating, sunken or interpenetrating).
diff --git a/harness/codeverse/prompts/system/harness_contract.md b/harness/codeverse/prompts/system/harness_contract.md
index e744cb49..82ddd8c2 100644
--- a/harness/codeverse/prompts/system/harness_contract.md
+++ b/harness/codeverse/prompts/system/harness_contract.md
@@ -81,7 +81,7 @@ tri count) and the images. "It should be fine" is not evidence; a render is.
5. [ ] `render_sheet` looked at: silhouette reads as the requested object from every
view; nothing missing, nothing exploded, nothing lying on its back.
6. [ ] Hollow / articulated / animated behaviour verified (`cross_section`,
- `joint_sweep`, `scene_probe` as applicable).
+ `joint_sweep`, `scene_probe` + `check_placement` as applicable).
7. [ ] Materials / colours assigned per plan (no grey default everywhere).
8. [ ] Code is tidy: constants on top, one function per part, no dead code, no debug
prints left, no forbidden imports.
diff --git a/harness/codeverse/prompts/system/tools_usage.md b/harness/codeverse/prompts/system/tools_usage.md
index 504ceb73..8b7ecae7 100644
--- a/harness/codeverse/prompts/system/tools_usage.md
+++ b/harness/codeverse/prompts/system/tools_usage.md
@@ -42,6 +42,9 @@ Always `build` after an edit; never reason about stale renders.
pairs per pose; "child does not move" or "penetrates parent at q=1.2" is the finding.
* `scene_probe()` — census (draw calls, tris, instanced meshes), cameras inside geometry,
console errors, fps, black/blown frames.
+* `check_placement()` — (scene) every placed asset's gap to what is under it, burial depth,
+ water, contacts and 3-D interpenetrations; "floating / sunken / unsupported /
+ interpenetration" findings with the exact move to make. Run it after every `build`.
* `shader_probe()` — compiles every ShaderMaterial / onBeforeCompile patch with the real
renderer; reports GLSL errors with the author's line number.
* `read_cookbook(section="Booleans")` — fetch one cookbook chapter by its heading.
diff --git a/harness/codeverse/prompts/tracks/scene_refine.j2 b/harness/codeverse/prompts/tracks/scene_refine.j2
index ee4ac039..77f37dcd 100644
--- a/harness/codeverse/prompts/tracks/scene_refine.j2
+++ b/harness/codeverse/prompts/tracks/scene_refine.j2
@@ -78,7 +78,9 @@ timid: double the amplitude / the count / the contrast this time.
## Tools
{{ tool_cards }}
-Run `build` (and `scene_probe`) after editing; finish only when clean. `scene_views` prints the
+Run `build` → `check_placement` → fix → `build` after editing (and `scene_probe` for the census);
+finish only when both are clean. `check_placement` measures floating / sunken / unsupported /
+interpenetrating assets deterministically — its numbers, not your impression. `scene_views` prints the
frame table and the MEASURED MOTION per camera — use those numbers, not your impression.
{% endif %}
{% if recipes is defined and recipes %}
diff --git a/harness/codeverse/prompts/tracks/scene_zone.j2 b/harness/codeverse/prompts/tracks/scene_zone.j2
index 6e149e97..3f014a54 100644
--- a/harness/codeverse/prompts/tracks/scene_zone.j2
+++ b/harness/codeverse/prompts/tracks/scene_zone.j2
@@ -80,7 +80,10 @@ The recipes for all five points below are printed in full at the end of this bri
## Tools
{{ tool_cards }}
-After editing run `build`, then `scene_views` and LOOK at the frames: count the silhouettes, look
+After editing run `build` → `check_placement` (it names every asset that floats, is sunken,
+touches nothing or interpenetrates another, with the exact "lower X by 0.23 m onto Terrain"
+fix; a deliberately airborne thing gets `obj.userData.placement = 'free'`) → fix → `build`
+again, then `scene_views` and LOOK at the frames: count the silhouettes, look
for a flat colour under your props, and read the MEASURED MOTION line it prints — if your zone's
motion is under 0.4 % of the frame, double the amplitude and render again.
{% endif %}
diff --git a/harness/codeverse/spatial/scene_placement.py b/harness/codeverse/spatial/scene_placement.py
new file mode 100644
index 00000000..d2d9dff7
--- /dev/null
+++ b/harness/codeverse/spatial/scene_placement.py
@@ -0,0 +1,309 @@
+"""Scene placement gate ``scene_placement``: floating / sunken / unsupported /
+interpenetrating assets, measured — not judged.
+
+Added 2026-08-26. Audit that day: the scene track had NO deterministic placement
+check (``probes.py`` reported 2-D zone-footprint overlap as INFO; the census
+``ground_y`` fed camera checks only); the scene_v1 ``floating_part`` cap (kinds
+floating / sunken / unsupported, gate ``*``) could never fire because no scene gate
+emitted those words; ``contracts/plan.py`` declared acceptance ``how: probe`` that
+nothing probed; in 52 recorded scene sessions the object tools ``check_connectivity``
+/ ``measure`` were called 0 times (they fail on a scene workspace). Floating /
+sunken was left to the VLM (defect −0.06).
+
+Numbers come from ``runtime_js/lib/host_placement.mjs`` (per placed asset: foot-column
+gap to the surface beneath, burial depth, water, contacts; 3-D interpenetration pairs),
+carried in the probe census under ``placement``; this module turns them into
+``GateFinding``\ s whose messages contain the cap words and whose ``fix_hint`` names
+the move ("lower X by 0.23 m onto Terrain"). Sunk is judged relative to the asset's
+height and its name words because the harness's own starter scene buries rocks
+20–50 % of their height, digs a pond basin 1.4 m under the terrain and drives jetty
+posts 0.97 m into the pond bed — a naive "> 0.10 m" rule flagged all of them
+(measured 2026-08-26). Word matching is a set lookup on ``to_snake`` words.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Any
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.conventions import to_snake
+from codeverse.proc import read_json_or_none
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+GATE = "scene_placement"
+CONTACT_M = 0.02 # a foot this close to what is under it rests on it
+FLOATING_OUTDOOR_M, FLOATING_INDOOR_M = 0.05, 0.02
+FLOATING_ERROR_M, FLOATING_ERROR_COUNT = 0.15, 3 # this high, or more than this many, → ERROR
+SUNK_M, SUNK_ERROR_M = 0.10, 0.30
+SUNK_ERROR_FRAC = 0.25 # an ERROR burial must also swallow this fraction of the height
+PARTIAL_OK_FRAC, PARTIAL_OK_ERROR_FRAC = 0.50, 0.75 # rocks / posts / bushes: WARN past half, ERROR past 3/4
+OVERLAP_WARN, OVERLAP_ERROR = 0.20, 0.60
+MAX_FINDINGS_PER_KIND = 8
+
+#: setting / environment words that make a scene "indoors" (tighter floating tolerance)
+INDOOR_WORDS = frozenset({
+ "attic", "basement", "bathroom", "bedroom", "cabin", "cellar", "chamber", "classroom", "cockpit", "corridor", "garage", "hall", "hut", "indoor",
+ "indoors", "inside", "interior", "kitchen", "lab", "laboratory", "library", "lobby", "office", "room", "studio", "tent", "warehouse", "workshop",
+})
+#: things that are BELOW ground by definition: never "sunken"
+BURIED_OK_WORDS = frozenset({
+ "basin", "bed", "canal", "cave", "cellar", "crater", "ditch", "drain", "foundation", "foundations", "grave", "gutter", "hole", "lakebed", "moat",
+ "pit", "pool", "riverbed", "trench", "tunnel", "well",
+})
+#: things normally driven or grown into the ground: sunken only past half their height
+PARTIAL_OK_WORDS = frozenset({
+ "boulder", "boulders", "bridge", "bush", "bushes", "cliff", "cliffs", "dock", "dune", "dunes", "fence", "fences", "flower", "flowers", "grass",
+ "hill", "hills", "jetty", "log", "logs", "mound", "mounds", "outcrop", "pebble", "pebbles", "pier", "pile", "piles", "plant", "plants", "pole",
+ "poles", "post", "posts", "reed", "reeds", "rock", "rocks", "root", "roots", "shrub", "shrubs", "stake", "stakes", "stone", "stones", "stump",
+ "stumps", "tree", "trees", "trunk", "trunks", "tuft", "tufts",
+})
+
+
+class AssetRow(BaseModel):
+ """One row of the census placement table (``host_placement.mjs``)."""
+
+ model_config = ConfigDict(extra="ignore")
+
+ name: str
+ zone: str = ""
+ exempt: str = ""
+ bbox: dict[str, Any] | None = None
+ ground_gap_m: float | None = None
+ support: str = ""
+ sunk_m: float = 0.0
+ sunk_into: str = ""
+ on_water: bool = False
+ attached: list[str] = Field(default_factory=list)
+
+ @property
+ def qualified(self) -> str:
+ """``Zone/Name`` — routes to the zone's file in refine tasks, stays unique per asset."""
+ return f"{self.zone}/{self.name}" if self.zone else self.name
+
+ @property
+ def height(self) -> float:
+ return float(self.bbox["size"][1]) if self.bbox and self.bbox.get("size") else 0.0
+
+
+class Interpenetration(BaseModel):
+ model_config = ConfigDict(extra="ignore")
+
+ a: str
+ b: str
+ zone_a: str = ""
+ zone_b: str = ""
+ aabb_overlap: float = 0.0 # box overlap / smaller box (the reported number)
+ inside_frac: float = 0.0 # vertices of the smaller inside the larger (the confirmation)
+
+
+class PlacementTable(BaseModel):
+ model_config = ConfigDict(extra="ignore")
+
+ assets: list[AssetRow] = Field(default_factory=list)
+ interpenetrations: list[Interpenetration] = Field(default_factory=list)
+ total: int = 0
+ checked: int = 0
+ truncated: bool = False
+ exempt: dict[str, int] = Field(default_factory=dict)
+ ground_y: float | None = None
+ notes: list[str] = Field(default_factory=list)
+ error: str = ""
+
+
+def _words(name: str) -> set[str]:
+ return {w for w in to_snake(name).split("_") if w and not w.isdigit()}
+
+
+def infer_indoor(text: str) -> bool:
+ """Does the plan's setting / environment text say the scene is indoors?"""
+ return bool(_words(text) & INDOOR_WORDS)
+
+
+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})
+
+
+def _support_label(row: AssetRow, ground_y: float | None) -> str:
+ if row.support and row.support != "ground_y":
+ return row.support
+ return f"the ground (census ground_y = {ground_y:.2f} m)" if ground_y is not None else "the ground"
+
+
+def _sunk_severity(row: AssetRow) -> Severity | None:
+ """WARN / ERROR / None for a buried foot, honouring height fraction and name words."""
+ if row.sunk_m <= 0 or row.on_water:
+ return None
+ words = _words(row.name)
+ if words & BURIED_OK_WORDS:
+ return None
+ frac = row.sunk_m / row.height if row.height > 1e-6 else 1.0
+ if words & PARTIAL_OK_WORDS:
+ if frac > PARTIAL_OK_ERROR_FRAC and row.sunk_m > SUNK_ERROR_M:
+ return Severity.ERROR
+ return Severity.WARN if frac > PARTIAL_OK_FRAC else None
+ if row.sunk_m > SUNK_ERROR_M and frac > SUNK_ERROR_FRAC:
+ return Severity.ERROR
+ 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]:
+ out: list[GateFinding] = []
+ floating: list[tuple[AssetRow, float]] = []
+ for row in rows:
+ q = row.qualified
+ sev = _sunk_severity(row)
+ if sev is not None:
+ out.append(_f(sev, f"{q} is sunken {row.sunk_m:.2f} m into {row.sunk_into or 'the ground'}", target=q,
+ hint=f"raise {q} by {row.sunk_m:.2f} m so its lowest point sits on {row.sunk_into or 'the ground'}",
+ kind="sunken", sunk_m=row.sunk_m, into=row.sunk_into, zone=row.zone))
+ continue
+ gap = row.ground_gap_m
+ if gap is None or row.on_water or row.sunk_m > 0 or gap <= CONTACT_M:
+ continue
+ support = _support_label(row, ground_y)
+ if gap > floating_m and row.attached:
+ out.append(_f(Severity.WARN, f"{q} is floating {gap:.2f} m above {support}, but its bbox touches {', '.join(row.attached[:3])}",
+ target=q, hint=f"fine if {q} is mounted on {row.attached[0]}; otherwise lower it by {gap:.2f} m onto {support}",
+ kind="floating", gap_m=gap, attached=row.attached[:3], zone=row.zone))
+ elif gap > floating_m:
+ floating.append((row, gap))
+ elif not row.attached:
+ 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'",
+ kind="unsupported", gap_m=gap, zone=row.zone))
+ many = len(floating) > FLOATING_ERROR_COUNT
+ for row, gap in floating:
+ q = row.qualified
+ 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'",
+ kind="floating", gap_m=gap, zone=row.zone))
+ return out
+
+
+def _pair_findings(pairs: list[Interpenetration]) -> list[GateFinding]:
+ out: list[GateFinding] = []
+ for p in pairs:
+ qa = f"{p.zone_a}/{p.a}" if p.zone_a else p.a
+ qb = f"{p.zone_b}/{p.b}" if p.zone_b else p.b
+ sev = Severity.ERROR if p.aabb_overlap > OVERLAP_ERROR else Severity.WARN
+ out.append(_f(sev, f"interpenetration: {qa} and {qb} overlap ({p.aabb_overlap:.0%} of the smaller box; "
+ f"{p.inside_frac:.0%} of its vertices inside the other)", target=qa,
+ hint=f"move {qa} out of {qb} or shrink one of them so their boxes share ≤ {OVERLAP_WARN:.0%}",
+ kind="interpenetration", overlap=p.aabb_overlap, inside_frac=p.inside_frac, other=qb, zone=p.zone_a))
+ return out
+
+
+def _cap_per_kind(findings: list[GateFinding]) -> list[GateFinding]:
+ """Keep the worst ``MAX_FINDINGS_PER_KIND`` per kind (ERROR first, then magnitude); the
+ rest becomes one INFO line, so 30 floating pebbles cannot flood the refine prompt."""
+ rank = {Severity.ERROR: 0, Severity.WARN: 1, Severity.INFO: 2}
+ by_kind: dict[str, list[GateFinding]] = {}
+ for f in findings:
+ by_kind.setdefault(str(f.data.get("kind")), []).append(f)
+ out: list[GateFinding] = []
+ for kind, fs in by_kind.items():
+ fs.sort(key=lambda f: (rank[f.severity], -float(f.data.get("gap_m") or f.data.get("sunk_m") or f.data.get("overlap") or 0)))
+ out.extend(fs[:MAX_FINDINGS_PER_KIND])
+ if len(fs) > MAX_FINDINGS_PER_KIND:
+ out.append(_f(Severity.INFO, f"… and {len(fs) - MAX_FINDINGS_PER_KIND} more {kind} finding(s) not listed", target="scene",
+ kind="truncated", of=kind))
+ return out
+
+
+def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool = False, duration_ms: int = 0) -> 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:
+ return GateReport(gate=GATE, passed=True, duration_ms=duration_ms, findings=[
+ _f(Severity.WARN, f"placement probe failed: {t.error[:300]}", target="scene", kind="probe_failed",
+ 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))
+ 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())
+ summary = (f"{t.checked} assets checked ({t.total} placed, {n_exempt} exempt): {counts['floating']} floating, "
+ f"{counts['sunken']} sunken, {counts['unsupported']} unsupported, {counts['interpenetration']} interpenetrating"
+ + (f"; {'indoor' if indoor else 'outdoor'} tolerance {floating_m * 100:.0f} cm")
+ + ("; table truncated (first 400 assets / time budget)" if t.truncated else ""))
+ findings.insert(0, _f(Severity.INFO, summary, target="scene", kind="summary", counts=counts, checked=t.checked, total=t.total,
+ exempt=t.exempt, truncated=t.truncated))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=duration_ms)
+
+
+def placement_census(ws: Workspace, *, force_probe: bool = False, timeout_s: float = 60.0) -> dict[str, Any]:
+ """The census dict carrying ``placement``: the last build's ``artifacts/census.json``,
+ or a fresh ``probe_scene`` when it is missing / predates the table / ``force_probe``."""
+ census = None if force_probe else read_json_or_none(ws.artifacts / "census.json")
+ if isinstance(census, dict) and isinstance(census.get("placement"), dict):
+ return census
+ from codeverse.spatial.probes import probe_scene
+
+ res = probe_scene(ws, timeout_s=timeout_s)
+ if res.errors:
+ return {"placement": {"error": res.errors[0]}}
+ census = res.census or {}
+ if not isinstance(census.get("placement"), dict):
+ census["placement"] = {"error": "the scene did not boot, so nothing was placed" if not census else "probe driver returned no placement table"}
+ return census
+
+
+def _setting_text(ws: Workspace) -> str:
+ plan = read_json_or_none(ws.plan_path)
+ if not isinstance(plan, dict):
+ return ""
+ return " ".join(str(plan.get(k) or "") for k in ("setting", "environment", "title"))
+
+
+def check_placement(ws: Workspace, *, indoor: bool | None = None, force_probe: bool = False, timeout_s: float = 60.0) -> GateReport:
+ """Gate ``scene_placement`` for a workspace (census of the last build, or a fresh probe)."""
+ t0 = time.time()
+ census = placement_census(ws, force_probe=force_probe, timeout_s=timeout_s)
+ if indoor is None:
+ indoor = infer_indoor(_setting_text(ws))
+ return placement_findings(census.get("placement") or {}, indoor=indoor, duration_ms=int((time.time() - t0) * 1000))
+
+
+def placement_gate_safe(census: dict[str, Any] | None, *, plan: Any = None) -> GateReport | None:
+ """Round-gate entry: ``None`` when the census has no placement table (scene did not
+ boot, or an older driver), a WARN-only report when anything raises — never an
+ exception, so the placement check cannot kill a round."""
+ try:
+ table = (census or {}).get("placement")
+ if not isinstance(table, dict):
+ return None
+ text = " ".join(str(getattr(plan, k, "") or "") for k in ("setting", "environment", "title"))
+ return placement_findings(table, indoor=infer_indoor(text))
+ except Exception as e: # noqa: BLE001 — advisory instrumentation must not fail the round
+ log.warning("scene placement gate failed: %s", e)
+ return GateReport(gate=GATE, passed=True, findings=[
+ _f(Severity.WARN, f"placement probe failed: {type(e).__name__}: {e}"[:400], target="scene", kind="probe_failed")])
+
+
+def placement_table_text(table: dict[str, Any] | PlacementTable, *, max_rows: int = 40) -> str:
+ """The per-asset table behind the findings (tool observations / prompts)."""
+ t = table if isinstance(table, PlacementTable) else PlacementTable.model_validate(table or {})
+ if t.error:
+ return f"placement table unavailable: {t.error}"
+ lines = [f"placement: {t.checked} checked of {t.total} placed; exempt {t.exempt or '{}'}; ground_y {t.ground_y}"
+ + ("; TRUNCATED" if t.truncated else "")]
+ lines.append("asset | gap to support (m) | support | sunk (m) | into | water | attached")
+ for r in [r for r in t.assets if not r.exempt][:max_rows]:
+ lines.append(f"{r.qualified} | {'-' if r.ground_gap_m is None else f'{r.ground_gap_m:+.3f}'} | {r.support or '-'} | "
+ f"{r.sunk_m:.3f} | {r.sunk_into or '-'} | {'yes' if r.on_water else '-'} | {', '.join(r.attached[:3]) or '-'}")
+ for p in t.interpenetrations[:10]:
+ lines.append(f"interpenetration {p.zone_a}/{p.a} × {p.zone_b}/{p.b}: {p.aabb_overlap:.0%} box, {p.inside_frac:.0%} inside")
+ lines += [f"note: {n}" for n in t.notes[:3]]
+ return "\n".join(lines)
diff --git a/harness/codeverse/spatial/tools_scene.py b/harness/codeverse/spatial/tools_scene.py
index 144e7e07..cef6d6ce 100644
--- a/harness/codeverse/spatial/tools_scene.py
+++ b/harness/codeverse/spatial/tools_scene.py
@@ -117,3 +117,33 @@ def _frame_table(out_dir) -> str:
return frame_summary_text(metrics) if metrics else ""
except Exception: # noqa: BLE001 — a tool observation must never fail on instrumentation
return ""
+
+
+class CheckPlacementArgs(BaseModel):
+ rebuild: bool = Field(default=False, description="re-run the scene probe first (slow) instead of reading the census of the last build")
+
+
+@tool("check_placement", CheckPlacementArgs,
+ "Deterministic placement check of the last build (scene only): per placed asset the gap from its feet to what is "
+ "under them, burial depth, water, contacts, plus 3-D interpenetrations between assets — findings read "
+ "'floating / sunken / unsupported / interpenetration' with 'lower X by 0.23 m onto Terrain' hints. Reads the "
+ "census of the last build/scene_probe; rebuild=true probes again. Tag a deliberately airborne thing with "
+ "obj.userData.placement = 'free'.",
+ languages=(Language.SCENE_THREEJS.value,), cost_hint="fast")
+def check_placement(ctx: ToolContext, args: CheckPlacementArgs) -> Observation:
+ census_of = lazy("codeverse.spatial.scene_placement", "placement_census")
+ findings_of = lazy("codeverse.spatial.scene_placement", "placement_findings")
+ table_of = lazy("codeverse.spatial.scene_placement", "placement_table_text")
+ infer_indoor = lazy("codeverse.spatial.scene_placement", "infer_indoor")
+ census = census_of(ctx.workspace, force_probe=args.rebuild)
+ indoor = False
+ if ctx.workspace.plan_path.is_file():
+ try:
+ plan = load_plan(ctx.workspace.plan_path)
+ indoor = infer_indoor(" ".join(str(getattr(plan, k, "") or "") for k in ("setting", "environment", "title")))
+ except ToolUsageError:
+ indoor = False
+ table = census.get("placement") or {}
+ report = findings_of(table, indoor=indoor)
+ obs = gate_observation(report, title="placement check")
+ return obs.model_copy(update={"text": truncate(obs.text + "\n\n" + table_of(table))})
diff --git a/harness/codeverse/tracks/prompting.py b/harness/codeverse/tracks/prompting.py
index 9a78a86e..da1912cc 100644
--- a/harness/codeverse/tracks/prompting.py
+++ b/harness/codeverse/tracks/prompting.py
@@ -493,6 +493,12 @@ def file_for_target_factory(ctx: RunContext):
return ["src/scene.js"]
if key in ("env", "environment", "lighting", "sky", "fog", "ground", "water", "light"):
return ["src/env.js"]
+ # "Zone/Asset" — the scene_placement gate names the asset but the fix lives in the
+ # zone's file; keeping the asset in the target keeps one refine task per asset
+ if "/" in target:
+ zone_key = to_snake(target.split("/", 1)[0])
+ if zone_key in zones:
+ return [f"src/zones/{zone_key}.js"]
return []
return _scene
diff --git a/harness/codeverse/tracks/scene.py b/harness/codeverse/tracks/scene.py
index 613fb593..fe3ffe01 100644
--- a/harness/codeverse/tracks/scene.py
+++ b/harness/codeverse/tracks/scene.py
@@ -108,6 +108,20 @@ class ScenePipeline:
census_gate = census_gate_report(build)
if census_gate is not None:
out.append(census_gate)
+ # scene_placement (2026-08-26): floating / sunken / unsupported / interpenetrating assets from
+ # the probe census's placement table — the first deterministic placement gate on this track
+ # (before it, the scene_v1 floating_part cap could never fire). Advisory instrumentation:
+ # a failure is a WARN finding, never an exception, so it cannot kill a round.
+ try:
+ from codeverse.spatial.scene_placement import placement_gate_safe
+
+ placement = placement_gate_safe(build.census, plan=ctx.plan)
+ except Exception as e: # noqa: BLE001
+ log.warning("scene placement gate unavailable: %s", e)
+ placement = GateReport(gate="scene_placement", passed=True, findings=[GateFinding(
+ gate="scene_placement", severity=Severity.WARN, target="scene", message=f"placement probe failed: {e}"[:400])])
+ if placement is not None:
+ out.append(placement)
return out
def render(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> RenderSet:
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 20d9ba98..37cc83ee 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -110,6 +110,9 @@ codeverse/
spatial/ node.py, render.py, tool_common.py (shared tool plumbing), cookbook_tool.py
(read_cookbook), render_scene.py (judge view subset, content-fitted orbit),
frame_metrics.py (scene_frames gate), frame_motion.py (measured inter-frame motion),
+ scene_placement.py (scene_placement gate + check_placement tool: floating / sunken /
+ unsupported / interpenetration per placed asset from the probe census's placement
+ table, runtime_js/lib/host_placement.mjs; added 2026-08-26),
gl_render.py (GlHost), frame_stats.py (gl_frames),
sheet.py (montage_2x2, crop_region), turntable.py, measure.py, connectivity.py,
contract.py (authoring-frame hints), sections.py, silhouette.py, probes.py,
@@ -206,7 +209,8 @@ bench/ run_bench.py, report.py (renders through codeverse/gallery
prompts/{static_objects_v1 (24), articulated_v1 (12), scenes_v1 (12), compare_v1 (8)}.yaml
runtime_js/ export_glb.mjs (placement policy, instance baking, selfcheck) render_glb.mjs
render_scene.mjs probe_scene.mjs check_shaders.mjs gpu_launch.cjs serve.cjs
- lib/{resolve_three, scene_host, host_coverage, orbit, instances, census, glsl_audit, browser/…}
+ lib/{resolve_three, scene_host, host_coverage, host_census, host_placement, orbit, instances,
+ census, glsl_audit, browser/…}
tests/ core models agents blender_cadquery threejs_render urdf_joints scene_runtime scene_gates
spatial_tools judges orchestrator_tracks flywheel_cli graphics texturing prompts (~860 offline)
```
@@ -356,7 +360,12 @@ finalise: restore best commit, rebuild so artifacts match delivered code, finali
```
Track-specific gates: static `connectivity` + `contract` (+ `reference_silhouette`),
articulated + `joint_sweep` + `motion_direction` (URDF axis vs plan motion text),
-scene `render_console` + `scene_frames` (`spatial/frame_metrics.py`, wired in
+scene `scene_placement` (`spatial/scene_placement.py`, appended after the census gate in
+`ScenePipeline.gates`: per placed asset, foot-column gap to the surface beneath, burial depth,
+water, contacts and 3-D interpenetration pairs from `runtime_js/lib/host_placement.mjs` — the
+first deterministic placement check on the track; before 2026-08-26 the scene_v1
+`floating_part` cap could never fire and floating/sunken was left to the VLM) +
+`render_console` + `scene_frames` (`spatial/frame_metrics.py`, wired in
`ScenePipeline.post_render_gates`: dark/blown/flat frames, camera in geometry, content
too small, and **`no_motion`** — the frames of one camera at the first and last animation
time are diffed in `spatial/frame_motion.py` and the per-camera "% of pixels changed"
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 4e0dc497..f3958d70 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -238,6 +238,11 @@ complexity_of_glb(glb) -> ComplexityVector # part_count, assembly_depth, tri
from codeverse.spatial.connectivity import check_connectivity # (glb, *, gap_m=…, …, language="") — Δ language selects the
from codeverse.spatial.contract import check_contract # frame of fix hints; both gates emit hints in the AUTHORING frame
# (labelled "blender frame: Z-up, -Y front" etc.), GLB vectors in data
+from codeverse.spatial.scene_placement import check_placement, placement_findings, placement_gate_safe, placement_census, placement_table_text
+check_placement(ws, *, indoor=None, force_probe=False) -> GateReport # gate "scene_placement"; data.kind ∈ floating | sunken |
+ # unsupported | interpenetration | summary | probe_failed; target "Zone/Asset" (routes to src/zones/<zone>.js);
+ # messages carry the scene_v1 floating_part cap words; reads artifacts/census.json["placement"] (host_placement.mjs)
+placement_gate_safe(census, *, plan=None) -> GateReport | None # round gate: None without a table, WARN on failure, never raises
from codeverse.spatial.silhouette import compare_silhouette
from codeverse.spatial.joints import load_urdf, fk, sweep_collisions, urdf_to_glb, render_poses # RESERVED_LINK_NAMES={'world'}
# joints_collide.py: deterministic penetration (oriented islands + fixed-direction parity ray test; python-fcl is a
@@ -251,7 +256,7 @@ from codeverse.spatial.frame_stats import sequence_stats, frame_gate # gate "
from codeverse.spatial.registry import tool, get_tool, list_tools, tool_cards, ToolContext, Observation
import codeverse.spatial.tools # registers: build, measure, render_views, render_sheet, isolate, cross_section,
# check_connectivity, check_contract, compare_silhouette, joint_sweep [articulated], shader_probe, scene_probe,
- # scene_views [scene], read_cookbook, gl_probe + gl_frames [graphics], texture_pass + texture_preview [object tracks]
+ # scene_views + check_placement [scene], read_cookbook, gl_probe + gl_frames [graphics], texture_pass + texture_preview [object tracks]
python -m codeverse.spatial.mcp_server --workspace <ws> [--track X] [--language Y] [--round N] [--list] # MCP name: 3dcv
```
diff --git a/harness/runtime_js/lib/host_census.mjs b/harness/runtime_js/lib/host_census.mjs
index ac9d7925..4358c199 100644
--- a/harness/runtime_js/lib/host_census.mjs
+++ b/harness/runtime_js/lib/host_census.mjs
@@ -8,6 +8,7 @@
import { classifyBackdrop } from './backdrop.mjs';
import { geometryTriangles as triCount } from './census.mjs';
+import { placementTable } from './host_placement.mjs';
export function isCustomShader(mat, THREE) {
if (!mat) return false;
@@ -87,8 +88,10 @@ function overlapStats(groups) {
return out.sort((x, y) => y.footprint_overlap - x.footprint_overlap).slice(0, 20);
}
-/** Walk `scene` and return the census JSON. */
-export function sceneCensus(scene, THREE) {
+/** Walk `scene` and return the census JSON. `opts.placement` (default off — the
+ * render driver calls this per frame set) adds the per-asset placement table of
+ * `host_placement.mjs` under `placement`; the probe driver asks for it separately. */
+export function sceneCensus(scene, THREE, opts = {}) {
scene.updateMatrixWorld(true);
const groups = [];
const totals = { meshes: 0, instances: 0, triangles: 0, lights: 0, custom_shader_meshes: 0 };
@@ -129,7 +132,7 @@ export function sceneCensus(scene, THREE) {
}
const groundY = groundAll.isEmpty() ? null : groundAll.max.y;
const contentBox = boxToJson(content.isEmpty() ? unionAll : content);
- return {
+ const out = {
totals,
light_types: lightTypes,
materials: materials.size,
@@ -144,4 +147,6 @@ export function sceneCensus(scene, THREE) {
has_ground: groundY !== null,
overlaps: overlapStats(groups),
};
+ if (opts.placement) out.placement = placementTable(scene, THREE, { groundY: out.ground_y, contentBox });
+ return out;
}
diff --git a/harness/runtime_js/lib/host_placement.mjs b/harness/runtime_js/lib/host_placement.mjs
new file mode 100644
index 00000000..7f4145f0
--- /dev/null
+++ b/harness/runtime_js/lib/host_placement.mjs
@@ -0,0 +1,422 @@
+/**
+ * Placement table — deterministic "does every placed asset sit on something?"
+ * for a THREE.Scene (page-side or node; pure three.js math, no renderer).
+ * Added 2026-08-26: the scene track had NO deterministic placement check — the
+ * census only reported 2-D zone-footprint overlap (INFO) and floating / sunken
+ * assets were left to the VLM (defect −0.06), while the scene_v1 `floating_part`
+ * cap could never fire because no gate emitted those words.
+ *
+ * A "placed asset" is each direct child of a top-level scene child (the zone
+ * groups the census already calls `groups`) that has Mesh descendants; a
+ * top-level Mesh is an asset of its own. Assets are named by Object3D name.
+ *
+ * Per asset (all in world space, metres):
+ * bbox exact AABB of its (non-instanced) mesh vertices
+ * ground_gap_m min over its FOOT COLUMNS of the vertical distance from the
+ * foot to the nearest surface of any OTHER mesh below it (terrain,
+ * floor, table…); falls back to the census ground_y when nothing
+ * is beneath. Foot columns are up to 5 XZ points taken from the
+ * asset's lowest vertices (lowest, ±x, ±z extremes of the band
+ * ≤ 5 % of its height above its minimum) — so a table is measured
+ * at its leg tips, not under its top.
+ * sunk_m max over columns of how far the foot sits below a surface that
+ * passes through the asset's own vertical extent at that column,
+ * or below a ground-like surface (terrain/floor) above it.
+ * support / sunk_into the mesh (its owning asset when it is one) that was hit
+ * on_water a water-named surface lies at/above the foot at some column: the
+ * foot is in the water (boat, jetty post) → supported, never sunk
+ * attached other assets whose AABB intersects this one's AABB + 2 cm
+ * supported gap ≤ 0.02 m or sunk
+ * floating gap > 0.05 m and not sunk (python re-derives with the indoor
+ * threshold; these booleans are for tools/humans)
+ * touches_nothing gap > 0.02 m, not sunk, attached to nothing
+ * Interpenetration: pairs of checked assets whose AABBs overlap by > 20 % of the
+ * smaller box, refined by sampling the smaller asset's vertices for containment
+ * in the larger one's meshes (parity of surfaces above the point per column) —
+ * a bench under a tree canopy is NOT an interpenetration, a crate half inside a
+ * wall is. `aabb_overlap` is the box fraction (the reported number), `inside_frac`
+ * the vertex containment that confirmed it.
+ *
+ * Exempt (listed with a reason, never scored): lights, cameras, ground / sky
+ * meshes (`backdrop.mjs` rules), enclosures whose AABB swallows the content box,
+ * instanced-only assets (scatter cannot be sampled per instance at this budget;
+ * instanced meshes are also never used as support), and anything the author tags
+ * `userData.placement = 'free'` on the asset or its zone (a bird, a hanging
+ * lantern, a drone). First 400 assets, 4 s budget; the table says when it cut.
+ *
+ * Vertical rays only, so every mesh gets a "column index": world vertices once
+ * and, above 1 500 triangles, a uniform XZ grid of triangle buckets. A column
+ * query is point-in-triangle in XZ + barycentric height — double-sided by
+ * construction (a raycaster with FrontSide materials never sees the terrain from
+ * below, which is exactly the sunk case).
+ */
+
+import { classifyBackdrop, GROUND_NAME_RE } from './backdrop.mjs';
+import { geometryTriangles } from './census.mjs';
+
+export const MAX_ASSETS = 400;
+export const TIME_BUDGET_MS = 4000;
+export const CONTACT_TOL_M = 0.02;
+export const FLOATING_M = 0.05;
+export const SUNK_M = 0.10;
+export const OVERLAP_MIN_FRAC = 0.20;
+export const WATER_RE = /\b(water|ocean|sea|lake|river|pond|pool|stream|canal)\b/i;
+const FOOT_BAND_MIN_M = 0.02;
+const FOOT_BAND_FRAC = 0.05;
+const MAX_COLUMNS = 5;
+const GRID_MIN_TRIS = 1500;
+const MAX_INDEXED_TRIS = 1500000;
+const OVERLAP_SAMPLES = 64;
+const EPS = 1e-3;
+const BARY_TOL = 1e-4;
+
+const r3 = (v) => +v.toFixed(3);
+
+/** World-space vertices + XZ triangle buckets for vertical column queries on one mesh. */
+class ColumnIndex {
+ constructor(mesh) {
+ const geo = mesh.geometry;
+ const pos = geo.attributes.position;
+ this.mesh = mesh;
+ this.tris = geometryTriangles(geo);
+ this.index = geo.index ? geo.index.array : null;
+ const n = pos.count;
+ const xyz = new Float32Array(n * 3);
+ const e = mesh.matrixWorld.elements;
+ let minx = Infinity, miny = Infinity, minz = Infinity, maxx = -Infinity, maxy = -Infinity, maxz = -Infinity;
+ for (let i = 0; i < n; i++) {
+ const x = pos.getX(i), y = pos.getY(i), z = pos.getZ(i);
+ const wx = e[0] * x + e[4] * y + e[8] * z + e[12];
+ const wy = e[1] * x + e[5] * y + e[9] * z + e[13];
+ const wz = e[2] * x + e[6] * y + e[10] * z + e[14];
+ xyz[3 * i] = wx; xyz[3 * i + 1] = wy; xyz[3 * i + 2] = wz;
+ if (wx < minx) minx = wx; if (wx > maxx) maxx = wx;
+ if (wy < miny) miny = wy; if (wy > maxy) maxy = wy;
+ if (wz < minz) minz = wz; if (wz > maxz) maxz = wz;
+ }
+ this.xyz = xyz;
+ this.count = n;
+ this.min = [minx, miny, minz];
+ this.max = [maxx, maxy, maxz];
+ this.grid = null;
+ this.kind = this.empty ? 'content' : classifyBackdrop(mesh, { min: { x: minx, y: miny, z: minz }, max: { x: maxx, y: maxy, z: maxz } });
+ this.water = isWaterLike(mesh);
+ this.groundLike = this.kind === 'ground' || GROUND_NAME_RE.test(spaced(mesh.name)) || GROUND_NAME_RE.test(spaced(nearestName(mesh)));
+ }
+
+ get empty() { return this.count === 0 || this.tris === 0 || !Number.isFinite(this.min[0]); }
+
+ containsXZ(x, z, pad = EPS) {
+ return x >= this.min[0] - pad && x <= this.max[0] + pad && z >= this.min[2] - pad && z <= this.max[2] + pad;
+ }
+
+ vertexOf(t, k) { return this.index ? this.index[3 * t + k] : 3 * t + k; }
+
+ _buildGrid() {
+ const cells = Math.min(128, Math.max(8, Math.ceil(Math.sqrt(this.tris) / 2)));
+ const sx = Math.max(1e-6, this.max[0] - this.min[0]), sz = Math.max(1e-6, this.max[2] - this.min[2]);
+ const buckets = new Array(cells * cells);
+ const xyz = this.xyz;
+ for (let t = 0; t < this.tris; t++) {
+ let cx0 = Infinity, cx1 = -Infinity, cz0 = Infinity, cz1 = -Infinity;
+ for (let k = 0; k < 3; k++) {
+ const v = this.vertexOf(t, k);
+ const x = xyz[3 * v], z = xyz[3 * v + 2];
+ if (x < cx0) cx0 = x; if (x > cx1) cx1 = x;
+ if (z < cz0) cz0 = z; if (z > cz1) cz1 = z;
+ }
+ const ix0 = Math.max(0, Math.floor((cx0 - this.min[0]) / sx * cells)), ix1 = Math.min(cells - 1, Math.floor((cx1 - this.min[0]) / sx * cells));
+ const iz0 = Math.max(0, Math.floor((cz0 - this.min[2]) / sz * cells)), iz1 = Math.min(cells - 1, Math.floor((cz1 - this.min[2]) / sz * cells));
+ for (let ix = ix0; ix <= ix1; ix++) for (let iz = iz0; iz <= iz1; iz++) {
+ const b = ix * cells + iz;
+ (buckets[b] || (buckets[b] = [])).push(t);
+ }
+ }
+ this.grid = { cells, sx, sz, buckets };
+ }
+
+ _candidates(x, z) {
+ if (this.tris <= GRID_MIN_TRIS) return null; // null = all triangles
+ if (!this.grid) this._buildGrid();
+ const g = this.grid;
+ const ix = Math.floor((x - this.min[0]) / g.sx * g.cells), iz = Math.floor((z - this.min[2]) / g.sz * g.cells);
+ if (ix < 0 || iz < 0 || ix >= g.cells || iz >= g.cells) return [];
+ return g.buckets[ix * g.cells + iz] || [];
+ }
+
+ /** Heights (world y) of every surface of this mesh crossing the vertical line at (x, z). */
+ heightsAt(x, z, out = []) {
+ if (!this.containsXZ(x, z)) return out;
+ const list = this._candidates(x, z);
+ const n = list ? list.length : this.tris;
+ const xyz = this.xyz;
+ for (let i = 0; i < n; i++) {
+ const t = list ? list[i] : i;
+ const a = this.vertexOf(t, 0), b = this.vertexOf(t, 1), c = this.vertexOf(t, 2);
+ const ax = xyz[3 * a], az = xyz[3 * a + 2], bx = xyz[3 * b], bz = xyz[3 * b + 2], cx = xyz[3 * c], cz = xyz[3 * c + 2];
+ const d = (bz - cz) * (ax - cx) + (cx - bx) * (az - cz);
+ if (Math.abs(d) < 1e-12) continue; // vertical / degenerate: never blocks a vertical line
+ const l1 = ((bz - cz) * (x - cx) + (cx - bx) * (z - cz)) / d;
+ const l2 = ((cz - az) * (x - cx) + (ax - cx) * (z - cz)) / d;
+ const l3 = 1 - l1 - l2;
+ if (l1 < -BARY_TOL || l2 < -BARY_TOL || l3 < -BARY_TOL) continue;
+ out.push(l1 * xyz[3 * a + 1] + l2 * xyz[3 * b + 1] + l3 * xyz[3 * c + 1]);
+ }
+ return out;
+ }
+
+ /** Parity test: is world point (x, y, z) inside this (closed) mesh? */
+ contains(x, y, z) {
+ const hs = this.heightsAt(x, z);
+ let above = 0;
+ for (const h of hs) if (h > y) above += 1;
+ return above % 2 === 1;
+ }
+}
+
+function boxJson(min, max) {
+ return { min: min.map(r3), max: max.map(r3), size: [max[0] - min[0], max[1] - min[1], max[2] - min[2]].map(r3) };
+}
+
+function materialNames(mesh) {
+ const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
+ return mats.map((m) => (m && (m.name || (m.map && m.map.name))) || '').join(' ');
+}
+
+function nearestName(obj) {
+ for (let o = obj; o; o = o.parent) if (o.name) return o.name;
+ return obj.type || 'mesh';
+}
+
+/** 'PondWater' / 'pond_water' → 'Pond Water' so the shared word regexes see the words. */
+function spaced(name) { return String(name || '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_\-.]+/g, ' '); }
+
+function isWaterLike(mesh) { return !!mesh && (WATER_RE.test(spaced(mesh.name)) || WATER_RE.test(spaced(materialNames(mesh))) || WATER_RE.test(spaced(nearestName(mesh)))); }
+
+/** Every visible, non-instanced Mesh with a position attribute → ColumnIndex (skipping giants). */
+function indexMeshes(scene, notes) {
+ const map = new Map();
+ scene.traverse((o) => {
+ if (!o.visible || !o.isMesh || o.isInstancedMesh || !o.geometry || !o.geometry.attributes || !o.geometry.attributes.position) return;
+ if (geometryTriangles(o.geometry) > MAX_INDEXED_TRIS) { notes.push(`skipped ${nearestName(o)}: > ${MAX_INDEXED_TRIS} triangles`); return; }
+ const ci = new ColumnIndex(o);
+ if (!ci.empty) map.set(o, ci);
+ });
+ return map;
+}
+
+function isFree(obj) { return !!(obj && obj.userData && obj.userData.placement === 'free'); }
+
+/** The placed assets: direct children of each top-level scene child (or a top-level mesh itself). */
+function collectAssets(scene, indices, contentBox) {
+ const assets = [];
+ let total = 0;
+ const seen = new Set();
+ for (const zone of scene.children) {
+ if (!zone.visible || zone.isLight || zone.isCamera) continue;
+ const children = zone.isMesh || zone.isInstancedMesh ? [zone] : zone.children;
+ for (const child of children) {
+ if (!child.visible || child.isLight || child.isCamera || seen.has(child)) continue;
+ seen.add(child);
+ const meshes = [];
+ let instanced = 0;
+ child.traverse((o) => { if (!o.visible) return; if (o.isInstancedMesh) instanced += 1; else if (indices.has(o)) meshes.push(indices.get(o)); });
+ if (!meshes.length && !instanced) continue;
+ total += 1;
+ if (assets.length >= MAX_ASSETS) continue;
+ const a = { obj: child, name: child.name || `${child.type}_${total}`, zone: zone === child ? '' : (zone.name || zone.type), meshes, instanced, exempt: '' };
+ if (isFree(zone) || isFree(child)) a.exempt = 'free';
+ else if (!meshes.length) a.exempt = 'instanced';
+ else {
+ a.min = [Infinity, Infinity, Infinity]; a.max = [-Infinity, -Infinity, -Infinity];
+ let backdrop = 0;
+ for (const ci of meshes) {
+ for (let k = 0; k < 3; k++) { a.min[k] = Math.min(a.min[k], ci.min[k]); a.max[k] = Math.max(a.max[k], ci.max[k]); }
+ // a ground / floor / water surface is what things sit ON, whatever its size
+ if (ci.kind !== 'content' || ci.groundLike || ci.water) backdrop += 1;
+ }
+ if (backdrop === meshes.length || GROUND_NAME_RE.test(spaced(a.name)) || WATER_RE.test(spaced(a.name))) a.exempt = 'backdrop';
+ else if (contentBox && enclosesContent(a, contentBox)) a.exempt = 'enclosure';
+ }
+ assets.push(a);
+ }
+ }
+ return { assets, total };
+}
+
+function enclosesContent(a, cb) {
+ const span = Math.max(a.max[0] - a.min[0], a.max[2] - a.min[2]);
+ const cspan = Math.max(cb.max[0] - cb.min[0], cb.max[2] - cb.min[2]);
+ const inside = [0, 1, 2].every((k) => a.min[k] <= cb.min[k] + EPS && a.max[k] >= cb.max[k] - EPS);
+ return inside && span > 2 * Math.max(cspan, 1);
+}
+
+/** Up to MAX_COLUMNS foot columns [x, y, z] from the asset's lowest vertices. */
+function footColumns(a) {
+ const band = a.min[1] + Math.max(FOOT_BAND_MIN_M, FOOT_BAND_FRAC * (a.max[1] - a.min[1]));
+ let lowest = null, minx = null, maxx = null, minz = null, maxz = null;
+ for (const ci of a.meshes) {
+ const xyz = ci.xyz;
+ for (let i = 0; i < ci.count; i++) {
+ const y = xyz[3 * i + 1];
+ if (y > band) continue;
+ const p = [xyz[3 * i], y, xyz[3 * i + 2]];
+ if (!lowest || y < lowest[1]) lowest = p;
+ if (!minx || p[0] < minx[0]) minx = p;
+ if (!maxx || p[0] > maxx[0]) maxx = p;
+ if (!minz || p[2] < minz[2]) minz = p;
+ if (!maxz || p[2] > maxz[2]) maxz = p;
+ }
+ }
+ const out = [];
+ for (const p of [lowest, minx, maxx, minz, maxz]) {
+ if (!p) continue;
+ if (out.some((q) => Math.hypot(q[0] - p[0], q[2] - p[2]) < 0.01)) continue;
+ out.push(p);
+ if (out.length >= MAX_COLUMNS) break;
+ }
+ return out;
+}
+
+/** One column: nearest other surface below the foot, nearest above, own top. */
+function probeColumn(a, col, indices, owner, groundY) {
+ const [x, y0, z] = col;
+ let y1 = y0;
+ for (const ci of a.meshes) for (const h of ci.heightsAt(x, z)) if (h > y1) y1 = h;
+ let below = null, above = null, onWater = false;
+ for (const ci of indices.values()) {
+ if (a.meshSet.has(ci) || ci.kind === 'sky' || !ci.containsXZ(x, z)) continue;
+ if (ci.min[1] > a.max[1] + EPS) continue; // entirely above the asset: cannot support or bury it
+ // only something that STARTS below the foot can bury it (terrain, a floor slab, a table
+ // under a badly stacked crate); a neighbour standing at the same level is a lateral
+ // overlap and belongs to the interpenetration pass
+ const startsBelow = ci.min[1] < y0 - EPS || ci.groundLike;
+ for (const h of ci.heightsAt(x, z)) {
+ // a foot at or under a water surface is IN the water: boats, jetty posts, reeds —
+ // whatever is below the surface is invisible, so neither floating nor sunk applies
+ if (ci.water && h >= y0 - EPS) onWater = true;
+ if (h <= y0 + EPS) { if (!below || h > below.y) below = { y: h, ci }; } else if (startsBelow && (!above || h < above.y)) above = { y: h, ci };
+ }
+ }
+ const res = { gap: below ? y0 - below.y : (groundY === null ? null : y0 - groundY),
+ support: below ? owner(below.ci.mesh) : (groundY === null ? '' : 'ground_y'), water: onWater, sunk: 0, into: '' };
+ if (above && (above.y <= y1 + EPS || above.ci.groundLike)) {
+ res.sunk = above.y - y0; res.into = owner(above.ci.mesh);
+ if (!below) { res.gap = -res.sunk; res.support = res.into; } // under a surface with nothing beneath: gap is "that far under"
+ }
+ return res;
+}
+
+function boxOverlapFrac(a, b) {
+ const size = (o) => [0, 1, 2].map((k) => Math.max(0.01, o.max[k] - o.min[k]));
+ const sa = size(a), sb = size(b);
+ let vol = 1;
+ for (let k = 0; k < 3; k++) {
+ const ov = Math.min(a.min[k] + sa[k], b.min[k] + sb[k]) - Math.max(a.min[k], b.min[k]);
+ if (ov <= 0) return 0;
+ vol *= ov;
+ }
+ return vol / Math.min(sa[0] * sa[1] * sa[2], sb[0] * sb[1] * sb[2]);
+}
+
+function touches(a, b, tol) {
+ return [0, 1, 2].every((k) => a.min[k] - tol <= b.max[k] && b.min[k] - tol <= a.max[k]);
+}
+
+/** Fraction of the smaller asset's sampled vertices inside the larger one's meshes. */
+function containment(small, large) {
+ const total = small.meshes.reduce((n, ci) => n + ci.count, 0);
+ const stride = Math.max(1, Math.floor(total / OVERLAP_SAMPLES));
+ let sampled = 0, inside = 0;
+ for (const ci of small.meshes) {
+ for (let i = 0; i < ci.count; i += stride) {
+ const x = ci.xyz[3 * i], y = ci.xyz[3 * i + 1], z = ci.xyz[3 * i + 2];
+ sampled += 1;
+ if (x < large.min[0] || x > large.max[0] || y < large.min[1] || y > large.max[1] || z < large.min[2] || z > large.max[2]) continue;
+ if (large.meshes.some((lc) => lc.contains(x, y, z))) inside += 1;
+ }
+ }
+ return { frac: sampled ? inside / sampled : 0, sampled };
+}
+
+function pairs(checked) {
+ const out = [];
+ for (let i = 0; i < checked.length; i++) {
+ for (let j = i + 1; j < checked.length; j++) {
+ const a = checked[i], b = checked[j];
+ if (!touches(a, b, CONTACT_TOL_M)) continue;
+ a.attached.push(b.name); b.attached.push(a.name);
+ const aabb = boxOverlapFrac(a, b);
+ if (aabb <= OVERLAP_MIN_FRAC) continue;
+ const vol = (o) => [0, 1, 2].reduce((v, k) => v * Math.max(0.01, o.max[k] - o.min[k]), 1);
+ const [small, large] = vol(a) <= vol(b) ? [a, b] : [b, a];
+ const c = containment(small, large);
+ if (c.frac > OVERLAP_MIN_FRAC) out.push({ a: small.name, b: large.name, zone_a: small.zone, zone_b: large.zone, aabb_overlap: r3(aabb), inside_frac: r3(c.frac), samples: c.sampled });
+ }
+ }
+ return out.sort((x, y) => y.overlap - x.overlap).slice(0, 40);
+}
+
+/**
+ * The placement table for `scene`.
+ * @param {THREE.Scene} scene
+ * @param {object} THREE unused today (kept for symmetry with sceneCensus)
+ * @param {{groundY?: number|null, contentBox?: {min:number[], max:number[]}|null}} opts
+ */
+export function placementTable(scene, THREE, opts = {}) {
+ const t0 = Date.now();
+ const groundY = Number.isFinite(opts.groundY) ? opts.groundY : null;
+ const notes = [];
+ scene.updateMatrixWorld(true);
+ const indices = indexMeshes(scene, notes);
+ const { assets, total } = collectAssets(scene, indices, opts.contentBox || null);
+ const meshOwner = new Map();
+ for (const a of assets) { a.meshSet = new Set(a.meshes); for (const ci of a.meshes) meshOwner.set(ci.mesh, a.name); }
+ const owner = (mesh) => meshOwner.get(mesh) || nearestName(mesh);
+ const checked = [];
+ let timeCut = false;
+ const rows = [];
+ for (const a of assets) {
+ const row = { name: a.name, zone: a.zone, meshes: a.meshes.length, instanced: a.instanced, exempt: a.exempt,
+ bbox: a.min ? boxJson(a.min, a.max) : null };
+ if (a.exempt) { rows.push(row); continue; }
+ if (Date.now() - t0 > TIME_BUDGET_MS) { row.exempt = 'time_budget'; timeCut = true; rows.push(row); continue; }
+ const cols = footColumns(a);
+ let best = null, sunk = null, water = false;
+ for (const col of cols) {
+ const r = probeColumn(a, col, indices, owner, groundY);
+ if (r.gap !== null && (!best || r.gap < best.gap)) best = r;
+ if (r.sunk > 0 && (!sunk || r.sunk > sunk.sunk)) sunk = r;
+ if (r.water) water = true; // one foot in the water is enough: a jetty is half on the shore
+ }
+ a.attached = [];
+ a.row = row;
+ Object.assign(row, {
+ columns: cols.length,
+ ground_gap_m: best ? r3(best.gap) : null,
+ support: best ? best.support : '',
+ sunk_m: sunk ? r3(sunk.sunk) : 0,
+ sunk_into: sunk ? sunk.into : '',
+ on_water: water,
+ });
+ checked.push(a);
+ rows.push(row);
+ }
+ const inter = pairs(checked);
+ for (const a of checked) {
+ const row = a.row;
+ row.attached = a.attached.slice(0, 8);
+ const gap = row.ground_gap_m === null ? 0 : row.ground_gap_m;
+ row.supported = gap <= CONTACT_TOL_M || row.sunk_m > 0 || row.on_water;
+ row.floating = gap > FLOATING_M && row.sunk_m === 0 && !row.on_water;
+ row.touches_nothing = gap > CONTACT_TOL_M && row.sunk_m === 0 && !row.on_water && a.attached.length === 0;
+ }
+ const exempt = {};
+ for (const r of rows) if (r.exempt) exempt[r.exempt] = (exempt[r.exempt] || 0) + 1;
+ return {
+ version: 1, assets: rows, interpenetrations: inter, total, checked: checked.length,
+ truncated: total > assets.length || timeCut, truncated_by_time: timeCut, exempt,
+ thresholds: { contact_m: CONTACT_TOL_M, floating_m: FLOATING_M, sunk_m: SUNK_M, overlap_min: OVERLAP_MIN_FRAC },
+ ground_y: groundY, notes, duration_ms: Date.now() - t0,
+ };
+}
diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjs
index ddcbb84f..863685e6 100644
--- a/harness/runtime_js/lib/scene_host.mjs
+++ b/harness/runtime_js/lib/scene_host.mjs
@@ -15,6 +15,7 @@
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { sceneCensus } from './host_census.mjs';
+import { placementTable } from './host_placement.mjs';
import { frameStats, nearGeometry } from './host_metrics.mjs';
import { frameCoverage } from './host_coverage.mjs';
import { installShaderErrorHook } from './host_shader_errors.mjs';
@@ -388,6 +389,16 @@ function fps(seconds, spec) {
return { fps: frames / Math.max(elapsed, 1e-3), frames, seconds: elapsed, draw_calls: r.calls, triangles: r.triangles };
}
+/** Per-asset placement table (host_placement.mjs) — never throws: a failure is `{error}`. */
+function placement() {
+ try {
+ const c = sceneCensus(state.scene, THREE);
+ return placementTable(state.scene, THREE, { groundY: c.ground_y, contentBox: c.content_bbox });
+ } catch (e) {
+ return { error: String((e && e.message) || e).slice(0, 400) };
+ }
+}
+
function census() {
const c = sceneCensus(state.scene, THREE);
c.glb_assets = glbUsage(state.scene);
@@ -404,6 +415,7 @@ window.__c3v = {
cameraChecks,
compileAll,
census,
+ placement,
fps,
setViewport(w, h) { state.width = w; state.height = h; state.renderer.setSize(w, h, false); },
shaderErrors: () => state.shaderErrors.slice(),
diff --git a/harness/runtime_js/probe_scene.mjs b/harness/runtime_js/probe_scene.mjs
index 1ecbae46..5393a0d3 100644
--- a/harness/runtime_js/probe_scene.mjs
+++ b/harness/runtime_js/probe_scene.mjs
@@ -65,6 +65,13 @@ async function main() {
try {
if (boot.ok) {
result.census = await page.evaluate(() => window.__c3v.census());
+ // placement table (floating / sunken / unsupported / interpenetration per asset);
+ // a failure here must never fail the probe — the python gate reports it as a WARN
+ try {
+ result.census.placement = await page.evaluate(() => window.__c3v.placement());
+ } catch (e) {
+ result.census.placement = { error: String((e && e.message) || e).slice(0, 400) };
+ }
// exercise update() for a few fixed steps and one tiny render (lazy programs compile)
const steps = parseInt(args['update-steps'], 10);
const upd = await page.evaluate((n) => {
diff --git a/harness/tests/flywheel_cli/test_bench.py b/harness/tests/flywheel_cli/test_bench.py
index 544490c6..41fd5c3c 100644
--- a/harness/tests/flywheel_cli/test_bench.py
+++ b/harness/tests/flywheel_cli/test_bench.py
@@ -28,7 +28,8 @@ def test_batteries_are_valid(path: Path):
assert len(ids) == len(set(ids))
tiers = {p.tier for p in b.prompts}
assert tiers <= {"easy", "medium", "hard"}
- assert all(p.must_have for p in b.prompts)
+ # head-to-head batteries keep the other side's brief verbatim: no must items by design (bench/h2h_*.py)
+ assert all(p.must_have for p in b.prompts) or b.name.startswith("h2h_")
expected = {"static_objects_v1": 24, "articulated_v1": 12, "scenes_v1": 12}
if b.name in expected: # other batteries (compare_*, *_v2) are owned elsewhere; only the schema is checked
assert len(tiers) == 3 # v1 batteries span all three tiers; v2 drops easy (it saturated)
diff --git a/harness/tests/judges/test_caps.py b/harness/tests/judges/test_caps.py
index 1ae599ae..92d697a3 100644
--- a/harness/tests/judges/test_caps.py
+++ b/harness/tests/judges/test_caps.py
@@ -94,3 +94,22 @@ def test_a_real_floating_part_still_caps():
assert not measured_absent(rubric, "floating_part", failed)
assert not measured_absent(rubric, "floating_part", []), "a gate that did not run measured nothing"
assert not measured_absent(rubric, "wrong_object", [_connectivity(True)]), "no gate measures 'wrong object'"
+
+
+def test_scene_placement_gate_measures_the_floating_asset_claim():
+ """scene_v1 (2026-08-26): the placement gate and the checklist defect share an id, so a passed
+ gate vetoes the VLM's floating/sunken claim and an ERROR there caps the round at 0.7."""
+ from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+ from codeverse.judges.caps import apply_caps, measured_absent
+ from codeverse.judges.rubrics import load_rubric
+
+ rubric = load_rubric("scene_v1")
+ passed = [GateReport(gate="scene_placement", passed=True, findings=[GateFinding(
+ gate="scene_placement", severity=Severity.INFO, target="scene", message="13 assets checked: 0 floating, 0 sunken")])]
+ assert measured_absent(rubric, "floating_or_sunken_asset", passed)
+ failed = [GateReport(gate="scene_placement", passed=False, findings=[GateFinding(
+ gate="scene_placement", severity=Severity.ERROR, target="Pondside/Lantern", message="Pondside/Lantern is floating 0.30 m above PondWater")])]
+ assert not measured_absent(rubric, "floating_or_sunken_asset", failed)
+ res = apply_caps(rubric, 0.9, failed, {}, [], defects_present={})
+ assert res.overall == 0.6, "the older floating_part rule (gate *, cap 0.6) fires too; the tighter cap wins"
+ assert any(c.rule == "floating_or_sunken_asset" for c in res.caps_applied)
diff --git a/harness/tests/scene_gates/test_placement.py b/harness/tests/scene_gates/test_placement.py
new file mode 100644
index 00000000..cb90282e
--- /dev/null
+++ b/harness/tests/scene_gates/test_placement.py
@@ -0,0 +1,178 @@
+"""scene_placement gate (2026-08-26): census placement table → findings, hints, caps, routing.
+
+Pure python over a fake census dict — the node-level measurement is exercised in
+``tests/scene_runtime/test_placement_census.py``.
+"""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+from codeverse.contracts.artifacts import BuildResult, Severity
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import BBox, CameraPlan, ScenePlan, ZonePlan
+from codeverse.judges.caps import apply_caps
+from codeverse.judges.rubrics import load_rubric
+from codeverse.orchestrator.rounds import build_refine_instructions
+from codeverse.spatial.scene_placement import (
+ GATE,
+ check_placement,
+ infer_indoor,
+ placement_findings,
+ placement_gate_safe,
+ placement_table_text,
+)
+from codeverse.tracks.prompting import file_for_target_factory
+from codeverse.tracks.scene import ScenePipeline
+
+
+def _row(name, zone="Yard", gap=0.0, support="Ground", sunk=0.0, into="", water=False, attached=(), h=1.0, exempt=""):
+ return {"name": name, "zone": zone, "exempt": exempt, "meshes": 1, "columns": 3,
+ "bbox": {"min": [0, 0, 0], "max": [1, h, 1], "size": [1, h, 1]}, "ground_gap_m": gap, "support": support,
+ "sunk_m": sunk, "sunk_into": into, "on_water": water, "attached": list(attached)}
+
+
+def _table(*rows, pairs=(), **over):
+ t = {"assets": list(rows), "interpenetrations": list(pairs), "total": len(rows),
+ "checked": sum(1 for r in rows if not r["exempt"]), "truncated": False, "exempt": {}, "ground_y": 0.0, "notes": []}
+ t.update(over)
+ return t
+
+
+def _by_kind(report, kind):
+ return [f for f in report.findings if f.data.get("kind") == kind]
+
+
+def test_supported_and_exempt_rows_pass_with_a_summary_line():
+ r = placement_findings(_table(_row("Crate"), _row("Bird", exempt="free"), _row("Ground", zone="Environment", exempt="backdrop")))
+ assert r.gate == GATE and r.passed
+ assert [f.data["kind"] for f in r.findings] == ["summary"]
+ assert "1 assets checked (3 placed" in r.findings[0].message and "0 floating, 0 sunken" in r.findings[0].message
+
+
+def test_floating_severity_by_gap_then_by_count():
+ r = placement_findings(_table(_row("Lantern", gap=0.3), _row("Cup", gap=0.08, support="Table")))
+ fl = _by_kind(r, "floating")
+ assert {f.target: f.severity for f in fl} == {"Yard/Lantern": Severity.ERROR, "Yard/Cup": Severity.WARN}
+ lantern = next(f for f in fl if f.target == "Yard/Lantern")
+ assert "floating 0.30 m above Ground" in lantern.message and "lower Yard/Lantern by 0.30 m" in lantern.fix_hint
+ assert "userData.placement = 'free'" in lantern.fix_hint
+ assert not r.passed
+ # more than FLOATING_ERROR_COUNT small hovers → every one is an ERROR
+ many = placement_findings(_table(*[_row(f"P{i}", gap=0.07) for i in range(4)]))
+ assert all(f.severity == Severity.ERROR for f in _by_kind(many, "floating")) and not many.passed
+
+
+def test_floating_but_attached_is_only_a_warning():
+ r = placement_findings(_table(_row("Sign", gap=0.9, attached=("Post",))))
+ (f,) = _by_kind(r, "floating")
+ assert f.severity == Severity.WARN and "touches Post" in f.message and "mounted on Post" in f.fix_hint
+ assert r.passed
+
+
+def test_indoor_tolerance_is_tighter():
+ t = _table(_row("Vase", gap=0.03, support="Table"))
+ assert _by_kind(placement_findings(t, indoor=False), "floating") == []
+ assert _by_kind(placement_findings(t, indoor=False), "unsupported")[0].severity == Severity.WARN
+ assert _by_kind(placement_findings(t, indoor=True), "floating")[0].severity == Severity.WARN
+ assert infer_indoor("a cosy cabin interior at dusk") and not infer_indoor("mountain meadow at dawn")
+
+
+def test_sunken_thresholds_height_fraction_and_name_words():
+ r = placement_findings(_table(
+ _row("Bench", sunk=0.15, into="Terrain", h=0.9), # WARN: > 0.10 m
+ _row("Statue", sunk=0.35, into="Terrain", h=2.0), # WARN: > 0.30 m but only 17 % of its height
+ _row("Lantern", sunk=0.4, into="Terrain", h=0.6), # ERROR: > 0.30 m and > 25 %
+ _row("Rock", sunk=0.45, into="Terrain", h=1.2), # starter-scene rock: 37 % buried is fine
+ _row("Boulder", sunk=0.8, into="Terrain", h=1.0), # 80 % buried → ERROR even for a rock
+ _row("PondBasin", sunk=1.4, into="Terrain", h=1.2), # dug in by definition
+ _row("Jetty", sunk=0.97, into="Terrain", h=1.1, water=True), # posts in the pond bed
+ ))
+ sev = {f.target: f.severity for f in _by_kind(r, "sunken")}
+ assert sev == {"Yard/Bench": Severity.WARN, "Yard/Statue": Severity.WARN, "Yard/Lantern": Severity.ERROR, "Yard/Boulder": Severity.ERROR}
+ lantern = next(f for f in r.findings if f.target == "Yard/Lantern")
+ assert "sunken 0.40 m into Terrain" in lantern.message and "raise Yard/Lantern by 0.40 m" in lantern.fix_hint
+
+
+def test_interpenetration_pairs_and_error_above_sixty_percent():
+ pairs = [{"a": "CrateA", "b": "CrateB", "zone_a": "Yard", "zone_b": "Yard", "aabb_overlap": 0.5, "inside_frac": 0.25, "samples": 24},
+ {"a": "Post", "b": "Wall", "zone_a": "Yard", "zone_b": "House", "aabb_overlap": 0.9, "inside_frac": 0.6, "samples": 16}]
+ r = placement_findings(_table(_row("CrateA"), _row("CrateB"), pairs=pairs))
+ inter = _by_kind(r, "interpenetration")
+ # worst first: ERROR before WARN
+ assert [(f.target, f.severity) for f in inter] == [("Yard/Post", Severity.ERROR), ("Yard/CrateA", Severity.WARN)]
+ assert "interpenetration: Yard/CrateA and Yard/CrateB overlap (50%" in inter[1].message
+ assert "move Yard/Post out of House/Wall" in inter[0].fix_hint
+
+
+def test_findings_are_capped_per_kind_and_the_summary_counts_them():
+ r = placement_findings(_table(*[_row(f"Pebble{i}", gap=0.06 + i * 0.01) for i in range(12)]))
+ fl = _by_kind(r, "floating")
+ assert len(fl) == 8 and fl[0].data["gap_m"] >= fl[-1].data["gap_m"] # worst first
+ assert any(f.data.get("kind") == "truncated" and "4 more floating" in f.message for f in r.findings)
+ assert "8 floating" in r.findings[0].message
+
+
+def test_probe_error_is_a_warning_that_passes():
+ r = placement_findings({"error": "boom"})
+ assert r.passed and r.findings[0].severity == Severity.WARN and "placement probe failed: boom" in r.findings[0].message
+
+
+def test_scene_v1_floating_part_cap_fires_on_a_placement_error():
+ rubric = load_rubric("scene_v1")
+ floating = placement_findings(_table(_row("Lantern", gap=0.3)))
+ res = apply_caps(rubric, 0.9, [floating], {}, [])
+ assert res.overall == 0.6 and {c.rule for c in res.caps_applied} == {"floating_part", "floating_or_sunken_asset"}
+ assert "Lantern" in res.caps_applied[0].evidence
+ sunken = placement_findings(_table(_row("Lantern", sunk=0.4, into="Terrain", h=0.6)))
+ assert apply_caps(rubric, 0.9, [sunken], {}, []).overall == 0.6
+ # WARN-level findings (a mounted sign, a small hover) never cap
+ warn = placement_findings(_table(_row("Sign", gap=0.9, attached=("Post",)), _row("Cup", gap=0.08)))
+ assert apply_caps(rubric, 0.9, [warn], {}, []).overall == 0.9
+
+
+def _plan():
+ bb = BBox(center=(0, 0, 0), extents=(10, 5, 10))
+ return ScenePlan(title="t", summary="s", setting="meadow", mood="calm", bounds=bb, environment="sunny",
+ zones=[ZonePlan(name="Yard", description="d", bbox=bb, contents=[]), ZonePlan(name="House", description="d", bbox=bb, contents=[])],
+ assets=[], cameras=[CameraPlan(name="overview", position=(1, 1, 1), look_at=(0, 0, 0), fov=50, purpose="p")],
+ animation=[], effects=[])
+
+
+def test_error_findings_become_zone_routed_refine_tasks_one_per_asset():
+ plan = _plan()
+ r = placement_findings(_table(_row("Lantern", gap=0.3), _row("Bench", gap=0.4), _row("Vase", zone="House", gap=0.5)))
+ ctx = SimpleNamespace(runtime=SimpleNamespace(), plan=plan, language=Language.SCENE_THREEJS)
+ tasks = build_refine_instructions(None, [r], [], plan, file_for_target=file_for_target_factory(ctx))
+ assert sorted((t.target, tuple(t.files)) for t in tasks) == [("House/Vase", ("src/zones/house.js",)), ("Yard/Bench", ("src/zones/yard.js",)),
+ ("Yard/Lantern", ("src/zones/yard.js",))]
+ assert all(t.kind == f"gate:{GATE}" and "lower " in t.instruction for t in tasks)
+
+
+def test_pipeline_gates_append_placement_after_census_and_never_raise():
+ plan = _plan()
+ ctx = SimpleNamespace(runtime=SimpleNamespace(), plan=plan)
+ build = BuildResult(ok=True, language="scene_threejs", census={"totals": {"meshes": 3}, "placement": _table(_row("Lantern", gap=0.3))})
+ gates = ScenePipeline().gates(ctx, 0, build, None)
+ assert [g.gate for g in gates] == ["scene_census", GATE] and not gates[-1].passed
+ # no table (scene did not boot / old driver) → no placement gate at all
+ assert [g.gate for g in ScenePipeline().gates(ctx, 0, BuildResult(ok=False, language="scene_threejs", census={}), None)] == []
+ # a broken table is a WARN, not an exception
+ broken = placement_gate_safe({"placement": {"assets": [{"no_name": 1}]}}, plan=plan)
+ assert broken is not None and broken.passed and "placement probe failed" in broken.findings[0].message
+ assert placement_gate_safe({}, plan=plan) is None
+
+
+def test_check_placement_reads_the_last_census_and_the_table_text(tmp_path):
+ from codeverse.workspace import Workspace
+
+ ws = Workspace(tmp_path / "run").create()
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ table = _table(_row("Lantern", gap=0.3), _row("Rock", sunk=0.3, into="Terrain", h=1.0))
+ (ws.artifacts / "census.json").write_text(json.dumps({"totals": {}, "placement": table}))
+ ws.plan_path.write_text(json.dumps({"setting": "a cabin interior", "environment": "", "title": "x"}))
+ r = check_placement(ws)
+ assert not r.passed and "indoor tolerance 2 cm" in r.findings[0].message
+ text = placement_table_text(table)
+ assert "Yard/Lantern | +0.300 | Ground | 0.000 | - | - | -" in text and "Yard/Rock | +0.000 | Ground | 0.300 | Terrain" in text
diff --git a/harness/tests/scene_runtime/test_placement_census.py b/harness/tests/scene_runtime/test_placement_census.py
new file mode 100644
index 00000000..5edef80d
--- /dev/null
+++ b/harness/tests/scene_runtime/test_placement_census.py
@@ -0,0 +1,120 @@
+"""Node-level placement table (``runtime_js/lib/host_placement.mjs`` via the census).
+
+A tiny synthetic scene drives ``sceneCensus(scene, THREE, {placement: true})``
+directly (no browser): a box on a ground plane (supported), a box 0.3 m up
+(floating), a box 0.5 m down (sunk), two half-overlapping boxes (interpenetration),
+a ``userData.placement = 'free'`` box (exempt) — plus the cases that produced false
+positives on the starter scene on 2026-08-26: a table with legs and a cup on it, a
+chair under the table, a bench under a tree canopy, a boat on a water plane, a
+half-buried rock, a sky dome and an instanced scatter.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.config import get_settings
+from tests.scene_runtime.conftest import needs_node, run_node_json
+
+pytestmark = [pytest.mark.node, needs_node]
+
+RUNTIME_JS = get_settings().runtime_js_dir()
+
+SCENE_JS = """
+import * as THREE from 'three';
+import { sceneCensus } from './lib/host_census.mjs';
+const mat = new THREE.MeshStandardMaterial();
+const box = (name, sx, sy, sz, x, y, z) => { const m = new THREE.Mesh(new THREE.BoxGeometry(sx, sy, sz), mat); m.name = name; m.position.set(x, y + sy / 2, z); return m; };
+const scene = new THREE.Scene();
+const env = new THREE.Group(); env.name = 'Environment'; scene.add(env);
+const ground = new THREE.Mesh(new THREE.PlaneGeometry(60, 60, 64, 64), mat); ground.name = 'Ground'; ground.rotation.x = -Math.PI / 2; env.add(ground);
+const sky = new THREE.Mesh(new THREE.SphereGeometry(600, 16, 8), mat); sky.name = 'SkyDome'; env.add(sky);
+const pond = new THREE.Mesh(new THREE.PlaneGeometry(10, 10), mat); pond.rotation.x = -Math.PI / 2; pond.position.set(-20, 0.2, -20);
+const pondGroup = new THREE.Group(); pondGroup.name = 'PondWater'; pondGroup.add(pond); env.add(pondGroup);
+env.add(new THREE.DirectionalLight());
+const zone = new THREE.Group(); zone.name = 'Yard'; scene.add(zone);
+zone.add(box('Crate', 1, 1, 1, 0, 0, 0));
+zone.add(box('Lantern', 0.4, 0.6, 0.4, 5, 0.3, 0));
+zone.add(box('Anvil', 1, 1, 1, -5, -0.5, 0));
+zone.add(box('CrateA', 1, 1, 1, 10, 0, 0));
+zone.add(box('CrateB', 1, 1, 1, 10.5, 0, 0));
+const bird = box('Bird', 0.3, 0.2, 0.3, 0, 4, 5); bird.userData.placement = 'free'; zone.add(bird);
+const table = new THREE.Group(); table.name = 'Table'; table.position.set(-10, 0, 5);
+for (const [lx, lz] of [[-0.6, -0.3], [0.6, -0.3], [-0.6, 0.3], [0.6, 0.3]]) table.add(box('Leg', 0.05, 0.72, 0.05, lx, 0, lz));
+table.add(box('Top', 1.4, 0.03, 0.8, 0, 0.72, 0)); zone.add(table);
+zone.add(box('Cup', 0.08, 0.1, 0.08, -10, 0.75, 5));
+zone.add(box('Chair', 0.4, 0.45, 0.4, -10, 0, 5.2));
+const tree = new THREE.Group(); tree.name = 'Tree'; tree.position.set(15, 0, 15);
+tree.add(box('Trunk', 0.3, 2, 0.3, 0, 0, 0)); tree.add(box('Canopy', 4, 3, 4, 0, 2, 0)); zone.add(tree);
+zone.add(box('Bench', 1.6, 0.9, 0.5, 16, 0, 15));
+zone.add(box('Boat', 2, 0.6, 0.8, -20, 0.0, -20));
+const rock = new THREE.Mesh(new THREE.DodecahedronGeometry(0.6, 1), mat); rock.name = 'Rock'; rock.position.set(8, 0.2, -8); zone.add(rock);
+const inst = new THREE.InstancedMesh(new THREE.BoxGeometry(0.2, 0.2, 0.2), mat, 50); inst.name = 'Pebbles'; zone.add(inst);
+scene.updateMatrixWorld(true);
+const c = sceneCensus(scene, THREE, { placement: true });
+console.log(JSON.stringify({ ground_y: c.ground_y, placement: c.placement, plain_has_placement: 'placement' in sceneCensus(scene, THREE) }));
+"""
+
+
[email protected](scope="module")
+def table() -> dict:
+ out = run_node_json(SCENE_JS.replace("'./lib/", f"'{RUNTIME_JS}/lib/"))
+ assert out["ground_y"] == 0 and out["plain_has_placement"] is False # the render-time census stays cheap
+ return out["placement"]
+
+
+def _row(table, name):
+ rows = [a for a in table["assets"] if a["name"] == name]
+ assert len(rows) == 1, (name, [a["name"] for a in table["assets"]])
+ return rows[0]
+
+
+def test_counts_exemptions_and_budget(table):
+ assert table["total"] == 17 and table["checked"] == 12 and table["truncated"] is False
+ assert table["exempt"] == {"backdrop": 3, "free": 1, "instanced": 1}
+ assert {a["name"] for a in table["assets"] if a["exempt"] == "backdrop"} == {"Ground", "SkyDome", "PondWater"}
+ assert _row(table, "Bird")["exempt"] == "free" and _row(table, "Pebbles")["exempt"] == "instanced"
+ assert table["duration_ms"] < 2000 and table["notes"] == []
+ assert table["thresholds"] == {"contact_m": 0.02, "floating_m": 0.05, "sunk_m": 0.1, "overlap_min": 0.2}
+
+
+def test_supported_floating_and_sunk_boxes(table):
+ crate = _row(table, "Crate")
+ assert crate["zone"] == "Yard" and crate["ground_gap_m"] == 0 and crate["support"] == "Ground" and crate["supported"]
+ assert crate["bbox"] == {"min": [-0.5, 0, -0.5], "max": [0.5, 1, 0.5], "size": [1, 1, 1]}
+ lantern = _row(table, "Lantern")
+ assert lantern["ground_gap_m"] == pytest.approx(0.3, abs=1e-3) and lantern["floating"] and lantern["touches_nothing"]
+ assert lantern["support"] == "Ground" and lantern["sunk_m"] == 0 and not lantern["supported"]
+ anvil = _row(table, "Anvil")
+ assert anvil["sunk_m"] == pytest.approx(0.5, abs=1e-3) and anvil["sunk_into"] == "Ground" and anvil["ground_gap_m"] == pytest.approx(-0.5, abs=1e-3)
+ assert anvil["supported"] and not anvil["floating"]
+
+
+def test_interpenetration_is_a_pair_not_a_burial(table):
+ pairs = table["interpenetrations"]
+ assert [(p["a"], p["b"], p["aabb_overlap"]) for p in pairs] == [("CrateA", "CrateB", 0.5)]
+ assert pairs[0]["inside_frac"] > 0.2 and pairs[0]["zone_a"] == "Yard"
+ for name in ("CrateA", "CrateB"):
+ r = _row(table, name)
+ assert r["sunk_m"] == 0 and r["ground_gap_m"] == 0 and r["attached"] == ["CrateB" if name == "CrateA" else "CrateA"]
+
+
+def test_no_false_positives_on_legitimate_placements(table):
+ """Table legs (not its top) are the feet; a cup on the table sits on 'Table'; a chair under
+ the table top is not 'sunk into' it; a bench under a canopy is not an interpenetration;
+ a boat with its hull under the water surface is on_water; a rock 0.4 m under the terrain
+ reports its burial (python decides whether a rock may sit that deep)."""
+ for name, support in (("Table", "Ground"), ("Cup", "Table"), ("Chair", "Ground"), ("Tree", "Ground"), ("Bench", "Ground")):
+ r = _row(table, name)
+ assert r["ground_gap_m"] == pytest.approx(0, abs=1e-3) and r["support"] == support and r["sunk_m"] == 0, (name, r)
+ assert not r["floating"] and not r["touches_nothing"]
+ assert _row(table, "Chair")["attached"] == ["Table"] and _row(table, "Bench")["attached"] == ["Tree"]
+ boat = _row(table, "Boat")
+ assert boat["on_water"] and boat["supported"] and not boat["floating"] and boat["sunk_into"] == "PondWater"
+ rock = _row(table, "Rock")
+ assert rock["sunk_into"] == "Ground" and 0.3 < rock["sunk_m"] < 0.5 and not rock["floating"]
+
+
+def test_time_and_size_limits_are_declared():
+ src = (RUNTIME_JS / "lib" / "host_placement.mjs").read_text()
+ assert "export const MAX_ASSETS = 400;" in src and "TIME_BUDGET_MS = 4000" in src
diff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.py
index ff313230..70c3f345 100644
--- a/harness/tests/spatial_tools/test_tools.py
+++ b/harness/tests/spatial_tools/test_tools.py
@@ -27,7 +27,7 @@ CORE_TOOLS = {"build", "measure", "render_views", "render_sheet", "isolate", "cr
#: track- / language-scoped tools (documented; keep in sync when registering a new one)
SCOPED_TOOLS = {
"joint_sweep", # articulated_object
- "shader_probe", "scene_probe", "scene_views", # scene_threejs
+ "shader_probe", "scene_probe", "scene_views", "check_placement", # scene_threejs
"gl_probe", "gl_frames", # graphics (glsl_shader / opengl_python)
"texture_pass", "texture_preview", # object tracks (texturing)
}